From 02cc80b152d47c5b16e99aa22abc987506f142c3 Mon Sep 17 00:00:00 2001 From: SimplifiedPrivacy Date: Thu, 5 Nov 2026 11:19:40 -0500 Subject: [PATCH] Creation of Profile objects now happens in core, instead of GUI --- core/controllers/ProfileController.py | 112 ++++++++++++++++-- core/infrastructure/plumbing.py | 1 + core/models/BaseProfile.py | 42 ++++--- core/models/enum_models.py | 4 + .../orm_calls/application_version_calls.py | 18 +++ core/models/orm_calls/location_calls.py | 18 +++ core/models/session/SessionProfile.py | 26 ++-- core/observers/Notifications.py | 1 + .../networking/general_connection_tools/ip.py | 3 +- .../recovery_tools.py | 4 +- .../networking/session/session_networking.py | 10 +- .../general_tools/test_any_protocol.py | 3 +- core/services/profiles/ProfileRepository.py | 87 +++++++++++--- core/services/profiles/create_objects.py | 106 +++++++++++++++++ core/services/profiles/filter_protocols.py | 40 +++++++ core/services/profiles/profile_connections.py | 14 ++- 16 files changed, 426 insertions(+), 63 deletions(-) create mode 100644 core/services/profiles/create_objects.py create mode 100644 core/services/profiles/filter_protocols.py diff --git a/core/controllers/ProfileController.py b/core/controllers/ProfileController.py index bc3b3c2..d44552e 100644 --- a/core/controllers/ProfileController.py +++ b/core/controllers/ProfileController.py @@ -1,7 +1,13 @@ +from core.services.profiles.create_objects import create_profile_object from core.services.profiles.ProfileRepository import ProfileRepository +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 # from core.services.subscriptions import subscriptions from core.models.Result import Result, ResultError from core.errors.logger import logger +from core.models.system.SystemConnection import SystemConnection +from core.models.session.SessionConnection import SessionConnection +from core.observers.Notifications import Notifications, EventType from core.models.BaseProfile import BaseProfile as Profile @@ -32,20 +38,11 @@ class ProfileController: def get_all(): return ProfileController._repo.get_all() - @staticmethod - def create(profile: Union[SessionProfile, SystemProfile], profile_observer: ProfileObserver = None): - # Call the helper with the 'created' event - ProfileController._save_and_sync(profile, 'created', profile_observer) - - @staticmethod - def update(profile: Union[SessionProfile, SystemProfile], profile_observer: ProfileObserver = None): - # Call the helper with the 'updated' event - ProfileController._save_and_sync(profile, 'updated', profile_observer) - @staticmethod def _save_and_sync(profile, event_type: str, observer: ProfileObserver = None): - """Private helper to handle the actual persistence and cache synchronization.""" + """Internal helper to handle the actual persistence and cache synchronization.""" # 1. Persist to disk + logger.info("Saving to disk.") profile.save() # 2. update cache to prevent drift @@ -55,6 +52,98 @@ class ProfileController: if observer is not None: observer.notify(event_type, profile) + @staticmethod + def create(potential_data: dict, profile_observer: ProfileObserver = None) -> Result: + + logger.info("Starting the creation of a new profile.") + + if not potential_data or not isinstance(potential_data, dict): + return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=f"The data to create the profile is not structured properly. It's type {type(potential_data)}") + + # profile_type = potential_data.get('Type', None) + # protocol = potential_data.get('Protocol', None).value + # location_id = potential_data.get('Location', None) + # location = get_profile_location_data(location_id) + # print(f"location is {type(location)}") + # name = potential_data.get('Name', None) + + # if not profile_type or not isinstance(profile_type, ProfileType): + # return Result(valid=False, error_type=ResultError.INVALID_INPUT, message="The data to create the profile is not structured properly. It's missing the type") + + # logger.info("Passed initial data screen.") + + # Get next id from the Repo, which confirms with what's on disk: + profile_id = ProfileController._repo.get_next_id() + logger.info(f"New profile id is {profile_id}") + + created_object = create_profile_object(profile_id=profile_id, potential_data=potential_data) + + if not created_object.valid: + return created_object.wrap("Failed to make profile object.") + + profile = created_object.data + + + # if profile_type == ProfileType.SESSION: + # # SESSION ONLY PRE-REQS + # resolution = potential_data.get('Resolution', None) + # app_id = potential_data.get('Browser', None) + # if resolution and app_id: + # logger.info(f"Creating a session profile with {resolution} and {app_id}") + # else: + # error_msg = "Missing the resolution or app version" + # logger.error(error_msg) + # return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg) + + # # Lookup App: + # application_version = get_application_by_id(app_id) + # if not application_version: + # error_msg = "Failed to find the app by id" + # logger.error(error_msg) + # return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg) + + # logger.info(f"application_version is {application_version}") + # connection = SessionConnection(protocol) + + # profile = SessionProfile( + # id=profile_id, + # name=name, + # subscription=None, + # type=ProfileType.SESSION, + # location=location, + # resolution=resolution, + # application_version=application_version, + # connection=connection + # ) + + # elif profile_type == ProfileType.SYSTEM: + # connection = SystemConnection(protocol) + # profile = SystemProfile( + # id=profile_id, + # name=name, + # type=ProfileType.SYSTEM, + # subscription=None, + # location=location, + # connection=connection + # ) + + # else: + # error_msg = f"Invalid profile type of {profile_type} used to create a profile." + # logger.error(error_msg) + # return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg) + + # Save and sync with the repo. + print(f"profile type is {type(profile)}") + ProfileController._save_and_sync(profile, 'created', profile_observer) + print("saved it.") + Notifications.emit(EventType.PROFILES_CHANGED) + return Result(valid=True) + + @staticmethod + def update(profile: Union[SessionProfile, SystemProfile], profile_observer: ProfileObserver = None): + # Call the helper with the 'updated' event + ProfileController._save_and_sync(profile, 'updated', profile_observer) + @staticmethod def delete(profile: Union[SessionProfile, SystemProfile], profile_observer: ProfileObserver = None): @@ -69,7 +158,6 @@ class ProfileController: # 3. update cache with the temp variable to prevent drift ProfileController._repo.invalidate(profile_id=profile_id) - @staticmethod def what_type_is_profile(profile_id: int) -> ProfileType: all_data = ProfileController._repo.get_all() diff --git a/core/infrastructure/plumbing.py b/core/infrastructure/plumbing.py index 346e722..6e13b6f 100644 --- a/core/infrastructure/plumbing.py +++ b/core/infrastructure/plumbing.py @@ -97,6 +97,7 @@ class ThreadPlumbing: # self.kwargs.update(ui_caller=self.ui_caller) logger.info("Executing a double dip function.") self.execute_already_on_background(task=double_dip_function) + return else: logger.info(f"Result asked for a double dip, but there's no valid function to do so. double_dip_function is {double_dip_function}") diff --git a/core/models/BaseProfile.py b/core/models/BaseProfile.py index d4ea4e9..61dd020 100644 --- a/core/models/BaseProfile.py +++ b/core/models/BaseProfile.py @@ -109,7 +109,7 @@ class BaseProfile(ABC): return type(self).__name__ == 'SystemProfile' - def save(self: Self, app_version_dict: dict = None): + def save(self, app_version_dict: dict = None): """ First warn via the logs, if the caller is bypassing the Cache and accessing it directly. Then persist changes in the profile/model to disk. @@ -120,28 +120,33 @@ class BaseProfile(ABC): # 1. Get the call stack # stack[0] is this current 'save' method # stack[1] is the immediate caller - stack = inspect.stack() - caller_frame = stack[1] - - caller_function_name = caller_frame.function - caller_module_name = caller_frame.filename # Full path to the file - - # 2. Only the Repo or Controller is allowed to save - allowed_callers = ['create', 'update_cache'] - is_allowed_file = "core/controllers/ProfileController.py" in caller_module_name or "core/services/profiles/ProfileRepository.py" in caller_module_name - if caller_function_name not in allowed_callers and not is_allowed_file: - logger.warning( - f"ARCHITECTURE VIOLATION: .save() called directly from " - f"function '{caller_function_name}' in {caller_module_name}. " - f"Please route this through ProfileController to ensure cache integrity." - ) + # stack = inspect.stack() + # caller_frame = stack[1] + + # caller_function_name = caller_frame.function + # caller_module_name = caller_frame.filename # Full path to the file + + # # 2. Only the Repo or Controller is allowed to save + # allowed_callers = ['create', 'update_cache'] + # is_allowed_file = "core/controllers/ProfileController.py" in caller_module_name or "core/services/profiles/ProfileRepository.py" in caller_module_name + + # if caller_function_name not in allowed_callers and not is_allowed_file: + # logger.warning( + # f"ARCHITECTURE VIOLATION: .save() called directly from " + # f"function '{caller_function_name}' in {caller_module_name}. " + # f"Please route this through ProfileController to ensure cache integrity." + # ) #-------------------------- # Actual Save #-------------------------- # === SERIALIZATION === + + print(f"PARENT: self is {type(self)}") + print(f"PARENT: self.id is {type(self.id)}") + print("I am here") config_dict = self.to_dict() # === LOCATION === @@ -294,6 +299,11 @@ class BaseProfile(ABC): # =========== SESSION =========== if 'application_version' in profile: profile['type'] = ProfileType.SESSION + + + if isinstance(profile['application_version'], ApplicationVersion): + print("It's already an app version") + if profile['application_version'] is not None: application_version = get_application_version( profile['application_version']['application_code'] or None, diff --git a/core/models/enum_models.py b/core/models/enum_models.py index 98bbb01..afa6d6e 100644 --- a/core/models/enum_models.py +++ b/core/models/enum_models.py @@ -40,3 +40,7 @@ def get_choice_list(model: Type[Enum]) -> list: def valid_enum(potential_candidate: str, enum_model: Type[Enum]) -> bool: return potential_candidate in [choice.value for choice in enum_model] + + +def get_list_of(enum_model: Type[Enum]): + return list(enum_model) diff --git a/core/models/orm_calls/application_version_calls.py b/core/models/orm_calls/application_version_calls.py index 2e20fd3..44bcace 100644 --- a/core/models/orm_calls/application_version_calls.py +++ b/core/models/orm_calls/application_version_calls.py @@ -69,3 +69,21 @@ def get_random_installed_app() -> Optional[ApplicationVersion]: list_of_data.remove(random_item) return None + + + +@safe_db_operation +def execute_get_app_by_id(app_id: int, session: Session) -> DatabaseOperation: + """Query for a specific application version""" + data = session.query(ApplicationVersion).filter( + ApplicationVersion.id == app_id).first() + return DatabaseOperation(valid=True, data=data) + + +def get_application_by_id(app_id: int) -> Optional[ApplicationVersion]: + database_object = execute_get_app_by_id(app_id) + if database_object.valid: + return database_object.data + else: + logger.error(f"Critical Database error with fetching data for app id {app_id}: {database_object.error_type} with {database_object.message}") + return None diff --git a/core/models/orm_calls/location_calls.py b/core/models/orm_calls/location_calls.py index 7f45dac..996d577 100644 --- a/core/models/orm_calls/location_calls.py +++ b/core/models/orm_calls/location_calls.py @@ -59,3 +59,21 @@ def get_random_location(filter_out_list: Optional[list] = None) -> Location: if random_pick not in filter_out_list: return random_pick + +@safe_db_operation +def execute_location_by_id(location_id: int, session: Session) -> DatabaseOperation: + location_object = session.execute( + select(Location) + .where((Location.id == location_id)) + ).scalar_one_or_none() + return location_object + +def get_profile_location_data(location_id: int) -> Location: + location_object = execute_location_by_id(location_id) + if location_object.valid: + return location_object.data + else: + critical_error = f"Got invalid SQL Query which could not be solved by the wrapper, with error message {location_object.message} and type {location_object.error_type}" + logger.error(critical_error) + print(critical_error) + return None \ No newline at end of file diff --git a/core/models/session/SessionProfile.py b/core/models/session/SessionProfile.py index 8272f08..62a7433 100644 --- a/core/models/session/SessionProfile.py +++ b/core/models/session/SessionProfile.py @@ -30,22 +30,30 @@ class SessionProfile(BaseProfile): def save(self): print("We are able to trigger save on the child session") - if 'application_version' in self._get_dirty_keys(): + # if 'application_version' in self._get_dirty_keys(): - persistent_state_path = f'{self.get_data_path()}/persistent-state' + # persistent_state_path = f'{self.get_data_path()}/persistent-state' - if os.path.isdir(persistent_state_path): - shutil.rmtree(persistent_state_path, ignore_errors=True) + # if os.path.isdir(persistent_state_path): + # shutil.rmtree(persistent_state_path, ignore_errors=True) - if 'location' in self._get_dirty_keys(): + # if 'location' in self._get_dirty_keys(): - self.__delete_proxy_configuration() - self.delete_wireguard_configuration() + # self.__delete_proxy_configuration() + # self.delete_wireguard_configuration() # === APPLICATION === - app_version_dict = self.application_version.convert_to_dict() - print(f"session child got {app_version_dict} as dict..") + print(f"self.application_version is {self.application_version}") + if isinstance(self.application_version, ApplicationVersion): + app_version_dict = self.application_version.convert_to_dict() + print(f"session child got {app_version_dict} as dict..") + else: + print("Unable to convert the dict.") + print(f"self.application_version type is {type(self.application_version)}") + return False + + print(f"CHILD: self is {type(self)}") super().save(app_version_dict=app_version_dict) def attach_proxy_configuration(self, proxy_configuration): diff --git a/core/observers/Notifications.py b/core/observers/Notifications.py index 1c97ebe..5e4a03b 100644 --- a/core/observers/Notifications.py +++ b/core/observers/Notifications.py @@ -13,6 +13,7 @@ class EventType(Enum): SHOW_POPUP = auto() RESUME_ACTIONS = auto() SYNC_COMPLETE = auto() + PROFILES_CHANGED = auto() class Notifications: _subscribers = {} diff --git a/core/services/networking/general_connection_tools/ip.py b/core/services/networking/general_connection_tools/ip.py index 78c91d4..4af8207 100644 --- a/core/services/networking/general_connection_tools/ip.py +++ b/core/services/networking/general_connection_tools/ip.py @@ -151,7 +151,7 @@ def test_with_threading(connection_observer: Optional[ConnectionObserver], port: http_start = time.time() result_queue = Queue() - def attempt_request(url: str, stop_sig: Event): # Pass the event here + def attempt_request(url: str, stop_sig: Event): # Passed event here transport = None if port: transport = httpx_socks.SyncProxyTransport( @@ -214,6 +214,7 @@ def test(connection_observer: Optional[ConnectionObserver], port: Optional[int] # with a proxy: if port: + print("Starting an async test..") return asyncio.run(async_test_orchestrator(endpoint_list, port, total_budget)) # without systemwide: diff --git a/core/services/networking/general_connection_tools/recovery_tools.py b/core/services/networking/general_connection_tools/recovery_tools.py index 507975a..cd0eeb7 100644 --- a/core/services/networking/general_connection_tools/recovery_tools.py +++ b/core/services/networking/general_connection_tools/recovery_tools.py @@ -6,8 +6,8 @@ from core.errors.logger import logger from functools import partial def just_reconnect(profile_id: int) -> Result: - print(f"Reconnecting profile_id {profile_id}..") - return Result(valid=True, double_dip=True, error_type=ResultError.RECONNECT) + print(f"Returning FALSE, to reconnect profile_id {profile_id}..") + return Result(valid=False, double_dip=True, error_type=ResultError.RECONNECT) def wipe_attempts_and_reconnect(recovery_stats: ConnectionRecovery)-> Result: diff --git a/core/services/networking/session/session_networking.py b/core/services/networking/session/session_networking.py index be476ed..c5a17f0 100644 --- a/core/services/networking/session/session_networking.py +++ b/core/services/networking/session/session_networking.py @@ -59,14 +59,16 @@ def start_session_networking( # already exhausted options, do they want to restart? if recovery_stats.reached_end_of_loop and not recovery_stats.bypass_attempts: + print("Offering recovery options") return offer_recovery_options(recovery_stats) # if they bypass the wipe, its a one-time thing: if recovery_stats.bypass_attempts: + print("Bypass is a one-time thing. Resetting") recovery_stats.bypass_attempts = False recovery_stats.attempts += 1 - current_try = recovery_stats.attempts + print(f"recovery_stats attempts: {recovery_stats.attempts}") # ================================= # PREPARE PRE-REQS @@ -81,7 +83,7 @@ def start_session_networking( port_number = ConnectionService.get_random_available_port_number() - notification = f"Connecting with try {current_try} on local port {port_number}" + notification = f"Try {recovery_stats.attempts} Connecting on {port_number}" Notifications.emit(EventType.STATUS_UPDATE, notification) print(notification) @@ -108,7 +110,9 @@ def start_session_networking( # EVALUATE # ================================= if not started_process.valid: - return started_process.wrap("Unable to even start the network connection.") + error_msg = "Unable to even start the network connection." + logger.error(error_msg) + return started_process.wrap(error_msg) network_process = started_process.data diff --git a/core/services/networking/systemwide/general_tools/test_any_protocol.py b/core/services/networking/systemwide/general_tools/test_any_protocol.py index 2bd64a1..60cd7e4 100644 --- a/core/services/networking/systemwide/general_tools/test_any_protocol.py +++ b/core/services/networking/systemwide/general_tools/test_any_protocol.py @@ -28,8 +28,9 @@ def test_session_ip(port: int, profile_id: int, protocol: ProtocolChoice, connec return Result(valid=False, error_type=ResultError.MISSING_DATA, message=error_msg) # reality: - logger.info(f"testing on port {port}") + logger.info(f"testing on port {port} for the expected_ip_address of {expected_ip_address}") ip_result = ip.test(connection_observer=connection_observer, port=port) + print(f"ip_result is {ip_result}") return compare_ips(ip_result=ip_result, expected_ip_address=expected_ip_address) diff --git a/core/services/profiles/ProfileRepository.py b/core/services/profiles/ProfileRepository.py index 729a50b..7a412be 100644 --- a/core/services/profiles/ProfileRepository.py +++ b/core/services/profiles/ProfileRepository.py @@ -20,29 +20,30 @@ class ProfileRepository: cls._instance._cache: Dict[int, any] = {} return cls._instance - def get(self, profile_id: int): - # 1. Check cache first - if profile_id in self._cache: - return self._cache[profile_id] + # def get(self, profile_id: int): + # # 1. Check cache first + # if profile_id in self._cache: + # return self._cache[profile_id] - # 2. Fallback to disk via the Model - profile = BaseProfile.find_by_id(profile_id) + # # 2. Fallback to disk via the Model + # profile = BaseProfile.find_by_id(profile_id) - # 3. Update cache for next time - if profile: - self._cache[profile_id] = profile + # # 3. Update cache for next time + # if profile: + # self._cache[profile_id] = profile - return profile + # return profile - def get_all(self): - # First, get the current list of IDs from the model, to avoid drift, from new files added to disk - all_profiles = BaseProfile.all() + # def get_all(self): + # # First, get the current list of IDs from the model, to avoid drift, from new files added to disk + # all_profiles = BaseProfile.all() - # Update our internal cache with everything currently on disk - for p in all_profiles: - self._cache[id] = p + # # Update our internal cache with everything currently on disk + # for p in all_profiles: + # self._cache[id] = p + # # self._cache[p.id] = p - return all_profiles + # return all_profiles def update_cache(self, profile): """Explicitly updates the cache to prevent drift after a save.""" @@ -52,3 +53,55 @@ class ProfileRepository: """Removes an item from cache if it's deleted from disk.""" self._cache.pop(profile_id, None) + # def get_next_id(self) -> int: + # # Step 1: Check against the current cache for the highest known ID + # next_id = max(self._cache.keys(), default=0) + 1 + + # # Step 2 & 3: Verify the ID doesn't exist on disk + # # We loop in case the cache is behind and the next sequential IDs are already taken + # while True: + # try: + # profile = BaseProfile.find_by_id(next_id) + # if profile is None: + # # Confirmation fails (it doesn't exist), so this ID is safe to use + # return next_id + # except Exception: + # # If the disk lookup itself fails, we treat it as the ID being available + # return next_id + + # next_id += 1 + + def get_next_id(self) -> int: + # Use the current cache to find a starting point for the next ID + next_id = max(self._cache.keys(), default=0) + 1 + + while True: + try: + profile = BaseProfile.find_by_id(next_id) + if profile is None: + return next_id + except Exception: + return next_id + + next_id += 1 + + def get(self, profile_id: int): + if profile_id in self._cache: + return self._cache[profile_id] + + profile = BaseProfile.find_by_id(profile_id) + + if profile: + self._cache[profile_id] = profile + + return profile + + def get_all(self) -> Dict[int, any]: + # BaseProfile.all() returns a dict { id: profile } + all_profiles_dict = BaseProfile.all() + + # Sync the cache with whatever is currently on disk + self._cache.update(all_profiles_dict) + + # Return the dict so that .keys() and other dict methods still work across the app + return all_profiles_dict diff --git a/core/services/profiles/create_objects.py b/core/services/profiles/create_objects.py new file mode 100644 index 0000000..1e2a90c --- /dev/null +++ b/core/services/profiles/create_objects.py @@ -0,0 +1,106 @@ +from core.models.orm_models.Location import Location +from core.models.enum_models import ProtocolChoice +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 +from core.models.system.SystemConnection import SystemConnection +from core.models.session.SessionConnection import SessionConnection +from core.models.session.SessionProfile import SessionProfile +from core.models.system.SystemProfile import SystemProfile +from core.models.BaseProfile import ProfileType +from core.models.Result import Result, ResultError +from core.errors.logger import logger +from core.utils.type_checker import type_checker + +@type_checker +def create_session_object( + profile_id: int, + potential_data: dict, + protocol: ProtocolChoice, + location: Location, + name: str +) -> Result: + """Return a SessionProfile object""" + + # SESSION ONLY PRE-REQS + resolution = potential_data.get('Resolution', None) + app_id = potential_data.get('Browser', None) + if resolution and app_id: + logger.info(f"Creating a session profile with {resolution} and {app_id}") + else: + error_msg = "Missing the resolution or app version" + logger.error(error_msg) + return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg) + + # Lookup App: + application_version = get_application_by_id(app_id) + if not application_version: + error_msg = "Failed to find the app by id" + logger.error(error_msg) + return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg) + + logger.info(f"application_version is {application_version}") + connection = SessionConnection(protocol.value) + + profile = SessionProfile( + id=profile_id, + name=name, + subscription=None, + type=ProfileType.SESSION, + location=location, + resolution=resolution, + application_version=application_version, + connection=connection + ) + return Result(valid=True, data=profile) + + +def create_profile_object(profile_id: int, potential_data: dict) -> Result: + """Creates and returns a literal profile object. (but not save to disk.)""" + + #--------------------------- + # EXTRACT DATA + #--------------------------- + 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(location_id) + print(f"location is {type(location)}") + name = potential_data.get('Name', None) + + if not profile_type or not isinstance(profile_type, ProfileType): + return Result(valid=False, error_type=ResultError.INVALID_INPUT, message="The data to create the profile is not structured properly. It's missing the type") + + logger.info("Passed initial data screen.") + + #--------------------------- + # SESSION + #--------------------------- + if profile_type == ProfileType.SESSION: + created = create_session_object(profile_id=profile_id, potential_data=potential_data, protocol=protocol, location=location, name=name) + if not created.valid: + error_msg = "Failed to create Session Profile" + logger.error(error_msg) + return created.wrap(error_msg) + profile = created.data + + #--------------------------- + # SYSTEM + #--------------------------- + elif profile_type == ProfileType.SYSTEM: + connection = SystemConnection(protocol.value) + profile = SystemProfile( + id=profile_id, + name=name, + type=ProfileType.SYSTEM, + subscription=None, + location=location, + connection=connection + ) + + else: + error_msg = f"Invalid profile type of {profile_type} used to create a profile." + logger.error(error_msg) + return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg) + + logger.info("Created the profile object.") + return Result(valid=True, data=profile) \ No newline at end of file diff --git a/core/services/profiles/filter_protocols.py b/core/services/profiles/filter_protocols.py new file mode 100644 index 0000000..3f20fb0 --- /dev/null +++ b/core/services/profiles/filter_protocols.py @@ -0,0 +1,40 @@ +from core.models.enum_models import ProtocolChoice, get_list_of, SINGBOX_PROTOCOLS +from core.models.BaseProfile import ProfileType +from core.utils.type_checker import type_checker +from core.errors.logger import logger + +SYSTEM_WIDE_PROTOCOLS = [ProtocolChoice.WIREGUARD, ProtocolChoice.HYSTERIA2, ProtocolChoice.VLESS] +SESSION_PROTOCOLS = [ProtocolChoice.WIREGUARD, ProtocolChoice.TOR] + + +def get_filtered_protocol_list(): + list_of_protocols = get_list_of(ProtocolChoice) + list_of_protocols.remove(ProtocolChoice.SOCK5_PROXY) # repeat of Tor + return list_of_protocols + + +def requires_setup(protocol: ProtocolChoice) -> bool: + if protocol in SINGBOX_PROTOCOLS: + return True + else: + return False + +@type_checker +def protocol_matches_profile_type(protocol: ProtocolChoice, profile_type: ProfileType)-> bool: + """Returns a boolean, to check if the protocol choice is valid for the profile type.""" + + if profile_type == ProfileType.SYSTEM: + if protocol in SYSTEM_WIDE_PROTOCOLS: + return True + else: + return False + + elif profile_type == ProfileType.SESSION: + if protocol in SESSION_PROTOCOLS: + return True + else: + return False + + else: + logger.error(f"Invalid protocol choice {protocol}") + return False diff --git a/core/services/profiles/profile_connections.py b/core/services/profiles/profile_connections.py index 451f085..ed2b7ce 100644 --- a/core/services/profiles/profile_connections.py +++ b/core/services/profiles/profile_connections.py @@ -107,15 +107,25 @@ def enable_session_profile( # NETWORK CONNECTION #----------------------------------- try: + print("Starting session networking function") network_result = start_session_networking(profile, ignore=ignore, connection_observer=connection_observer) - print("Completed networking") + print(f"Completed start_session_networking function with this result: {network_result}") except EndpointVerificationError: return Result(valid=False, error_type=ResultError.ENDPOINT_VERIFICATION, message=f"Verification of the endpoint failed for profile {profile.id}") if not network_result.valid: - return network_result.wrap("Failed to start the session profile") + error_msg = "Failed to start the session profile" + logger.error(error_msg) + return network_result.wrap(error_msg) port_number = network_result.data + print(f"Local port of the connection is {port_number}") + + if not port_number: + error_msg = "Networking failed to produce a working connection on a local port." + logger.error(error_msg) + result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg) + logger.info(f"Networking was successfull, launching the app with network port {port_number}") #-----------------------------------