Compare commits

..

No commits in common. "ee49e41977bf28e685e314fa8c0e24dcd9ed9fa9" and "a01bd4212297e67ea9a664394f1e4ed0c9f86ca3" have entirely different histories.

9 changed files with 69 additions and 206 deletions

View file

@ -41,11 +41,10 @@ class ProfileController:
"""Internal 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(f"Saving to disk profile {profile.id}.") logger.info("Saving to disk.")
model_manipulator.save_to_disk(profile) model_manipulator.save_to_disk(profile)
# 2. update cache to prevent drift # 2. update cache to prevent drift
logger.info(f"Saved to disk. Now updating cache for profile {profile.id}..")
ProfileController._repo.update_cache(profile) ProfileController._repo.update_cache(profile)
# 3. Notify observer # 3. Notify observer
@ -80,16 +79,13 @@ class ProfileController:
return Result(valid=True) return Result(valid=True)
@staticmethod @staticmethod
def update(profile: Profile, profile_observer: ProfileObserver = None): def update(profile: Union[SessionProfile, SystemProfile], profile_observer: ProfileObserver = None):
# Call the helper with the 'updated' event # Call the helper with the 'updated' event
ProfileController._save_and_sync(profile, 'updated', profile_observer) ProfileController._save_and_sync(profile, 'updated', profile_observer)
# update ui:
Notifications.emit(EventType.PROFILES_CHANGED)
@staticmethod @staticmethod
def delete(profile: Profile, profile_observer: ProfileObserver = None): def delete(profile: Union[SessionProfile, SystemProfile], profile_observer: ProfileObserver = None):
"""Remove the profile from both disk and cache""" """Remove the profile from both disk and cache"""
# 1. Save to temp variable: # 1. Save to temp variable:

View file

@ -39,7 +39,6 @@ class ResultError(Enum):
TICKET_SETUP = "ticket_setup" TICKET_SETUP = "ticket_setup"
TICKET_EXPIRED = "ticket_expired" TICKET_EXPIRED = "ticket_expired"
ALREADY_EXISTS = "already_exists" ALREADY_EXISTS = "already_exists"
ALREADY_USED = "already_used"
BILLING_CODE_EXISTS = "billing_code_exists" BILLING_CODE_EXISTS = "billing_code_exists"
PROCESS_GOT_KILLED = "process_got_killed" PROCESS_GOT_KILLED = "process_got_killed"
PROCESS_WONT_START = "process_wont_start" PROCESS_WONT_START = "process_wont_start"

View file

@ -22,8 +22,7 @@ TRANSLATION_DICT = {
ServerError.MISSING_DATA: ResultError.INVALID_INPUT, ServerError.MISSING_DATA: ResultError.INVALID_INPUT,
ServerError.UNPAID: ResultError.SUBSCRIPTION, ServerError.UNPAID: ResultError.SUBSCRIPTION,
ServerError.SERVER_SIDE: ResultError.SERVER_SIDE, ServerError.SERVER_SIDE: ResultError.SERVER_SIDE,
ServerError.EXPIRED: ResultError.EXPIRED_INVOICE, ServerError.EXPIRED: ResultError.EXPIRED_INVOICE
ServerError.ALREADY_USED: ResultError.ALREADY_EXISTS
} }
def format_server_response(api_response: ApiResponse|dict, desired_type: str) -> Result: def format_server_response(api_response: ApiResponse|dict, desired_type: str) -> Result:

View file

@ -5,10 +5,10 @@ from dataclasses import dataclass
class SessionConnection(BaseConnection): class SessionConnection(BaseConnection):
masked: bool = False masked: bool = False
# def __post_init__(self): def __post_init__(self):
# if self.code not in ('system', 'tor', 'wireguard'): if self.code not in ('system', 'tor', 'wireguard'):
# raise ValueError('Invalid connection code.') raise ValueError('Invalid connection code.')
# Called by: ConnectionController # Called by: ConnectionController

View file

@ -5,10 +5,10 @@ from dataclasses import dataclass
@dataclass @dataclass
class SystemConnection (BaseConnection): class SystemConnection (BaseConnection):
# def __post_init__(self): def __post_init__(self):
# if self.code not in ('vless', 'hysteria2', 'wireguard'): if self.code not in ('vless', 'hysteria2', 'wireguard'):
# raise ValueError('Invalid connection code.') raise ValueError('Invalid connection code.')
@staticmethod @staticmethod
def needs_proxy_configuration(): def needs_proxy_configuration():

View file

@ -105,27 +105,8 @@ def create_new_profile_object(profile_id: int, potential_data: dict) -> Result:
#--------------------------- #---------------------------
profile_type = potential_data.get('type', None) profile_type = potential_data.get('type', None)
protocol = potential_data.get('protocol', None) protocol = potential_data.get('protocol', None)
location_id = potential_data.get('location', None)
raw_location = potential_data.get('location', None)
# already a location id:
if isinstance(raw_location, int):
location = get_profile_location_data_by_id(raw_location)
# serialized form:
elif isinstance(raw_location, dict):
location_id = raw_location.get('location_id', None)
location = get_profile_location_data_by_id(location_id) location = get_profile_location_data_by_id(location_id)
# already a location:
elif isinstance(raw_location, Location):
location = raw_location
else:
error_msg = f"invalid location format of type {type(raw_location)} with data: {raw_location}."
logger.error(error_msg)
return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg)
name = potential_data.get('name', None) name = potential_data.get('name', None)
if not profile_type or not isinstance(profile_type, ProfileType): if not profile_type or not isinstance(profile_type, ProfileType):

View file

@ -8,8 +8,6 @@ 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 from core.models.orm_calls.application_version_calls import get_application_version
from core.models.Subscription import Subscription from core.models.Subscription import Subscription
from core.models.enum_models import ProtocolChoice from core.models.enum_models import ProtocolChoice
from core.models.orm_models.Location import Location
from core.models.orm_models.ApplicationVersion import ApplicationVersion
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.Constants import Constants from core.Constants import Constants
@ -260,32 +258,7 @@ def handle_outdated_session_data(dirty_keys: dict, profile: SessionProfile):
profile.delete_proxy_configuration() profile.delete_proxy_configuration()
def ensure_dict_format(profile: Profile, string_name: str, potential_sql_type) -> dict|None: def save_to_disk(profile: Profile):
"""Make sure the hot profile object coming in, matches the cold data storage format."""
potential_data = getattr(profile, string_name)
# if it's an SQL model, we convert it,
if isinstance(potential_data, potential_sql_type):
return potential_data.convert_to_dict()
# already is a dict:
elif isinstance(potential_data, dict):
return potential_data
else:
error_msg = "Invalid format for application version."
logger.error(error_msg)
return None
# dict_format = ensure_dict_format(profile=profile, string_name=, potential_sql_type)
# if not dict_format:
# return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg)
def save_to_disk(profile: Profile) -> Result:
""" """
Persist a Profile model to disk. Persist a Profile model to disk.
For SQL based attributes, we manually override the dict prior to serialization. For SQL based attributes, we manually override the dict prior to serialization.
@ -301,30 +274,14 @@ def save_to_disk(profile: Profile) -> Result:
if profile.type == ProfileType.SESSION: if profile.type == ProfileType.SESSION:
handle_outdated_session_data(dirty_keys=dirty_keys, profile=profile) handle_outdated_session_data(dirty_keys=dirty_keys, profile=profile)
# Application is an SQL model, so we override the dict,
# if it's an SQL model, we convert it,
if isinstance(profile.application_version, ApplicationVersion):
app_version_dict = profile.application_version.convert_to_dict() app_version_dict = profile.application_version.convert_to_dict()
config_dict["application_version"] = app_version_dict config_dict["application_version"] = app_version_dict
# already is a dict:
elif isinstance(profile.application_version, dict):
config_dict["application_version"] = profile.application_version
else:
error_msg = "Invalid format for application version."
logger.error(error_msg)
return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg)
# === LOCATION === # === LOCATION ===
# if it's an SQL model, we convert it, # Location is an SQL model, so we override the dict,
if isinstance(profile.location, Location): location_dict = profile.location.convert_to_dict() # this is from SQLAlchemy, and not JSON-models, that's why it's separate.
location_dict = profile.location.convert_to_dict()
config_dict["location"] = location_dict config_dict["location"] = location_dict
elif isinstance(profile.location, dict):
config_dict["location"] = profile.location
else:
error_msg = "Invalid format for location."
logger.error(error_msg)
return Result(valid=False, error_type=ResultError.INVALID_INPUT, message=error_msg)
# === FILE I/O === # === FILE I/O ===
config_file_contents = json.dumps(config_dict, indent=4) + '\n' config_file_contents = json.dumps(config_dict, indent=4) + '\n'
@ -334,7 +291,6 @@ def save_to_disk(profile: Profile) -> Result:
config_file_path = f'{profile_config_path}/config.json' config_file_path = f'{profile_config_path}/config.json'
write_atomically(config_file_path, config_file_contents) write_atomically(config_file_path, config_file_contents)
return Result(valid=True)
def delete(profile: Profile) -> Result: def delete(profile: Profile) -> Result:

View file

@ -3,96 +3,51 @@ from core.models.Result import Result, ResultError
from core.services.config_tools.manage_sudo_configs import remove_sudo_config from core.services.config_tools.manage_sudo_configs import remove_sudo_config
from core.models.enum_models import ProtocolChoice, is_valid_protocol from core.models.enum_models import ProtocolChoice, is_valid_protocol
from core.services.config_tools.config_manager import delete_connection_configs from core.services.config_tools.config_manager import delete_connection_configs
# from core.services.profiles import model_manipulator
from core.controllers.ProfileController import ProfileController from core.controllers.ProfileController import ProfileController
from core.models.BaseProfile import BaseProfile as Profile from core.models.BaseProfile import BaseProfile as Profile
from core.models.BaseProfile import ProfileType, PROTOCOL_CHOICES from core.models.BaseProfile import ProfileType, PROTOCOL_CHOICES
from core.models.system.SystemProfile import SystemProfile
from core.models.session.SessionProfile import SessionProfile 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 from core.models.orm_models.Location import Location
from core.models.orm_calls.application_version_calls import get_application_by_id
from core.models.orm_calls.location_calls import get_profile_location_data_by_id
from core.services.profiles.create_objects import create_new_profile_object
def finally_save_it(profile: Profile) -> Result: """
# ------------------------- Steps:
# SAVE ENTIRE THING 1) Looks up the profile by id number
# ------------------------- 2) Filters what values to save, using the ORM for some such as location
logger.info(f"We in the final stage with the mutated profile {profile}") 3) Saves it with the abstract class' json serialization methods, which use the ORM methods
try:
ProfileController.update(profile)
logger.info("Save worked, passing to the GUI the Result..")
return Result(valid=True)
except Exception as e:
error_msg = f"Profile save failed because {str(e)}"
return Result(valid=False, message=error_msg, error_type=ResultError.UNKNOWN)
Returns:
Result Object
def mutate_profile_object_type(profile: Profile, new_choices: dict) -> Result: Called by:
"""Mutate a profile object from one type to another.""" GUI's editor_page
new_type = new_choices["type"] Raises Errors:
profile_id = profile.id False
original_subscription = profile.subscription """
original_ticket = profile.ticket
original_choices = profile.to_dict() def update_profile(
profile_id: int,
if "location" not in new_choices:
# re-use existing location object:
new_choices["location"] = profile.location
for each_category, each_value in original_choices.items():
if each_category not in new_choices:
logger.info(f"Copying over category {each_category} from the original.")
new_choices[each_category] = original_choices[each_category]
creation_result = create_new_profile_object(profile_id=profile_id, potential_data=new_choices)
if not creation_result.valid:
return creation_result.wrap("Unable to switch profile type due to creation of new object.")
new_profile_object = creation_result.data
if not new_profile_object:
return Result(valid=False, data=creation_result, error_type=ResultError.INVALID_INPUT, message="Dev error, this was marked true but its missing the data")
logger.info("Copying over sub data:")
new_profile_object.subscription = original_subscription
new_profile_object.ticket = original_ticket
# Delete the old one:
logger.info("Deleting the previous profile in that slot.")
ProfileController.delete(profile)
# save the new:
return finally_save_it(new_profile_object)
def _mutate_one_profile_choice(
profile: Profile,
key: str, key: str,
new_value: str new_value: str
) -> Result: ) -> Result:
"""Mutates the profile object fo a single value, but doesn't save it. Returns it."""
# final_data = None # final_data = None
logger.info(f"Recieved profile_id {profile.id}, key {key}, and new_value {new_value}.") logger.info(f"[UPDATE PROFILE] Recieved profile_id {profile_id}, key {key}, and new_value {new_value}.")
if not key: if not key or not new_value:
return Result(valid=False, data=f"Invalid Input of {key}", error_type=ResultError.INVALID_INPUT) return Result(valid=False, data=f"Invalid Inputs of {key} and {new_value}", error_type=ResultError.INVALID_INPUT)
# ============= RESOLUTION ============= profile = ProfileController.get(profile_id)
if key == 'resolution': if not profile:
profile.resolution = new_value error_msg = f"Invalid profile id of {profile_id}"
# # ============= TYPE =============
elif key == 'type':
error_msg = "This is a developer bug. The type should have triggered an object conversion prior to this function."
logger.error(error_msg)
return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT) return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT)
# ============= NAME ============= if key == 'dimentions':
profile.resolution = new_value
elif key == 'name': elif key == 'name':
profile.name = new_value profile.name = new_value
@ -111,9 +66,15 @@ def _mutate_one_profile_choice(
# ============= BROWSER ============= # ============= BROWSER =============
elif key == 'browser': elif key == 'browser':
profile.application_version = get_application_by_id(new_value) browser_type, browser_version = new_value.split(':', 1)
application_version = get_application_version( # SQLAlchemy
application_code=browser_type,
version_number=browser_version
)
# SQLAlchemy foreign key assignment — fills in id, timezone, operator, etc.
profile.application_version = application_version
# ============= PROTOCOL TYPE =============
elif key == 'protocol': elif key == 'protocol':
logger.info("Changing the protocol..") logger.info("Changing the protocol..")
changed_result = change_protocol(profile, new_value) changed_result = change_protocol(profile, new_value)
@ -124,7 +85,11 @@ def _mutate_one_profile_choice(
# ============= LOCATION ============= # ============= LOCATION =============
elif key == "location": elif key == "location":
new_location = get_profile_location_data_by_id(new_value) country_code, city_code = new_value.split("_")
new_location = get_profile_location_data( # SQLAlchemy
country_code=country_code,
city_code=city_code
)
pre_existing_protocol = profile.protocol pre_existing_protocol = profile.protocol
if new_location.supports_protocol(pre_existing_protocol): if new_location.supports_protocol(pre_existing_protocol):
profile.location = new_location profile.location = new_location
@ -136,47 +101,14 @@ def _mutate_one_profile_choice(
else: else:
return Result(valid=False, message="Invalid Value to Edit", error_type=ResultError.INVALID_INPUT) return Result(valid=False, message="Invalid Value to Edit", error_type=ResultError.INVALID_INPUT)
logger.info("Passing back the mutated profile object..") logger.info("[UPDATE PROFILE] Passing to Profile model to save..")
try:
return Result(valid=True, data=profile) ProfileController.update(profile)
logger.info("[UPDATE PROFILE] Save worked, passing to the GUI the Result..")
def update_profile( return Result(valid=True)
profile_id: int, except Exception as e:
new_choices: dict error_msg = f"Profile save failed because {str(e)}"
) -> Result: return Result(valid=False, message=error_msg, error_type=ResultError.UNKNOWN)
# -------------------------
# GET PROFILE
# -------------------------
profile = ProfileController.get(profile_id)
if not profile:
error_msg = f"Invalid profile id of {profile_id}"
return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT)
# -------------------------
# TYPE CHANGE (requires object swap)
# -------------------------
if "type" in new_choices:
return mutate_profile_object_type(profile=profile, new_choices=new_choices)
# -------------------------
# LOOP UPDATE EACH
# -------------------------
for each_category, each_value in new_choices.items():
logger.info(f"Updating {each_category}")
each_update = _mutate_one_profile_choice(
profile=profile,
key=each_category,
new_value=each_value
)
if not each_update.valid:
return each_update.wrap(f"Category {each_category} choice failed to update.")
# mutated profile object continues loop,
profile = each_update.data
return finally_save_it(profile)
def change_protocol(profile: Profile, new_value: str) -> Result: def change_protocol(profile: Profile, new_value: str) -> Result:
@ -198,8 +130,8 @@ def change_protocol(profile: Profile, new_value: str) -> Result:
return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT) return Result(valid=False, message=error_msg, error_type=ResultError.INVALID_INPUT)
# ============= LOCATION SUPPORTS PROTOCOL ============= # ============= LOCATION SUPPORTS PROTOCOL =============
logger.info("checking protocol support for this location..")
pre_existing_location = profile.location pre_existing_location = profile.location
logger.info(f"checking protocol support for location {pre_existing_location.country_name} with {protocol_choice}..")
if not pre_existing_location.supports_protocol(new_value): if not pre_existing_location.supports_protocol(new_value):
logger.error(f"User is trying to update the protocol to {new_value}, but selected an invalid location to do so.") logger.error(f"User is trying to update the protocol to {new_value}, but selected an invalid location to do so.")

View file

@ -181,7 +181,7 @@ def use_ticket_orchestrator(
################################### ###################################
if not server_reply.valid: if not server_reply.valid:
logger.info("Server's reply is invalid") logger.info("Server's reply is invalid")
if server_reply.error_type in (ServerError.ALREADY_USED, ResultError.ALREADY_USED) and server_reply.billing_code: if server_reply.error_type == ServerError.ALREADY_USED and server_reply.billing_code:
logger.info("But it's because it's re-using a previously valid billing code. Continue..") logger.info("But it's because it's re-using a previously valid billing code. Continue..")
else: else:
logger.error("Returning a failure..") logger.error("Returning a failure..")