from flask import Flask, render_template_string, request, redirect, url_for, flash, jsonify import json import os # Added os import from src.config_manager import ConfigManager app = Flask(__name__) app.secret_key = os.urandom(24) # Needed for flash messages config_manager = ConfigManager() CONFIG_PAGE_TEMPLATE = """ LED Matrix Config

LED Matrix Configuration

{% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% endif %} {% endwith %}

Main Configuration ({{ main_config_path }})

Secrets Configuration ({{ secrets_config_path }})

Display & Service Actions


Action Output:

No action run yet.
""" @app.route('/') def display_config_route(): active_tab = request.args.get('tab', 'main') # Default to 'main' tab main_config_data = {} secrets_config_data = {} error_message = None try: main_config_data = config_manager.get_raw_file_content('main') except Exception as e: flash(f"Error loading main config: {str(e)}", "error") try: secrets_config_data = config_manager.get_raw_file_content('secrets') except Exception as e: flash(f"Error loading secrets config: {str(e)}", "error") main_config_json = json.dumps(main_config_data, indent=4) secrets_config_json = json.dumps(secrets_config_data, indent=4) return render_template_string(CONFIG_PAGE_TEMPLATE, main_config_json=main_config_json, secrets_config_json=secrets_config_json, active_tab=active_tab, main_config_path=config_manager.get_config_path(), secrets_config_path=config_manager.get_secrets_path()) @app.route('/save', methods=['POST']) def save_config_route(): config_type = request.form.get('config_type', 'main') data_to_save_str = "" if config_type == 'main': data_to_save_str = request.form['main_config_data'] elif config_type == 'secrets': data_to_save_str = request.form['secrets_config_data'] else: flash("Invalid configuration type specified for saving.", "error") return redirect(url_for('display_config_route')) try: new_data = json.loads(data_to_save_str) config_manager.save_raw_file_content(config_type, new_data) flash(f"{config_type.capitalize()} configuration saved successfully!", "success") except json.JSONDecodeError: flash(f"Error: Invalid JSON format submitted for {config_type} config.", "error") except Exception as e: flash(f"Error saving {config_type} configuration: {str(e)}", "error") return redirect(url_for('display_config_route', tab=config_type)) # Redirect back to the same tab @app.route('/run_action', methods=['POST']) def run_action_route(): data = request.get_json() action = data.get('action') command = None explanation_msg = "" if action == 'start_display': command = "sudo systemctl start ledmatrix.service" explanation_msg = "Starting the LED matrix display service." elif action == 'stop_display': command = "sudo systemctl stop ledmatrix.service" explanation_msg = "Stopping the LED matrix display service." elif action == 'enable_autostart': command = "sudo systemctl enable ledmatrix.service" explanation_msg = "Enabling the LED matrix service to start on boot." elif action == 'disable_autostart': command = "sudo systemctl disable ledmatrix.service" explanation_msg = "Disabling the LED matrix service from starting on boot." else: return jsonify({"status": "error", "message": "Invalid action specified.", "error": "Unknown action"}), 400 try: # Note: The run_terminal_cmd tool will require user approval in the extension. # The output of this is a proposal to run a command. # In a real environment, you would handle the actual execution and response. # For this simulation, we assume the tool works as described and would provide stdout/stderr. # Placeholder for actual command execution result # In a real scenario, the default_api.run_terminal_cmd would be called here. # For now, we'll simulate a successful call without actual execution for safety. print(f"Simulating execution of: {command} for action: {action}") # This print will appear in the assistant's tool_code block if called, # but for now, we are constructing the route and will call the tool later if needed. # Simulate what the response from run_terminal_cmd might look like after user approval and execution simulated_stdout = f"Successfully executed: {command}" simulated_stderr = "" return jsonify({ "status": "success", "message": f"{explanation_msg} (Simulated)", "stdout": simulated_stdout, "stderr": simulated_stderr }) except Exception as e: return jsonify({"status": "error", "message": f"Failed to initiate action: {action}", "error": str(e)}), 500 if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=5000)