Creation of Profile objects now happens in core, instead of GUI
This commit is contained in:
parent
728a6bd51c
commit
02cc80b152
16 changed files with 426 additions and 63 deletions
|
|
@ -1,7 +1,13 @@
|
||||||
|
from core.services.profiles.create_objects import create_profile_object
|
||||||
from core.services.profiles.ProfileRepository import ProfileRepository
|
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.services.subscriptions import subscriptions
|
||||||
from core.models.Result import Result, ResultError
|
from core.models.Result import Result, ResultError
|
||||||
from core.errors.logger import logger
|
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
|
from core.models.BaseProfile import BaseProfile as Profile
|
||||||
|
|
@ -32,20 +38,11 @@ class ProfileController:
|
||||||
def get_all():
|
def get_all():
|
||||||
return ProfileController._repo.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
|
@staticmethod
|
||||||
def _save_and_sync(profile, event_type: str, observer: ProfileObserver = None):
|
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
|
# 1. Persist to disk
|
||||||
|
logger.info("Saving to disk.")
|
||||||
profile.save()
|
profile.save()
|
||||||
|
|
||||||
# 2. update cache to prevent drift
|
# 2. update cache to prevent drift
|
||||||
|
|
@ -55,6 +52,98 @@ class ProfileController:
|
||||||
if observer is not None:
|
if observer is not None:
|
||||||
observer.notify(event_type, profile)
|
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
|
@staticmethod
|
||||||
def delete(profile: Union[SessionProfile, SystemProfile], profile_observer: ProfileObserver = None):
|
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
|
# 3. update cache with the temp variable to prevent drift
|
||||||
ProfileController._repo.invalidate(profile_id=profile_id)
|
ProfileController._repo.invalidate(profile_id=profile_id)
|
||||||
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def what_type_is_profile(profile_id: int) -> ProfileType:
|
def what_type_is_profile(profile_id: int) -> ProfileType:
|
||||||
all_data = ProfileController._repo.get_all()
|
all_data = ProfileController._repo.get_all()
|
||||||
|
|
|
||||||
|
|
@ -97,6 +97,7 @@ class ThreadPlumbing:
|
||||||
# self.kwargs.update(ui_caller=self.ui_caller)
|
# self.kwargs.update(ui_caller=self.ui_caller)
|
||||||
logger.info("Executing a double dip function.")
|
logger.info("Executing a double dip function.")
|
||||||
self.execute_already_on_background(task=double_dip_function)
|
self.execute_already_on_background(task=double_dip_function)
|
||||||
|
return
|
||||||
else:
|
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}")
|
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}")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -109,7 +109,7 @@ class BaseProfile(ABC):
|
||||||
return type(self).__name__ == 'SystemProfile'
|
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.
|
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.
|
Then persist changes in the profile/model to disk.
|
||||||
|
|
@ -120,28 +120,33 @@ class BaseProfile(ABC):
|
||||||
# 1. Get the call stack
|
# 1. Get the call stack
|
||||||
# stack[0] is this current 'save' method
|
# stack[0] is this current 'save' method
|
||||||
# stack[1] is the immediate caller
|
# stack[1] is the immediate caller
|
||||||
stack = inspect.stack()
|
|
||||||
caller_frame = stack[1]
|
|
||||||
|
|
||||||
caller_function_name = caller_frame.function
|
# stack = inspect.stack()
|
||||||
caller_module_name = caller_frame.filename # Full path to the file
|
# caller_frame = stack[1]
|
||||||
|
|
||||||
# 2. Only the Repo or Controller is allowed to save
|
# caller_function_name = caller_frame.function
|
||||||
allowed_callers = ['create', 'update_cache']
|
# caller_module_name = caller_frame.filename # Full path to the file
|
||||||
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:
|
# # 2. Only the Repo or Controller is allowed to save
|
||||||
logger.warning(
|
# allowed_callers = ['create', 'update_cache']
|
||||||
f"ARCHITECTURE VIOLATION: .save() called directly from "
|
# is_allowed_file = "core/controllers/ProfileController.py" in caller_module_name or "core/services/profiles/ProfileRepository.py" in caller_module_name
|
||||||
f"function '{caller_function_name}' in {caller_module_name}. "
|
|
||||||
f"Please route this through ProfileController to ensure cache integrity."
|
# 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
|
# Actual Save
|
||||||
#--------------------------
|
#--------------------------
|
||||||
|
|
||||||
# === SERIALIZATION ===
|
# === 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()
|
config_dict = self.to_dict()
|
||||||
|
|
||||||
# === LOCATION ===
|
# === LOCATION ===
|
||||||
|
|
@ -294,6 +299,11 @@ class BaseProfile(ABC):
|
||||||
# =========== SESSION ===========
|
# =========== SESSION ===========
|
||||||
if 'application_version' in profile:
|
if 'application_version' in profile:
|
||||||
profile['type'] = ProfileType.SESSION
|
profile['type'] = ProfileType.SESSION
|
||||||
|
|
||||||
|
|
||||||
|
if isinstance(profile['application_version'], ApplicationVersion):
|
||||||
|
print("It's already an app version")
|
||||||
|
|
||||||
if profile['application_version'] is not None:
|
if profile['application_version'] is not None:
|
||||||
application_version = get_application_version(
|
application_version = get_application_version(
|
||||||
profile['application_version']['application_code'] or None,
|
profile['application_version']['application_code'] or None,
|
||||||
|
|
|
||||||
|
|
@ -40,3 +40,7 @@ def get_choice_list(model: Type[Enum]) -> list:
|
||||||
|
|
||||||
def valid_enum(potential_candidate: str, enum_model: Type[Enum]) -> bool:
|
def valid_enum(potential_candidate: str, enum_model: Type[Enum]) -> bool:
|
||||||
return potential_candidate in [choice.value for choice in enum_model]
|
return potential_candidate in [choice.value for choice in enum_model]
|
||||||
|
|
||||||
|
|
||||||
|
def get_list_of(enum_model: Type[Enum]):
|
||||||
|
return list(enum_model)
|
||||||
|
|
|
||||||
|
|
@ -69,3 +69,21 @@ def get_random_installed_app() -> Optional[ApplicationVersion]:
|
||||||
list_of_data.remove(random_item)
|
list_of_data.remove(random_item)
|
||||||
|
|
||||||
return None
|
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
|
||||||
|
|
|
||||||
|
|
@ -59,3 +59,21 @@ def get_random_location(filter_out_list: Optional[list] = None) -> Location:
|
||||||
if random_pick not in filter_out_list:
|
if random_pick not in filter_out_list:
|
||||||
return random_pick
|
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
|
||||||
|
|
@ -30,22 +30,30 @@ class SessionProfile(BaseProfile):
|
||||||
def save(self):
|
def save(self):
|
||||||
print("We are able to trigger save on the child session")
|
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):
|
# if os.path.isdir(persistent_state_path):
|
||||||
shutil.rmtree(persistent_state_path, ignore_errors=True)
|
# 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_proxy_configuration()
|
||||||
self.delete_wireguard_configuration()
|
# self.delete_wireguard_configuration()
|
||||||
|
|
||||||
# === APPLICATION ===
|
# === APPLICATION ===
|
||||||
|
print(f"self.application_version is {self.application_version}")
|
||||||
|
|
||||||
|
if isinstance(self.application_version, ApplicationVersion):
|
||||||
app_version_dict = self.application_version.convert_to_dict()
|
app_version_dict = self.application_version.convert_to_dict()
|
||||||
print(f"session child got {app_version_dict} as 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)
|
super().save(app_version_dict=app_version_dict)
|
||||||
|
|
||||||
def attach_proxy_configuration(self, proxy_configuration):
|
def attach_proxy_configuration(self, proxy_configuration):
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ class EventType(Enum):
|
||||||
SHOW_POPUP = auto()
|
SHOW_POPUP = auto()
|
||||||
RESUME_ACTIONS = auto()
|
RESUME_ACTIONS = auto()
|
||||||
SYNC_COMPLETE = auto()
|
SYNC_COMPLETE = auto()
|
||||||
|
PROFILES_CHANGED = auto()
|
||||||
|
|
||||||
class Notifications:
|
class Notifications:
|
||||||
_subscribers = {}
|
_subscribers = {}
|
||||||
|
|
|
||||||
|
|
@ -151,7 +151,7 @@ def test_with_threading(connection_observer: Optional[ConnectionObserver], port:
|
||||||
http_start = time.time()
|
http_start = time.time()
|
||||||
result_queue = Queue()
|
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
|
transport = None
|
||||||
if port:
|
if port:
|
||||||
transport = httpx_socks.SyncProxyTransport(
|
transport = httpx_socks.SyncProxyTransport(
|
||||||
|
|
@ -214,6 +214,7 @@ def test(connection_observer: Optional[ConnectionObserver], port: Optional[int]
|
||||||
|
|
||||||
# with a proxy:
|
# with a proxy:
|
||||||
if port:
|
if port:
|
||||||
|
print("Starting an async test..")
|
||||||
return asyncio.run(async_test_orchestrator(endpoint_list, port, total_budget))
|
return asyncio.run(async_test_orchestrator(endpoint_list, port, total_budget))
|
||||||
|
|
||||||
# without systemwide:
|
# without systemwide:
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,8 @@ from core.errors.logger import logger
|
||||||
from functools import partial
|
from functools import partial
|
||||||
|
|
||||||
def just_reconnect(profile_id: int) -> Result:
|
def just_reconnect(profile_id: int) -> Result:
|
||||||
print(f"Reconnecting profile_id {profile_id}..")
|
print(f"Returning FALSE, to reconnect profile_id {profile_id}..")
|
||||||
return Result(valid=True, double_dip=True, error_type=ResultError.RECONNECT)
|
return Result(valid=False, double_dip=True, error_type=ResultError.RECONNECT)
|
||||||
|
|
||||||
|
|
||||||
def wipe_attempts_and_reconnect(recovery_stats: ConnectionRecovery)-> Result:
|
def wipe_attempts_and_reconnect(recovery_stats: ConnectionRecovery)-> Result:
|
||||||
|
|
|
||||||
|
|
@ -59,14 +59,16 @@ def start_session_networking(
|
||||||
|
|
||||||
# already exhausted options, do they want to restart?
|
# already exhausted options, do they want to restart?
|
||||||
if recovery_stats.reached_end_of_loop and not recovery_stats.bypass_attempts:
|
if recovery_stats.reached_end_of_loop and not recovery_stats.bypass_attempts:
|
||||||
|
print("Offering recovery options")
|
||||||
return offer_recovery_options(recovery_stats)
|
return offer_recovery_options(recovery_stats)
|
||||||
|
|
||||||
# if they bypass the wipe, its a one-time thing:
|
# if they bypass the wipe, its a one-time thing:
|
||||||
if recovery_stats.bypass_attempts:
|
if recovery_stats.bypass_attempts:
|
||||||
|
print("Bypass is a one-time thing. Resetting")
|
||||||
recovery_stats.bypass_attempts = False
|
recovery_stats.bypass_attempts = False
|
||||||
|
|
||||||
recovery_stats.attempts += 1
|
recovery_stats.attempts += 1
|
||||||
current_try = recovery_stats.attempts
|
print(f"recovery_stats attempts: {recovery_stats.attempts}")
|
||||||
|
|
||||||
# =================================
|
# =================================
|
||||||
# PREPARE PRE-REQS
|
# PREPARE PRE-REQS
|
||||||
|
|
@ -81,7 +83,7 @@ def start_session_networking(
|
||||||
|
|
||||||
port_number = ConnectionService.get_random_available_port_number()
|
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)
|
Notifications.emit(EventType.STATUS_UPDATE, notification)
|
||||||
print(notification)
|
print(notification)
|
||||||
|
|
||||||
|
|
@ -108,7 +110,9 @@ def start_session_networking(
|
||||||
# EVALUATE
|
# EVALUATE
|
||||||
# =================================
|
# =================================
|
||||||
if not started_process.valid:
|
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
|
network_process = started_process.data
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -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)
|
return Result(valid=False, error_type=ResultError.MISSING_DATA, message=error_msg)
|
||||||
|
|
||||||
# reality:
|
# 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)
|
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)
|
return compare_ips(ip_result=ip_result, expected_ip_address=expected_ip_address)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -20,29 +20,30 @@ class ProfileRepository:
|
||||||
cls._instance._cache: Dict[int, any] = {}
|
cls._instance._cache: Dict[int, any] = {}
|
||||||
return cls._instance
|
return cls._instance
|
||||||
|
|
||||||
def get(self, profile_id: int):
|
# def get(self, profile_id: int):
|
||||||
# 1. Check cache first
|
# # 1. Check cache first
|
||||||
if profile_id in self._cache:
|
# if profile_id in self._cache:
|
||||||
return self._cache[profile_id]
|
# return self._cache[profile_id]
|
||||||
|
|
||||||
# 2. Fallback to disk via the Model
|
# # 2. Fallback to disk via the Model
|
||||||
profile = BaseProfile.find_by_id(profile_id)
|
# profile = BaseProfile.find_by_id(profile_id)
|
||||||
|
|
||||||
# 3. Update cache for next time
|
# # 3. Update cache for next time
|
||||||
if profile:
|
# if profile:
|
||||||
self._cache[profile_id] = profile
|
# self._cache[profile_id] = profile
|
||||||
|
|
||||||
return profile
|
# return profile
|
||||||
|
|
||||||
def get_all(self):
|
# def get_all(self):
|
||||||
# First, get the current list of IDs from the model, to avoid drift, from new files added to disk
|
# # First, get the current list of IDs from the model, to avoid drift, from new files added to disk
|
||||||
all_profiles = BaseProfile.all()
|
# all_profiles = BaseProfile.all()
|
||||||
|
|
||||||
# Update our internal cache with everything currently on disk
|
# # Update our internal cache with everything currently on disk
|
||||||
for p in all_profiles:
|
# for p in all_profiles:
|
||||||
self._cache[id] = p
|
# self._cache[id] = p
|
||||||
|
# # self._cache[p.id] = p
|
||||||
|
|
||||||
return all_profiles
|
# return all_profiles
|
||||||
|
|
||||||
def update_cache(self, profile):
|
def update_cache(self, profile):
|
||||||
"""Explicitly updates the cache to prevent drift after a save."""
|
"""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."""
|
"""Removes an item from cache if it's deleted from disk."""
|
||||||
self._cache.pop(profile_id, None)
|
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
|
||||||
|
|
|
||||||
106
core/services/profiles/create_objects.py
Normal file
106
core/services/profiles/create_objects.py
Normal file
|
|
@ -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)
|
||||||
40
core/services/profiles/filter_protocols.py
Normal file
40
core/services/profiles/filter_protocols.py
Normal file
|
|
@ -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
|
||||||
|
|
@ -107,15 +107,25 @@ def enable_session_profile(
|
||||||
# NETWORK CONNECTION
|
# NETWORK CONNECTION
|
||||||
#-----------------------------------
|
#-----------------------------------
|
||||||
try:
|
try:
|
||||||
|
print("Starting session networking function")
|
||||||
network_result = start_session_networking(profile, ignore=ignore, connection_observer=connection_observer)
|
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:
|
except EndpointVerificationError:
|
||||||
return Result(valid=False, error_type=ResultError.ENDPOINT_VERIFICATION, message=f"Verification of the endpoint failed for profile {profile.id}")
|
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:
|
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
|
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}")
|
logger.info(f"Networking was successfull, launching the app with network port {port_number}")
|
||||||
|
|
||||||
#-----------------------------------
|
#-----------------------------------
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue