210 lines
7.7 KiB
Python
210 lines
7.7 KiB
Python
from core.models.manage.lifecycle_tools import serialize_dataclass_with_models
|
|
from core.services.profiles import model_manipulator
|
|
from core.services.profiles.create_objects import create_new_profile_object
|
|
from core.services.profiles.ProfileRepository import ProfileRepository
|
|
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
|
|
from core.models.BaseProfile import ProfileType
|
|
from core.models.Subscription import Subscription
|
|
from core.models.session.SessionProfile import SessionProfile
|
|
from core.models.system.SystemProfile import SystemProfile
|
|
from core.observers.ApplicationVersionObserver import ApplicationVersionObserver
|
|
from core.observers.ConnectionObserver import ConnectionObserver
|
|
from core.observers.ProfileObserver import ProfileObserver
|
|
from core.services.WebServiceApiService import WebServiceApiService
|
|
from typing import Union, Optional
|
|
import base64
|
|
import re
|
|
import time
|
|
|
|
PROFILE_TABLES_WITH_ORM = ["locations", "operators", "application_versions"]
|
|
|
|
class ProfileController:
|
|
# Initialize the singleton repository
|
|
_repo = ProfileRepository()
|
|
|
|
@staticmethod
|
|
def get(id: int) -> Union[SessionProfile, SystemProfile, None]:
|
|
# Controller no longer talks to the Model; it talks to the Repo
|
|
return ProfileController._repo.get(id)
|
|
|
|
@staticmethod
|
|
def get_all() -> Result:
|
|
return ProfileController._repo.get_all()
|
|
|
|
@staticmethod
|
|
def get_all_serialized() -> Result:
|
|
got_all = ProfileController._repo.get_all()
|
|
|
|
if not got_all.valid:
|
|
return got_all.wrap("failed to get from the repo")
|
|
|
|
initial_results = got_all.data
|
|
converted_results = {}
|
|
|
|
for key, each_result in initial_results.items():
|
|
if not each_result:
|
|
logger.info(f"Skipping profile {key}")
|
|
try:
|
|
converted_dict = serialize_dataclass_with_models(each_result)
|
|
converted_results[key] = converted_dict
|
|
except Exception as e:
|
|
error_msg = str(e)
|
|
logger.error(error_msg)
|
|
|
|
return Result(valid=True, data=converted_results)
|
|
|
|
|
|
@staticmethod
|
|
def get_ONE_serialized(profile_id: int) -> Result:
|
|
logger.info("Fetching from the repo")
|
|
got_one = ProfileController._repo.get(profile_id)
|
|
|
|
logger.info(f"Got data, converting it. of type {type(got_one)}")
|
|
converted_dict = serialize_dataclass_with_models(got_one)
|
|
logger.info(f"converted_dict is {converted_dict}")
|
|
|
|
return Result(valid=True, data=converted_dict)
|
|
|
|
@staticmethod
|
|
def clear_cache_and_get_fresh_data() -> Result:
|
|
"""Clear the Repo's Cache and gets new fresh data."""
|
|
logger.info("Clearing Repo cache")
|
|
result = ProfileController._repo.refresh_cache()
|
|
|
|
# update ui:
|
|
if result.valid:
|
|
logger.info("Updating notifications of change")
|
|
Notifications.emit(EventType.PROFILES_CHANGED)
|
|
|
|
return result
|
|
|
|
|
|
@staticmethod
|
|
def _save_and_sync(profile, event_type: str, observer: ProfileObserver = None):
|
|
"""Internal helper to handle the actual persistence and cache synchronization."""
|
|
|
|
# 1. Persist to disk
|
|
logger.info(f"Saving to disk profile {profile.id}.")
|
|
model_manipulator.save_to_disk(profile)
|
|
|
|
# 2. update cache to prevent drift
|
|
logger.info(f"Saved to disk. Now updating cache for profile {profile.id}..")
|
|
ProfileController._repo.update_cache(profile)
|
|
|
|
# 3. Notify observer
|
|
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)}")
|
|
|
|
# Get next id from the Repo, which confirms with what's on disk:
|
|
profile_id = ProfileController._repo.get_next_id()
|
|
|
|
# Create the object:
|
|
created_object = create_new_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
|
|
|
|
# Save the object and sync with the repo.
|
|
ProfileController._save_and_sync(profile, 'created', profile_observer)
|
|
|
|
# Update UI & Return:
|
|
Notifications.emit(EventType.PROFILES_CHANGED)
|
|
return Result(valid=True)
|
|
|
|
@staticmethod
|
|
def update(profile: Profile, profile_observer: ProfileObserver = None):
|
|
# Call the helper with the 'updated' event
|
|
ProfileController._save_and_sync(profile, 'updated', profile_observer)
|
|
|
|
# update ui:
|
|
Notifications.emit(EventType.PROFILES_CHANGED)
|
|
|
|
@staticmethod
|
|
def delete(profile: Profile, profile_observer: ProfileObserver = None):
|
|
"""Remove the profile from both disk and cache"""
|
|
|
|
# 1. Save to temp variable:
|
|
profile_id = profile.id
|
|
|
|
# 2. Permanently delete from disk
|
|
removed = model_manipulator.delete(profile)
|
|
if not removed.valid:
|
|
return removed.wrap("Unable to delete files, so keeping repo intact.")
|
|
|
|
# 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|None:
|
|
profiles_result = ProfileController._repo.get_all()
|
|
if not profiles_result.valid:
|
|
logger.error(f"Fetch of profiles was invalid. {profiles_result.message}")
|
|
return None
|
|
|
|
all_data = profiles_result.data
|
|
given_profile = all_data[profile_id]
|
|
return given_profile.type
|
|
|
|
|
|
@staticmethod
|
|
def get_default_state_dict(profile_id: int) -> dict:
|
|
"""Get a dict of state for UI callers"""
|
|
|
|
profile = ProfileController._repo.get(profile_id)
|
|
profile_dict = profile.to_dict()
|
|
|
|
profile_dict["location"] = profile.location.id
|
|
|
|
if isinstance(profile, SessionProfile):
|
|
app_id = profile.application_version.id
|
|
profile_dict["browser"] = app_id
|
|
|
|
return profile_dict
|
|
|
|
|
|
@staticmethod
|
|
def attach_proxy_configuration(profile: Union[SessionProfile, SystemProfile]):
|
|
|
|
if profile.is_session_profile() and profile.has_subscription():
|
|
|
|
proxy_configuration = WebServiceApiService.get_proxy_configuration(profile.subscription.billing_code)
|
|
|
|
if proxy_configuration is not None:
|
|
profile.attach_proxy_configuration(proxy_configuration)
|
|
|
|
@staticmethod
|
|
def get_proxy_configuration(profile: Union[SessionProfile, SystemProfile]):
|
|
|
|
if profile.is_session_profile():
|
|
return profile.get_proxy_configuration()
|
|
else:
|
|
return None
|
|
|
|
@staticmethod
|
|
def has_proxy_configuration(profile: Union[SessionProfile, SystemProfile]):
|
|
profile.has_proxy_configuration()
|
|
|
|
@staticmethod
|
|
def get_wireguard_configuration_path(profile: Union[SessionProfile, SystemProfile]):
|
|
return profile.get_wireguard_configuration_path()
|
|
|
|
@staticmethod
|
|
def has_wireguard_configuration(profile: Union[SessionProfile, SystemProfile]):
|
|
return profile.has_wireguard_configuration()
|