From 87cc90ffb1d064275f8c6447d7e929bb8d72fa5e Mon Sep 17 00:00:00 2001 From: SimplifiedPrivacy Date: Sat, 7 Nov 2026 12:35:02 -0500 Subject: [PATCH] Transition to using protocol enums and the protocol attribute in profiles, and away from connection.code --- core/controllers/ConnectionController.py | 140 ------------------ .../controllers/profile_state/data_filters.py | 2 +- core/errors/pydantic_errors.py | 17 +++ .../state_management/state_poll_loop.py | 4 +- core/models/BaseProfile.py | 23 +++ core/models/enum_models.py | 1 + .../connection_enable.py | 20 +-- .../location_evaluation.py | 3 +- .../networking/session/session_networking.py | 2 +- .../encrypted_proxy/configure_singbox.py | 53 +++---- core/services/profiles/model_manipulator.py | 28 +++- core/services/profiles/update_profile.py | 73 ++++----- .../subscriptions_by_protocol.py | 2 +- .../using_tickets/use_ticket_orchestrator.py | 2 +- 14 files changed, 134 insertions(+), 236 deletions(-) create mode 100644 core/errors/pydantic_errors.py diff --git a/core/controllers/ConnectionController.py b/core/controllers/ConnectionController.py index d117273..a096e14 100644 --- a/core/controllers/ConnectionController.py +++ b/core/controllers/ConnectionController.py @@ -14,8 +14,6 @@ from collections.abc import Callable from core.Constants import Constants from core.Errors import ConnectionUnprotectedError, ConnectionTerminationError, CommandNotFoundError from core.controllers.ConfigurationController import ConfigurationController -# from core.controllers.ProfileController import ProfileController -# from core.controllers.SessionStateController import SessionStateController from core.controllers.SystemStateController import SystemStateController from core.models.BaseProfile import ProfileType from core.models.session.SessionProfile import SessionProfile @@ -35,8 +33,6 @@ import subprocess import tempfile import time from enum import Enum -# import sys -# import re class ConnectionController: @@ -63,72 +59,6 @@ class ConnectionController: return None - # @staticmethod - # def establish_session_connection(profile: SessionProfile, ignore: tuple[type[Exception]] = (), connection_observer: Optional[ConnectionObserver] = None, ticket_observer: Optional[TicketObserver] = None): - - # session_directory = tempfile.mkdtemp(prefix='hv-') - # session_state = SessionStateController.get_or_new(profile.id) - - # port_number = None - # proxy_port_number = None - - # # this is a check from SessionConnection of if there's a systemwide with mask - # if profile.connection.is_unprotected(): - - # if not system_uses_wireguard_interface(): - - # if not ConnectionUnprotectedError in ignore: - # raise ConnectionUnprotectedError('Connection unprotected while the system is not using a WireGuard interface.') - # else: - # from core.services.profiles.profile_connections import disable_profile - # disable_profile(profile=profile, connection_observer=connection_observer, ticket_observer=ticket_observer) - - - # if profile.connection.code == 'tor': - - # port_number = ConnectionService.get_random_available_port_number() - # ConnectionController.establish_tor_session_connection(port_number, connection_observer=connection_observer) - - # session_state.network_port_numbers.tor.append(port_number) - - # elif profile.connection.code == 'wireguard': - - # if ConfigurationController.get_endpoint_verification_enabled(): - # verify_wireguard_endpoint(profile, ignore=ignore) - - # port_number = ConnectionService.get_random_available_port_number() - # ConnectionController.establish_wireguard_session_connection(profile, session_directory, port_number) - # session_state.network_port_numbers.wireguard.append(port_number) - - # if profile.connection.masked: - - # while proxy_port_number is None or proxy_port_number == port_number: - # proxy_port_number = ConnectionService.get_random_available_port_number() - - # ConnectionController.establish_proxy_session_connection(profile, session_directory, port_number, proxy_port_number) - # session_state.network_port_numbers.proxy.append(proxy_port_number) - - # # if not profile.connection.is_unprotected(): - - # if profile.connection.code == 'wireguard': - # test_result = test_session_ip(port=port_number, profile_id=profile.id, protocol=ProtocolChoice.WIREGUARD, connection_observer=connection_observer) - # if test_result.valid: - # logger.info("Connection established.") - # if connection_observer: - # connection_observer.notify("connected", "Confirmed") - # else: - # logger.error(test_result.message) - # return test_result.wrap("Unable to connect in ConnectionController.") - - # elif profile.connection.code == 'tor': - # await_connection(proxy_port_number or port_number, connection_observer=connection_observer) - - - # SessionStateController.update_or_create(session_state) - - # return proxy_port_number or port_number - - @staticmethod def establish_tor_connection(connection_observer: Optional[ConnectionObserver] = None): try: @@ -143,11 +73,6 @@ class ConnectionController: if connection_observer is not None: connection_observer.notify('custom_message', "Tor Can't Initialize") - # @staticmethod - # def terminate_tor_connection(): - - # tor_module = TorModule(Constants.HV_TOR_STATE_HOME) - # tor_module.stop_service() @staticmethod def establish_tor_session_connection(port_number: int, connection_observer: Optional[ConnectionObserver] = None) -> Result: @@ -169,23 +94,6 @@ class ConnectionController: tor_module = TorModule(Constants.HV_TOR_STATE_HOME) tor_module.destroy_session(port_number) - # @staticmethod - # def establish_wireguard_session_connection(profile: SessionProfile, session_directory: str, port_number: int): - - # if not profile.has_wireguard_configuration(): - # raise FileNotFoundError('Web service did not give us a WireGuard configuration, meaning the location is likely down.') - - # wireguard_session_directory = f'{session_directory}/wireguard' - # Path(wireguard_session_directory).mkdir(exist_ok=True, mode=0o700) - - # wireproxy_configuration_file_path = f'{wireguard_session_directory}/wireproxy.conf' - # Path(wireproxy_configuration_file_path).touch(exist_ok=True, mode=0o600) - - # with open(wireproxy_configuration_file_path, 'w') as wireproxy_configuration_file: - # wireproxy_configuration_file.write(f'WGConfig = {profile.get_wireguard_configuration_path()}\n\n[Socks5]\nBindAddress = 127.0.0.1:{str(port_number)}\n') - - # return subprocess.Popen((f'{Constants.HV_RUNTIME_DATA_HOME}/wireproxy/wireproxy', '-c', wireproxy_configuration_file_path), stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) - @staticmethod def establish_proxy_session_connection(profile: SessionProfile, session_directory: str, port_number: int, proxy_port_number: int) -> Result: @@ -249,51 +157,3 @@ class ConnectionController: return task_output - -# def start_tor_session_networking( -# port_number: int, -# session_directory: str, -# session_state: SessionState, -# profile: SessionProfile, -# ignore: tuple[type[Exception]] = (), -# connection_observer: Optional[ConnectionObserver] = None -# ) -> Result: - -# print("Starting a Tor Session Profile") -# proxy_port_number = None - -# tor_connected = ConnectionController.establish_tor_session_connection(port_number, connection_observer=connection_observer) -# if not tor_connected.valid: -# return tor_connected.wrap("Failed to start Tor, for Tor->socks5") - -# session_state.network_port_numbers.tor.append(port_number) - -# print(f"Started Tor connection on port {port_number}") - -# if profile.connection.masked: - -# while proxy_port_number is None or proxy_port_number == port_number: -# proxy_port_number = ConnectionService.get_random_available_port_number() - -# sock_proxy_result = ConnectionController.establish_proxy_session_connection(profile, session_directory, port_number, proxy_port_number) -# if not sock_proxy_result.valid: -# # Kill the underlying Tor right here: -# terminate_tor_session_connection(port_number=port_number) -# return sock_proxy_result.wrap("We were able to start Tor, but not the socks5 proxy masking on top of it.") - -# network_process = sock_proxy_result.data -# session_state.network_port_numbers.proxy.append(proxy_port_number) - -# # Update in memory repo, -# SessionStateController.update_or_create(session_state) -# SessionStateController.add_process(profile_id=profile.id, process_type=ProcessType.NETWORK, process=network_process) - -# print("Awaiting the connection..") -# await_connection(proxy_port_number or port_number, connection_observer=connection_observer) - -# print("Updating state..") -# SessionStateController.update_or_create(session_state) - -# print("Returning final proxy port") -# final_proxy_port = proxy_port_number or port_number -# return Result(valid=True, data=final_proxy_port) diff --git a/core/controllers/profile_state/data_filters.py b/core/controllers/profile_state/data_filters.py index 7fae995..7bc4ba7 100644 --- a/core/controllers/profile_state/data_filters.py +++ b/core/controllers/profile_state/data_filters.py @@ -73,7 +73,7 @@ def get_plans_for_profile(profile_id: int) -> Result: return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT) # Get Protocol for that profile: - chosen_protocol = ProtocolChoice(profile.connection.code) + chosen_protocol = profile.protocol # create or get the singleton: billing_data = PaymentData(instance_id=profile_id) diff --git a/core/errors/pydantic_errors.py b/core/errors/pydantic_errors.py new file mode 100644 index 0000000..4b1c506 --- /dev/null +++ b/core/errors/pydantic_errors.py @@ -0,0 +1,17 @@ +from core.errors.logger import logger + +from pydantic import ValidationError + +def get_failed_validation_fields(e: ValidationError) -> list: + missing_fields = [] + for error in e.errors(): + if error['type'] == 'missing': + error_msg = f"Required field '{error['loc'][0]}' is missing" + missing_fields.append(error_msg) + logger.error(error_msg) + else: + error_msg = f"Field '{error['loc'][0]}' error: {error['msg']}" + missing_fields.append(error_msg) + logger.error(error_msg) + + return missing_fields \ No newline at end of file diff --git a/core/infrastructure/state_management/state_poll_loop.py b/core/infrastructure/state_management/state_poll_loop.py index 7d4b37b..b4a8052 100644 --- a/core/infrastructure/state_management/state_poll_loop.py +++ b/core/infrastructure/state_management/state_poll_loop.py @@ -2,7 +2,7 @@ from core.infrastructure.thread_dispatch import MainThreadDispatcher from core.infrastructure.global_state import ProfileStateRepository, ProcessType, LIST_OF_PROCESSES from core.controllers.SessionStateController import SessionStateController from core.controllers.ProfileController import ProfileController -from core.models.enum_models import ProtocolChoice +# from core.models.enum_models import ProtocolChoice from core.errors.logger import logger import threading @@ -17,7 +17,7 @@ def actually_kill_it(profile_id): return # Remove the dead handle from the repo so we stop polling it - result = SessionStateController.kill_session_profile(profile_id=profile_id, protocol=ProtocolChoice(profile.connection.code)) + result = SessionStateController.kill_session_profile(profile_id=profile_id, protocol=profile.protocol) if not result.valid: SessionStateController.scortched_earth_kill_profile(profile_id) diff --git a/core/models/BaseProfile.py b/core/models/BaseProfile.py index e20d23f..8951469 100644 --- a/core/models/BaseProfile.py +++ b/core/models/BaseProfile.py @@ -18,6 +18,29 @@ class ProfileType(str, Enum): SESSION = "session" SYSTEM = "system" +SYSTEMWIDE_CHOICES = [ProtocolChoice.WIREGUARD, ProtocolChoice.HYSTERIA2, ProtocolChoice.VLESS] +SESSION_CHOICES = [ProtocolChoice.WIREGUARD, ProtocolChoice.TOR, ProtocolChoice.SOCK5_PROXY] + +PROTOCOL_CHOICES = { + ProfileType.SYSTEM: SYSTEMWIDE_CHOICES, + ProfileType.SESSION: SESSION_CHOICES +} + +CONFIG_NAME = { + ProtocolChoice.WIREGUARD: "wg.conf", + ProtocolChoice.TOR: "proxy.json", + ProtocolChoice.SOCK5_PROXY: "proxy.json", + ProtocolChoice.HYSTERIA2: "proxy.json", + ProtocolChoice.VLESS: "proxy.json" +} + +SYSTEM_WIDE_BACKUP_CONFIG_NAME = { + ProtocolChoice.WIREGUARD: "wg.conf.bak", + ProtocolChoice.HYSTERIA2: "proxy.json.bak", + ProtocolChoice.VLESS: "proxy.json.bak" +} + + @dataclass_json @dataclass class BaseProfile(ABC): diff --git a/core/models/enum_models.py b/core/models/enum_models.py index 9ce2f5a..db2b2ca 100644 --- a/core/models/enum_models.py +++ b/core/models/enum_models.py @@ -11,6 +11,7 @@ class ProtocolChoice(StrEnum): SINGBOX_PROTOCOLS = [ProtocolChoice.HYSTERIA2, ProtocolChoice.VLESS] + class Currency(Enum): MONERO = "monero" BITCOIN = "bitcoin" diff --git a/core/services/networking/general_connection_tools/connection_enable.py b/core/services/networking/general_connection_tools/connection_enable.py index 97816fb..263052a 100644 --- a/core/services/networking/general_connection_tools/connection_enable.py +++ b/core/services/networking/general_connection_tools/connection_enable.py @@ -1,3 +1,4 @@ +from core.models.enum_models import ProtocolChoice, SINGBOX_PROTOCOLS from core.services.networking.systemwide.encrypted_proxy.launch_proxy import launch_encrypted_proxy # from core.services.networking.general_connection_tools.location_evaluation import check_if_location_is_up # from core.services.networking.api_requests.ApiResponseModel import BackoffStrategy @@ -48,7 +49,7 @@ def establish_connection( # ========================================= # HYSTERIA2 & VLESS # ========================================= - if profile.connection.code in ("hysteria2", "vless"): + if profile.protocol in SINGBOX_PROTOCOLS: logger.info("Pulling encrypted proxies off the main flow..") try: return launch_encrypted_proxy(profile, connection_observer) @@ -65,13 +66,13 @@ def establish_connection( return sock_proxy_result.wrap("Connection Enable Router failed to configure a regular socks5 proxy") logger.info("[CONNECTION] Checking Wireguard configuration..") - if profile.connection.code == "wireguard": + if profile.protocol == ProtocolChoice.WIREGUARD: configure_result = _ensure_wireguard_configured(profile, connection_observer) if not configure_result.valid: return configure_result.wrap("Got interupted from connection by a failed setup.") - if profile.connection.code == "wireguard" and profile.type == ProfileType.SYSTEM: + if profile.protocol == ProtocolChoice.WIREGUARD and profile.type == ProfileType.SYSTEM: logger.info("Doing a systemwide WG connection..") return establish_system_connection(profile, ignore, connection_observer, ticket_observer) @@ -121,7 +122,7 @@ def _ensure_wireguard_configured( #----------------------- # Is Wireguard #----------------------- - if profile.connection.code != "wireguard": + if profile.protocol != ProtocolChoice.WIREGUARD: logger.info("Not a wireguard profile") return @@ -188,17 +189,8 @@ def __should_renegotiate(profile: Union[SessionProfile, SystemProfile]): if not profile.has_subscription(): raise MissingSubscriptionError() - if profile.connection.code == "wireguard" and profile.has_wireguard_configuration(): + if profile.protocol == ProtocolChoice.WIREGUARD and profile.has_wireguard_configuration(): if profile.subscription.has_been_activated(): return True else: return False - - - - -# Enums -# if profile.type == ProfileType.SYSTEM: -# print("This is a system profile") -# elif profile.type == ProfileType.SESSION: -# print("This is a session profile") diff --git a/core/services/networking/general_connection_tools/location_evaluation.py b/core/services/networking/general_connection_tools/location_evaluation.py index 610d1d7..d93abe2 100644 --- a/core/services/networking/general_connection_tools/location_evaluation.py +++ b/core/services/networking/general_connection_tools/location_evaluation.py @@ -37,8 +37,7 @@ def check_if_location_is_up(profile: Profile, connection_observer: ConnectionObs location_id = profile.location.id location_name = profile.location.country_name profile_type = profile.type - string_protocol = profile.connection.code - protocol = ProtocolChoice(string_protocol) + protocol = profile.protocol print(f""" profile_id: {profile_id} diff --git a/core/services/networking/session/session_networking.py b/core/services/networking/session/session_networking.py index 2ae9871..2a01ba6 100644 --- a/core/services/networking/session/session_networking.py +++ b/core/services/networking/session/session_networking.py @@ -73,7 +73,7 @@ def start_session_networking( # ================================= # PREPARE PRE-REQS # ================================= - protocol = ProtocolChoice(profile.connection.code) + protocol = profile.protocol session_directory = tempfile.mkdtemp(prefix='hv-') session_state = SessionStateController.get_or_new(profile.id) diff --git a/core/services/networking/systemwide/encrypted_proxy/configure_singbox.py b/core/services/networking/systemwide/encrypted_proxy/configure_singbox.py index 2922f7e..0c559e8 100644 --- a/core/services/networking/systemwide/encrypted_proxy/configure_singbox.py +++ b/core/services/networking/systemwide/encrypted_proxy/configure_singbox.py @@ -1,7 +1,8 @@ -from core.models.orm_calls.location_calls import get_profile_location_data +from core.errors.pydantic_errors import get_failed_validation_fields from core.services.networking.tor_tools import ports from core.services.networking.httpx import connect - +from core.models.enum_models import ProtocolChoice +from core.models.BaseProfile import SYSTEM_WIDE_BACKUP_CONFIG_NAME from core.services.networking.systemwide.encrypted_proxy.hysteria_config import build_hysteria_config from core.services.networking.systemwide.encrypted_proxy.vless_config import build_vless_config, parse_vless_link from core.utils.basic_operations.write_or_read_from_json import write_json_to_file @@ -12,11 +13,11 @@ from core.utils.basic_operations.does_file_exist import does_file_exist # Models from core.models.pydantic_models.HysteriaData import HysteriaData from core.models.pydantic_models.VlessData import VlessData -from core.services.networking.api_requests.ApiResponseModel import ApiResponse, ErrorType +# from core.services.networking.api_requests.ApiResponseModel import ApiResponse, ErrorType from core.models.Result import Result, ResultError from core.models.session.SessionProfile import SessionProfile from core.models.system.SystemProfile import SystemProfile -from core.models.manage.session_management import get_session +# from core.models.manage.session_management import get_session from core.models.manage import pydantic_manager # errors & observers @@ -28,10 +29,10 @@ from core.Errors import ProfileModificationError, CommandNotFoundError, MissingS # generic from pydantic import ValidationError from typing import Union, Optional -import os +# import os import shutil -import subprocess -import json +# import subprocess +# import json def configure_singbox( @@ -49,7 +50,7 @@ def configure_singbox( ################################### # PREP PAYLOADS ################################### - protocol = profile.connection.code + protocol = profile.protocol profile_sudo_filepath = f"{profile.get_system_config_path()}/proxy.json" profile_regular_filepath = profile.get_config_path() @@ -62,7 +63,7 @@ def configure_singbox( logger.info("getting config..") config_results = post_operator_proxy( billing_code=profile.subscription.billing_code, - protocol=protocol, + protocol=protocol.value, connection_observer=connection_observer ) @@ -98,7 +99,7 @@ def configure_singbox( random_port = ports.get_random_available_port() # HYSTERIA - if protocol == "hysteria2": + if protocol == ProtocolChoice.HYSTERIA2: real_config = build_hysteria_config( username=validated_data.username, password=validated_data.password, @@ -108,7 +109,7 @@ def configure_singbox( ) # VLESS - elif protocol == "vless": + elif protocol == ProtocolChoice.VLESS: # parse the link: vless = parse_vless_link(validated_data.links) @@ -136,7 +137,8 @@ def configure_singbox( saved_it = attach_config_to_sudo_folder( config_data=real_config, sudo_filepath=profile_sudo_filepath, - backup_folder=profile_regular_filepath + backup_folder=profile_regular_filepath, + protocol=protocol ) if saved_it: @@ -146,17 +148,16 @@ def configure_singbox( -def verify_proxy_data(data: dict, protocol: str) -> Result: +def verify_proxy_data(data: dict, protocol: ProtocolChoice) -> Result: """ Verify the API's proxy details using a Pydantic model Works for both Hysteria2 & VLESS """ - # session = get_session() try: - if protocol == "hysteria2": + if protocol == ProtocolChoice.HYSTERIA2: validated_data = HysteriaData(**data) - elif protocol == "vless": + elif protocol == ProtocolChoice.VLESS: validated_data = VlessData(**data) else: return Result(valid=False, error_type=ResultError.INVALID_INPUT, message="Unsupported protocol.") @@ -165,31 +166,23 @@ def verify_proxy_data(data: dict, protocol: str) -> Result: return Result(valid=True, data=validated_data) except ValidationError as e: - missing_fields = [] - for error in e.errors(): - if error['type'] == 'missing': - error_msg = f"Required field '{error['loc'][0]}' is missing" - missing_fields.append(error_msg) - logger.error(error_msg) - else: - error_msg = f"Field '{error['loc'][0]}' error: {error['msg']}" - missing_fields.append(error_msg) - logger.error(error_msg) - + missing_fields = get_failed_validation_fields(e) return Result(valid=False, error_type=ResultError.INVALID_API_REPLY, message=f"Missing fields: {missing_fields}") def attach_config_to_sudo_folder( config_data: dict, sudo_filepath: str, - backup_folder: str + backup_folder: str, + protocol: ProtocolChoice ) -> bool: if shutil.which('pkexec') is None: raise CommandNotFoundError('pkexec') logger.info("About to save to backup config path") - backup_path = f'{backup_folder}/backup.conf.bak' + backup_file_name = SYSTEM_WIDE_BACKUP_CONFIG_NAME[protocol] + backup_path = f'{backup_folder}/{backup_file_name}' saved_backup = write_json_to_file(data=config_data, filepath=backup_path) if not saved_backup: @@ -249,6 +242,8 @@ def post_operator_proxy(billing_code: str, protocol: str, connection_observer: C ################################### # VERIFY LOCATION ################################### +# from core.models.orm_calls.location_calls import get_profile_location_data + # location_country_code= data.get('location_country_code') # location_city_code= data.get('location_city_code') # matched_location = get_profile_location_data( diff --git a/core/services/profiles/model_manipulator.py b/core/services/profiles/model_manipulator.py index 17acde8..afd9e0d 100644 --- a/core/services/profiles/model_manipulator.py +++ b/core/services/profiles/model_manipulator.py @@ -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.orm_calls.location_calls import LocationCache from core.models.BaseProfile import BaseProfile as Profile -from core.models.BaseProfile import ProfileType +from core.models.BaseProfile import ProfileType, CONFIG_NAME, SYSTEM_WIDE_BACKUP_CONFIG_NAME 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.models.orm_calls.application_version_calls import get_application_version @@ -19,7 +19,7 @@ import json import os import re import shutil - +from pathlib import Path def get_config_path(id: int): return f'{Constants.HV_PROFILE_CONFIG_HOME}/{str(id)}' @@ -306,4 +306,28 @@ def delete(profile: Profile) -> Result: shutil.rmtree(get_config_path(profile.id), ignore_errors=True) shutil.rmtree(get_data_path(profile.id), ignore_errors=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) \ No newline at end of file diff --git a/core/services/profiles/update_profile.py b/core/services/profiles/update_profile.py index 957f0e3..174f3e7 100644 --- a/core/services/profiles/update_profile.py +++ b/core/services/profiles/update_profile.py @@ -2,18 +2,17 @@ from core.errors.logger import logger 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.profiles.model_manipulator import delete_connection_configs from core.controllers.ProfileController import ProfileController from core.models.BaseProfile import BaseProfile as Profile -from core.models.BaseProfile import ProfileType +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.orm_models.Location import Location -SYSTEMWIDE_CHOICES = ['wireguard', 'hysteria2', 'vless'] -SESSION_CHOICES = ['wireguard', 'tor', 'proxy'] - """ Steps: 1) Looks up the profile by id number @@ -33,7 +32,8 @@ Raises Errors: def update_profile( profile_id: int, key: str, - new_value: str) -> Result: + new_value: str +) -> Result: # final_data = None logger.info(f"[UPDATE PROFILE] Recieved profile_id {profile_id}, key {key}, and new_value {new_value}.") @@ -91,7 +91,7 @@ def update_profile( country_code=country_code, city_code=city_code ) - pre_existing_protocol = profile.connection.code + pre_existing_protocol = profile.protocol if new_location.supports_protocol(pre_existing_protocol): profile.location = new_location else: @@ -113,10 +113,19 @@ def update_profile( def change_protocol(profile: Profile, new_value: str) -> Result: - logger.info(f"changing the protcol to {new_value}") + """Changes the profile's protocol, after evaluating that it's a valid choice.""" + logger.info(f"evaluating changing the protocol to {new_value}") + + # ============= VALID ENUM ============= + if not is_valid_protocol(new_value): + error_msg = "Invalid protocol choice." + logger.error(error_msg) + return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT) + + protocol_choice = ProtocolChoice(new_value) # ============= SAME VALUE ============= - if profile.connection.code == new_value: + if profile.protocol == protocol_choice: error_msg = f"This is NOT changing the protocol, it already was {new_value}" logger.error(error_msg) return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT) @@ -131,46 +140,24 @@ def change_protocol(profile: Profile, new_value: str) -> Result: return Result(valid=False, message=error_msg, error_type=ResultError.WRONG_LOCATION) logger.info("Passed location check") - # ============= SYSTEMWIDE ============= + # ============= By Type ============= logger.info(f"Evaluating the profile's connection type of {profile.type}") - if profile.type == ProfileType.SYSTEM: - return change_systemwide_connection(profile, new_value) - else: - return change_session_connection(profile, new_value) - - -def change_session_connection(profile: Profile, new_value: str) -> Result: - logger.info("This is a session profile") - if new_value not in SESSION_CHOICES: - error_msg = f"{new_value} is not a session choice" + choices_for_this_profile = PROTOCOL_CHOICES[profile.type] + if protocol_choice not in choices_for_this_profile: + error_msg = f"{new_value} is not a {profile.type.value} choice" logger.error(error_msg) return Result(valid=False, message=error_msg, error_type=ResultError.NOT_SUPPORTED) - profile.connection.code = new_value - profile.protocol = new_value + # ============= DELETE PAST CONFIGS ============= + deleted_configs = delete_connection_configs(profile) + if not deleted_configs.valid: + return deleted_configs.wrap("Couldn't change protocol because of issues deleting the previous configs.") - if new_value == 'wireguard': + # ============= SET NEW CHOICES ============= + profile.connection.code = new_value # legacy + profile.protocol = protocol_choice + + if profile.type == ProfileType.SESSION and protocol_choice == ProtocolChoice.WIREGUARD: profile.connection.masked = False return Result(valid=True, data=profile) - - -def change_systemwide_connection(profile: Profile, new_value: str) -> Result: - logger.info("This is a systemwide profile") - if not new_value in SYSTEMWIDE_CHOICES: - error_msg = f"{new_value} is not a systemwide choice" - logger.error(error_msg) - return Result(valid=False, message=error_msg, error_type=ResultError.NOT_SUPPORTED) - - # REMOVE PAST CONFIG: - logger.info("removing the config from sudo slot..") - removed = remove_sudo_config(profile) - if not removed.valid: - error_msg = "You must give permission to delete the previous protocol's config file." - return Result(valid=False, message=error_msg, error_type=ResultError.PERMISSION) - - # UPDATE PROFILE - logger.info("Literally updating the value..") - profile.connection.code = new_value - profile.protocol = new_value - return Result(valid=True, data=profile) diff --git a/core/services/subscriptions/subscriptions_by_protocol.py b/core/services/subscriptions/subscriptions_by_protocol.py index 0dadc69..9cc312b 100644 --- a/core/services/subscriptions/subscriptions_by_protocol.py +++ b/core/services/subscriptions/subscriptions_by_protocol.py @@ -402,7 +402,7 @@ def create_individual_invoice(payment_cycle: OverallPaymentCycle, connection_obs # make sure the protocol is saved in the singleton already, if not billing_data.protocol_choice: # If not, then get the Protocol for that profile: - billing_data.protocol_choice = ProtocolChoice(profile.connection.code) + billing_data.protocol_choice = profile.protocol # location billing_data.location_id = profile.location.id diff --git a/core/services/using_tickets/use_ticket_orchestrator.py b/core/services/using_tickets/use_ticket_orchestrator.py index 569b173..951924a 100644 --- a/core/services/using_tickets/use_ticket_orchestrator.py +++ b/core/services/using_tickets/use_ticket_orchestrator.py @@ -120,7 +120,7 @@ def use_ticket_orchestrator( return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg) location_id = profile.location.id - protocol_choice = ProtocolChoice(profile.connection.code) + protocol_choice = profile.protocol PRE_REQS = [profile_id, location_id, protocol_choice, which_ticket] if None in PRE_REQS: return Result(valid=False, error_type=ResultError.MISSING_DATA, message="You are missing the profile data to use a ticket with.")