MQL5-Google-Onedrive/scripts/web_dashboard.py

212 lines
9.4 KiB
Python
Raw Permalink Normal View History

import os
import sys
import logging
from flask import Flask, render_template_string, jsonify
import markdown
import time
import threading
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
app = Flask(__name__)
# Cache storage: filepath -> (mtime, html_content)
_content_cache = {}
# Thread-local storage for Markdown instances to avoid re-initialization overhead
_md_local = threading.local()
# Constants for paths to avoid re-calculating on every request
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
README_PATH = os.path.join(BASE_DIR, '..', 'README.md')
VERIFICATION_PATH = os.path.join(BASE_DIR, '..', 'VERIFICATION.md')
# HTML Template
DASHBOARD_HTML = """
<!DOCTYPE html>
<html>
<head>
<title>MQL5 Trading Automation Dashboard</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; line-height: 1.6; max-width: 1000px; margin: 0 auto; padding: 20px; background: #f0f2f5; color: #1c1e21; }
.card { background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin-bottom: 20px; }
h1, h2 { color: #050505; border-bottom: 1px solid #ddd; padding-bottom: 10px; }
pre { background: #f8f9fa; padding: 15px; border-radius: 5px; overflow-x: auto; border: 1px solid #eee; }
.status-badge { display: inline-block; padding: 4px 12px; border-radius: 15px; font-weight: bold; background: #42b983; color: white; }
.nav { margin-bottom: 20px; background: #fff; padding: 10px 20px; border-radius: 8px; box-shadow: 0 1px 2px rgba(0,0,0,0.1); }
.nav a { margin-right: 15px; color: #1877f2; text-decoration: none; font-weight: bold; }
.nav a:hover { text-decoration: underline; }
footer { text-align: center; margin-top: 40px; color: #65676b; font-size: 0.9em; }
img { max-width: 100%; height: auto; }
table { border-collapse: collapse; width: 100%; margin-bottom: 1em; }
th, td { text-align: left; padding: 8px; border-bottom: 1px solid #ddd; }
th { background-color: #f8f9fa; }
.skip-link { position: absolute; top: -40px; left: 0; background: #42b983; color: white; padding: 8px; z-index: 100; transition: top 0.3s; text-decoration: none; border-radius: 0 0 8px 0; font-weight: 600; }
.skip-link:focus { top: 0; }
.status-value { font-weight: bold; color: #42b983; display: flex; align-items: center; gap: 8px; }
.copy-btn { background: none; border: none; padding: 4px; cursor: pointer; color: #6b7280; border-radius: 4px; display: flex; align-items: center; transition: all 0.2s; }
.copy-btn:hover { background-color: #f3f4f6; color: #42b983; }
.copy-btn:focus-visible { outline: 2px solid #42b983; outline-offset: 2px; }
</style>
</head>
<body>
<a href="#status" class="skip-link">Skip to main content</a>
<div class="nav">
<a href="#status">System Status</a>
<a href="#docs">Documentation</a>
</div>
<div id="status" class="card">
<h1>System Status <span class="status-badge">ONLINE</span></h1>
<p>MQL5 Trading Automation is running.</p>
<div style="margin: 20px 0; border: 1px solid #eee; border-radius: 8px; padding: 15px;">
<div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #eee;">
<span style="font-weight: 600; color: #666;">Fly.io App</span>
<span class="status-value">
mql5-automation
<button class="copy-btn" aria-label="Copy Fly.io App name" data-clipboard-text="mql5-automation">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>
</button>
</span>
</div>
<div style="display: flex; justify-content: space-between; padding: 10px 0;">
<span style="font-weight: 600; color: #666;">Telegram Bot</span>
<span class="status-value">
@GenX_FX_bot
<button class="copy-btn" aria-label="Copy Telegram Bot handle" data-clipboard-text="@GenX_FX_bot">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>
</button>
</span>
</div>
</div>
{{ html_verification|safe }}
</div>
<div id="docs" class="card">
<h2>Project Documentation</h2>
{{ html_readme|safe }}
</div>
<footer>
<p>&copy; {{ year }} MQL5 Trading Automation | Dashboard v1.0.0</p>
</footer>
<script>
document.querySelectorAll('.copy-btn').forEach(btn => {
btn.addEventListener('click', async () => {
const text = btn.getAttribute('data-clipboard-text');
try {
await navigator.clipboard.writeText(text);
const originalHTML = btn.innerHTML;
btn.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#42b983" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>';
setTimeout(() => { btn.innerHTML = originalHTML; }, 2000);
} catch (err) { console.error('Failed to copy:', err); }
});
});
</script>
</body>
</html>
"""
# Global to store compiled template
DASHBOARD_TEMPLATE = None
def get_cached_markdown(filepath):
"""
Returns the markdown content of a file converted to HTML, using a cache
that invalidates based on file modification time.
Optimization: Uses os.stat() to get mtime and check existence in one syscall.
"""
try:
# Optimization: os.stat gets existence and mtime in one call
# removing the need for separate os.path.exists() check
stat_result = os.stat(filepath)
except OSError:
return None
try:
mtime = stat_result.st_mtime
if filepath in _content_cache:
cached_mtime, cached_html = _content_cache[filepath]
if cached_mtime == mtime:
return cached_html
# Cache miss or file changed
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
# ⚡ Performance Optimization: Reuse Markdown instance via thread-local storage
if not hasattr(_md_local, 'md'):
_md_local.md = markdown.Markdown()
_md_local.md.reset()
html_content = _md_local.md.convert(content)
_content_cache[filepath] = (mtime, html_content)
return html_content
except Exception as e:
print(f"Error reading/converting {filepath}: {e}")
return None
@app.route('/health')
def health_check():
"""Lightweight health check for load balancers."""
return jsonify({
"status": "healthy",
"timestamp": time.time()
})
@app.after_request
def add_security_headers(response):
"""
Add security headers to every response to protect against
XSS, Clickjacking, and other web vulnerabilities.
"""
# Content-Security-Policy: restrict sources of content
# default-src 'self': only allow content from own origin
# style-src 'self' 'unsafe-inline': allow inline styles (needed for template)
# script-src 'self': only allow scripts from own origin (blocks inline scripts in markdown)
csp = "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'"
response.headers['Content-Security-Policy'] = csp
# X-Content-Type-Options: prevent MIME-sniffing
response.headers['X-Content-Type-Options'] = 'nosniff'
# X-Frame-Options: prevent clickjacking
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
# Referrer-Policy: control referrer information
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
return response
@app.route('/')
def dashboard():
global DASHBOARD_TEMPLATE
try:
# Use pre-calculated paths
html_readme = get_cached_markdown(README_PATH) or "<p>README.md not found.</p>"
html_verification = get_cached_markdown(VERIFICATION_PATH) or "<p>VERIFICATION.md not found.</p>"
# ⚡ Performance Optimization: Compile template once instead of every request
if DASHBOARD_TEMPLATE is None:
DASHBOARD_TEMPLATE = app.jinja_env.from_string(DASHBOARD_HTML)
return DASHBOARD_TEMPLATE.render(html_readme=html_readme, html_verification=html_verification, year=2026)
except Exception as e:
logger.error(f"Error rendering dashboard: {e}", exc_info=True)
return "Internal Server Error", 500
if __name__ == '__main__':
port = int(os.environ.get('PORT', 8080))
print(f"Starting web dashboard on port {port}...")
app.run(host='0.0.0.0', port=port)