forked from Support/sp-hydra-veil-gui
387 lines
15 KiB
Python
387 lines
15 KiB
Python
from core.models.BaseProfile import ProfileType
|
|
from core.services.payment_phase.ticket_cycle import profile_can_respawn
|
|
from core.controllers.ProfileController import ProfileController
|
|
from core.services.profiles.attribute_filters import protocol_matches_profile_type, app_or_display_matches_profile_type
|
|
from core.controllers.profile_state.data_filters import protocol_is_supported_for_location
|
|
from gui.v2.presenters.data.location_data import get_location_display_data
|
|
from gui.v2.presenters.data.app_data import get_app_display_data
|
|
from gui.v2.presenters.data.protocol_data import get_protocol_button_data
|
|
from gui.v2.presenters.data.resolution_data import get_resolution_data, validate_selected_resolution
|
|
from gui.v2.presenters.data.type_data import get_profile_type_data
|
|
from gui.v2.presenters.image_tools.button_factory import create_button_image, create_resolution_button_image, blank_button
|
|
from core.errors.logger import logger
|
|
from core.models.Result import ResultError
|
|
|
|
from pathlib import Path
|
|
from dataclasses import dataclass
|
|
from typing import Optional, Dict
|
|
import random
|
|
|
|
@dataclass
|
|
class PreEdit:
|
|
proceed: bool
|
|
warnings: bool
|
|
warnings_dict: Optional[Dict]
|
|
whats_different: Optional[Dict]
|
|
|
|
|
|
class RegistrationState:
|
|
def __init__(self, btn_path, profile_id: Optional[int] = None, location_down: Optional[bool] = False):
|
|
self.btn_path = btn_path
|
|
self.all_options = {}
|
|
self.selections = {}
|
|
self.order_map = {}
|
|
self.pixmap_cache = {}
|
|
self.profile_id = profile_id
|
|
self.original_choices = {}
|
|
self.proceed = False
|
|
self.warnings_dict = {}
|
|
self.key_choices = []
|
|
self.location_down = location_down
|
|
|
|
# Maps a category to the function that validates its current selection.
|
|
self._filter_map = {
|
|
"protocol": self.is_protocol_valid,
|
|
"browser": self.is_app_valid,
|
|
"resolution": self.is_resolution_valid,
|
|
}
|
|
|
|
# Maps a "Trigger" category to the categories it affects.
|
|
self._dependency_map = {
|
|
"type": ["protocol", "browser", "resolution"],
|
|
"location": ["protocol"],
|
|
}
|
|
|
|
# Callbacks to notify the UI. Store functions here: { "Category": callback_func }
|
|
self.listeners = {}
|
|
|
|
# Gets this profile's available data:
|
|
if self.profile_id is not None:
|
|
logger.info(f"RegistrationState got a profile id of {self.profile_id}")
|
|
default_data = ProfileController.get_default_state_dict(profile_id)
|
|
self.original_choices = default_data
|
|
else:
|
|
default_data = None
|
|
|
|
# Gets ALL available data:
|
|
self._load_all_data(default_data)
|
|
|
|
|
|
def register_listener(self, category, callback):
|
|
"""UI elements call this to be notified when their category changes."""
|
|
self.listeners[category] = callback
|
|
|
|
|
|
def _no_premade_choices(self, category: str, default_data: Optional[dict]):
|
|
"""For categories without premade choices, we see if default data is available. If not, then it's None"""
|
|
if default_data:
|
|
self.selections[category] = default_data.get(category)
|
|
else:
|
|
self.selections[category] = None
|
|
|
|
|
|
def _apply_order_filter(self, category: str, order: list) -> list:
|
|
"""apply custom sorting or filtering based on the category"""
|
|
if category == "browser":
|
|
# browser is reversed order (so highest IDs are first)
|
|
return order[::-1]
|
|
|
|
if category == "location":
|
|
# location is random order
|
|
return random.sample(order, len(order))
|
|
|
|
return order
|
|
|
|
def _load_all_data(self, default_data: Optional[dict] = None):
|
|
"""Load the data for a given category, and then register that data"""
|
|
load_config = {
|
|
"type": (get_profile_type_data, 0),
|
|
"protocol": (get_protocol_button_data, 0),
|
|
"resolution": (get_resolution_data, 0),
|
|
"location": (get_location_display_data, 0),
|
|
"browser": (get_app_display_data, 0),
|
|
"name": (None, None)
|
|
}
|
|
|
|
for category, (loader_func, default_idx) in load_config.items():
|
|
self.key_choices.append(category)
|
|
if loader_func is None:
|
|
self._no_premade_choices(category=category, default_data=default_data)
|
|
continue
|
|
|
|
data = loader_func(self.btn_path)
|
|
self._register_category(category=category, data=data, default_data=default_data, default_idx=default_idx)
|
|
|
|
|
|
def _register_category(self, category: str, data: dict, default_data: Optional[dict], default_idx: int = 0):
|
|
"""Setup a category with a given data set and default index"""
|
|
|
|
if isinstance(data, list):
|
|
data = {item: item for item in data}
|
|
self.all_options[category] = data
|
|
# self.order_map[category] = list(data.keys())
|
|
|
|
raw_order = list(data.keys())
|
|
self.order_map[category] = self._apply_order_filter(category, raw_order)
|
|
|
|
|
|
# Default selection logic
|
|
if default_data is not None:
|
|
# If default_data is provided, we use it exclusively.
|
|
# .get() returns None if the category key is missing.
|
|
self.selections[category] = default_data.get(category)
|
|
else:
|
|
# Fall back to index-based selection only if default_data was not provided.
|
|
ids = self.order_map[category]
|
|
self.selections[category] = ids[default_idx] if ids and default_idx < len(ids) else (ids[0] if ids else None)
|
|
|
|
|
|
def _ensure_valid(self, category):
|
|
"""Generic validator: resets selection to first valid option, or None if none exist."""
|
|
filter_func = self._filter_map.get(category)
|
|
if not filter_func:
|
|
return
|
|
|
|
current_val = self.selections.get(category)
|
|
# If current selection is invalid (or None), try to find a replacement
|
|
if current_val is None or not filter_func(current_val):
|
|
found_valid = False
|
|
for candidate_id in self.order_map.get(category, []):
|
|
if filter_func(candidate_id):
|
|
self.selections[category] = candidate_id
|
|
found_valid = True
|
|
break
|
|
|
|
# If no valid option is found, set to None to trigger blank image
|
|
if not found_valid:
|
|
self.selections[category] = None
|
|
|
|
def cycle_selection(self, category, direction):
|
|
ids = self.order_map.get(category, [])
|
|
if not ids:
|
|
self.selections[category] = None
|
|
self._notify(category)
|
|
return None
|
|
|
|
current_id = self.selections.get(category)
|
|
current_index = ids.index(current_id) if current_id in ids else 0
|
|
filter_func = self._filter_map.get(category)
|
|
|
|
found_valid = False
|
|
for i in range(1, len(ids) + 1):
|
|
next_index = (current_index + (i * direction)) % len(ids)
|
|
candidate_id = ids[next_index]
|
|
if filter_func is None or filter_func(candidate_id):
|
|
self.selections[category] = candidate_id
|
|
found_valid = True
|
|
break
|
|
|
|
# If we cycled through everything and found nothing valid, set to None
|
|
if not found_valid:
|
|
self.selections[category] = None
|
|
|
|
# Reactive Updates
|
|
dependents = self._dependency_map.get(category, [])
|
|
|
|
# 1. Notify the category that was just cycled
|
|
self._notify(category)
|
|
|
|
# 2. Check and notify all dependents (e.g., Type -> Browser)
|
|
for dep in dependents:
|
|
self._ensure_valid(dep)
|
|
self._notify(dep)
|
|
|
|
return self.get_current_image(category)
|
|
|
|
def _notify(self, category):
|
|
"""Triggers the UI callback for a specific category."""
|
|
if category in self.listeners:
|
|
self.listeners[category]()
|
|
|
|
|
|
def get_current_image(self, category):
|
|
"""Returns an image or a path to one depending on the category and data format"""
|
|
|
|
current_id = self.selections.get(category)
|
|
|
|
if current_id is None:
|
|
return blank_button(self.btn_path)
|
|
|
|
# Cache check
|
|
cache_key = f"{category}_{current_id}"
|
|
if cache_key in self.pixmap_cache:
|
|
return self.pixmap_cache[cache_key]
|
|
|
|
# 1. HANDLE DYNAMIC CATEGORIES FIRST
|
|
# These categories build images from the ID itself and don't need a lookup table
|
|
if category == "resolution":
|
|
res_img = create_resolution_button_image(
|
|
btn_path=f"{self.btn_path}/resolution_template.png",
|
|
resolution_text=str(current_id)
|
|
)
|
|
self.pixmap_cache[cache_key] = res_img
|
|
return res_img
|
|
|
|
# 2. HANDLE DATA-DRIVEN CATEGORIES
|
|
# Only perform the lookup for categories that actually use the all_options dictionary
|
|
try:
|
|
data = self.all_options[category][current_id]
|
|
except KeyError:
|
|
print(f"Error: {current_id} not found in {category} options. Returning blank.")
|
|
return blank_button(self.btn_path)
|
|
|
|
if data is None:
|
|
return blank_button(self.btn_path)
|
|
|
|
if isinstance(data, Path):
|
|
return data
|
|
|
|
if isinstance(data, dict):
|
|
pixmap = create_button_image(
|
|
first_line=data.get('name', ''),
|
|
fallback_image_path=data.get('path'),
|
|
second_line=data.get('second_line'),
|
|
existing_icon_path=data.get('existing_icon')
|
|
)
|
|
self.pixmap_cache[cache_key] = pixmap
|
|
return pixmap
|
|
else:
|
|
return blank_button(self.btn_path)
|
|
|
|
# Validation logic, used by the generic _ensure_valid
|
|
def is_app_valid(self, app_choice):
|
|
current_type = self.selections.get("type")
|
|
return app_or_display_matches_profile_type(app_choice=app_choice, profile_type=current_type)
|
|
|
|
def is_protocol_valid(self, protocol_id):
|
|
"""Checks if a protocol is valid by the other choices of type and location."""
|
|
current_type = self.selections.get("type")
|
|
current_location = self.selections.get("location")
|
|
|
|
if not protocol_matches_profile_type(protocol=protocol_id, profile_type=current_type):
|
|
return False
|
|
|
|
return protocol_is_supported_for_location(location_id=current_location, protocol_choice=protocol_id)
|
|
|
|
def is_resolution_valid(self, resolution_choice):
|
|
current_type = self.selections.get("type")
|
|
|
|
# same criteria as app:
|
|
if not app_or_display_matches_profile_type(app_choice=resolution_choice, profile_type=current_type):
|
|
return False
|
|
|
|
# plus size filter:
|
|
return validate_selected_resolution(resolution_choice)
|
|
|
|
def set_selection(self, category, value):
|
|
"""Manually set a selection, validate it, and notify listeners."""
|
|
|
|
# 1. Validate the choice using the existing filter map
|
|
filter_func = self._filter_map.get(category)
|
|
if filter_func and not filter_func(value):
|
|
print(f"Invalid selection for {category}: {value}")
|
|
return False
|
|
|
|
# 2. Update the selection
|
|
self.selections[category] = value
|
|
|
|
# 3. Trigger reactive updates for dependents (e.g., if Type changed)
|
|
dependents = self._dependency_map.get(category, [])
|
|
for dep in dependents:
|
|
self._ensure_valid(dep)
|
|
self._notify(dep)
|
|
|
|
# 4. Notify the UI for this category
|
|
self._notify(category)
|
|
return True
|
|
|
|
|
|
def get_final_choices(self):
|
|
return self.selections
|
|
|
|
def _get_transition_skip(self, skip_type="real"):
|
|
"""
|
|
Handles mapping of profile transitions to skip lists.
|
|
skip_type: 'real' for data changes, 'warning' for UI alerts.
|
|
"""
|
|
# Define transition rules: (original, new) -> [keys to skip]
|
|
rules = {
|
|
"warning": {
|
|
(ProfileType.SYSTEM, ProfileType.SESSION): ["browser"],
|
|
},
|
|
"real": {
|
|
# If new is SYSTEM and original is either SYSTEM or None
|
|
# We handle the 'None' case by checking the transition specifically
|
|
(ProfileType.SYSTEM, ProfileType.SYSTEM): ["browser", "resolution"],
|
|
(None, ProfileType.SYSTEM): ["browser", "resolution"],
|
|
}
|
|
}
|
|
|
|
orig = self.original_choices.get("type")
|
|
new = self.selections.get("type")
|
|
return rules.get(skip_type, {}).get((orig, new), [])
|
|
|
|
def whats_different(self):
|
|
"""Creates a dictionary of actual value differences."""
|
|
if not self.original_choices:
|
|
return self.selections
|
|
|
|
different = {}
|
|
# skip_list = self._get_transition_skip(skip_type="real")
|
|
|
|
# Get a union of all keys to ensure we catch removals and additions
|
|
all_keys = set(self.selections.keys()) | set(self.original_choices.keys())
|
|
|
|
for key in all_keys:
|
|
# only pay attention to the universe of keys we actually are deciding here
|
|
if key not in self.key_choices:
|
|
continue
|
|
|
|
# if key in skip_list:
|
|
# continue
|
|
|
|
old_val = self.original_choices.get(key)
|
|
new_val = self.selections.get(key)
|
|
|
|
if old_val != new_val:
|
|
different[key] = new_val
|
|
|
|
return different
|
|
|
|
def before_we_proceed(self) -> PreEdit:
|
|
different_dict = self.whats_different()
|
|
if not different_dict:
|
|
return PreEdit(True, False, None, None)
|
|
|
|
# 1. Filter differences by the warning skip list
|
|
warning_skip = self._get_transition_skip(skip_type="warning")
|
|
warning_keys = [k for k in different_dict if k not in warning_skip]
|
|
|
|
# 2. Map keys to their specific warning messages
|
|
WARNING_MESSAGES = {
|
|
"location": lambda: "If you change the location, it wipes the subscription, proceed?"
|
|
if not self.location_down
|
|
and not profile_can_respawn(self.profile_id).valid
|
|
and profile_can_respawn(self.profile_id).error_type != ResultError.SUBSCRIPTION
|
|
else None,
|
|
"browser": lambda: "If you change the browser, it wipes the cookies/bookmarks, proceed?"
|
|
}
|
|
|
|
warnings_dict = {}
|
|
for key in warning_keys:
|
|
rule = WARNING_MESSAGES.get(key)
|
|
msg = rule() if callable(rule) else rule
|
|
if msg:
|
|
warnings_dict[key] = msg
|
|
|
|
|
|
has_warnings = bool(warnings_dict)
|
|
self.warnings_dict = warnings_dict
|
|
|
|
# Determine if we can proceed based on the 'proceed' state and whether warnings exist
|
|
can_proceed = self.proceed if has_warnings else True
|
|
return PreEdit(can_proceed, has_warnings, warnings_dict, different_dict)
|
|
|
|
def is_anything_different(self):
|
|
different_dict = self.whats_different()
|
|
return bool(different_dict)
|