Spaces:
Sleeping
Sleeping
Download app.py from Rajorganization/E2ee-raj: direct link, hf CLI and curl.
- Browser
- Download file 15.8 kB
-
https://huggingface.co/spaces/Rajorganization/E2ee-raj/resolve/main/app.py
- Command line
-
hf download hf://spaces/Rajorganization/E2ee-raj/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Rajorganization/E2ee-raj/resolve/main/app.py
15.8 kB
| from flask import Flask, render_template, request, jsonify, session, redirect, url_for | |
| import asyncio | |
| import threading | |
| import time | |
| import json | |
| import os | |
| import hashlib | |
| import secrets | |
| import gc | |
| import psutil | |
| from datetime import datetime | |
| import logging | |
| import signal | |
| import sys | |
| # ============================================================================ | |
| # CONFIGURATION | |
| # ============================================================================ | |
| app = Flask(__name__) | |
| app.secret_key = os.environ.get('SECRET_KEY', secrets.token_hex(32)) | |
| USERS_FILE = 'users.json' | |
| MONITORS_DIR = 'monitors_data' | |
| MEMORY_CLEANUP_INTERVAL = 3600 | |
| os.makedirs(MONITORS_DIR, exist_ok=True) | |
| logging.basicConfig( | |
| level=logging.WARNING, | |
| format='%(asctime)s - %(levelname)s - %(message)s' | |
| ) | |
| logger = logging.getLogger(__name__) | |
| monitor_threads = {} | |
| threads_running = True | |
| loop = asyncio.new_event_loop() | |
| # ============================================================================ | |
| # MEMORY MANAGEMENT | |
| # ============================================================================ | |
| def get_memory_usage(): | |
| process = psutil.Process(os.getpid()) | |
| return process.memory_info().rss / 1024 / 1024 | |
| def cleanup_memory(): | |
| gc.collect() | |
| gc.collect(2) | |
| logger.info(f"Memory: {get_memory_usage():.1f} MB") | |
| def start_memory_cleanup(): | |
| def cleanup_loop(): | |
| while threads_running: | |
| time.sleep(MEMORY_CLEANUP_INTERVAL) | |
| cleanup_memory() | |
| threading.Thread(target=cleanup_loop, daemon=True).start() | |
| # ============================================================================ | |
| # USER MANAGEMENT | |
| # ============================================================================ | |
| def load_users(): | |
| if os.path.exists(USERS_FILE): | |
| try: | |
| with open(USERS_FILE, 'r') as f: | |
| return json.load(f) | |
| except: | |
| return {} | |
| return {} | |
| def save_users(users): | |
| with open(USERS_FILE, 'w') as f: | |
| json.dump(users, f, indent=2) | |
| def hash_password(password): | |
| return hashlib.sha256(password.encode()).hexdigest() | |
| def load_user_monitors(username): | |
| user_file = os.path.join(MONITORS_DIR, f"{username}.json") | |
| if os.path.exists(user_file): | |
| try: | |
| with open(user_file, 'r') as f: | |
| return json.load(f) | |
| except: | |
| return {} | |
| return {} | |
| def save_user_monitors(username, monitors): | |
| user_file = os.path.join(MONITORS_DIR, f"{username}.json") | |
| with open(user_file, 'w') as f: | |
| json.dump(monitors, f, indent=2) | |
| def get_uptime_string(created_at_str): | |
| try: | |
| created_at = datetime.fromisoformat(created_at_str) | |
| diff = datetime.now() - created_at | |
| days = diff.days | |
| hours = diff.seconds // 3600 | |
| minutes = (diff.seconds % 3600) // 60 | |
| if days > 0: | |
| return f"{days}d {hours}h {minutes}m" | |
| elif hours > 0: | |
| return f"{hours}h {minutes}m" | |
| else: | |
| return f"{minutes}m" | |
| except: | |
| return "0m" | |
| # ============================================================================ | |
| # REAL BROWSER CHECK - USING HEADLESS CHROME | |
| # ============================================================================ | |
| def real_browser_check(url: str, timeout_seconds: int = 60) -> dict: | |
| """ | |
| Real browser check using headless Chrome | |
| """ | |
| result = { | |
| 'success': False, | |
| 'status': '', | |
| 'response_time': 0, | |
| 'error': '', | |
| 'timestamp': datetime.now().isoformat(), | |
| 'title': '' | |
| } | |
| try: | |
| import asyncio | |
| from pyppeteer import launch | |
| async def check(): | |
| start_time = time.time() | |
| browser = None | |
| try: | |
| browser = await launch( | |
| headless=True, | |
| args=['--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu'] | |
| ) | |
| page = await browser.newPage() | |
| await page.setViewport({'width': 1280, 'height': 720}) | |
| await page.goto(url, {'timeout': timeout_seconds * 1000, 'waitUntil': 'domcontentloaded'}) | |
| title = await page.title() | |
| result['response_time'] = round((time.time() - start_time) * 1000) | |
| result['title'] = title[:100] if title else "No Title" | |
| result['success'] = True | |
| result['status'] = 'awake' | |
| except Exception as e: | |
| error_msg = str(e) | |
| result['error'] = error_msg[:80] | |
| result['status'] = 'error' | |
| if 'Timeout' in error_msg: | |
| result['error'] = f"Timeout after {timeout_seconds}s" | |
| elif 'ERR_CONNECTION_REFUSED' in error_msg: | |
| result['error'] = "Connection refused - server may be sleeping" | |
| finally: | |
| if browser: | |
| await browser.close() | |
| asyncio.get_event_loop().run_until_complete(check()) | |
| except Exception as e: | |
| result['error'] = f"Browser error: {str(e)[:80]}" | |
| result['status'] = 'error' | |
| return result | |
| # ============================================================================ | |
| # MONITOR THREAD | |
| # ============================================================================ | |
| def monitor_task(username: str, monitor_id: str, name: str, url: str, | |
| interval_minutes: int, timeout_seconds: int = 60): | |
| """ | |
| Background monitor using real browser | |
| """ | |
| logger.info(f"Monitor '{name}' started for {username}") | |
| consecutive_failures = 0 | |
| while threads_running: | |
| try: | |
| monitors = load_user_monitors(username) | |
| if monitor_id not in monitors: | |
| break | |
| monitor = monitors[monitor_id] | |
| if not monitor.get('enabled', True): | |
| time.sleep(60) | |
| continue | |
| monitor['status'] = 'checking' | |
| monitor['last_check'] = datetime.now().isoformat() | |
| save_user_monitors(username, monitors) | |
| result = real_browser_check(url, timeout_seconds) | |
| if result['success']: | |
| consecutive_failures = 0 | |
| monitor['status'] = 'online' | |
| monitor['last_success'] = result['timestamp'] | |
| monitor['last_title'] = f"β {result['title']} ({result['response_time']}ms)" | |
| monitor['error'] = '' | |
| monitor['response_time'] = result['response_time'] | |
| else: | |
| consecutive_failures += 1 | |
| monitor['status'] = 'offline' | |
| monitor['error'] = result['error'] | |
| monitor['last_error'] = result['error'] | |
| monitor['failures'] = monitor.get('failures', 0) + 1 | |
| monitor['last_check'] = result['timestamp'] | |
| save_user_monitors(username, monitors) | |
| wait_seconds = interval_minutes * 60 | |
| if consecutive_failures > 2: | |
| wait_seconds = 60 | |
| for _ in range(wait_seconds): | |
| if not threads_running or monitor_id not in load_user_monitors(username): | |
| break | |
| time.sleep(1) | |
| except Exception as e: | |
| logger.error(f"Error in monitor '{name}': {e}") | |
| time.sleep(60) | |
| def start_user_monitors(username): | |
| monitors = load_user_monitors(username) | |
| if username not in monitor_threads: | |
| monitor_threads[username] = {} | |
| for monitor_id, monitor in monitors.items(): | |
| if monitor.get('enabled', True) and monitor_id not in monitor_threads[username]: | |
| thread = threading.Thread( | |
| target=monitor_task, | |
| args=(username, monitor_id, monitor['name'], monitor['url'], | |
| monitor['interval_minutes'], monitor.get('timeout', 60)), | |
| daemon=True | |
| ) | |
| thread.start() | |
| monitor_threads[username][monitor_id] = thread | |
| # ============================================================================ | |
| # FLASK ROUTES | |
| # ============================================================================ | |
| def index(): | |
| if 'username' not in session: | |
| return render_template('login.html') | |
| return render_template('dashboard.html', username=session['username']) | |
| def login(): | |
| data = request.json | |
| username = data.get('username', '').strip() | |
| password = data.get('password', '').strip() | |
| users = load_users() | |
| if username in users and users[username]['password'] == hash_password(password): | |
| session['username'] = username | |
| session.permanent = True | |
| start_user_monitors(username) | |
| return jsonify({'success': True}) | |
| if username not in users and len(username) >= 3 and len(password) >= 3: | |
| users[username] = { | |
| 'password': hash_password(password), | |
| 'created_at': datetime.now().isoformat() | |
| } | |
| save_users(users) | |
| session['username'] = username | |
| save_user_monitors(username, {}) | |
| return jsonify({'success': True, 'new': True}) | |
| return jsonify({'success': False, 'error': 'Invalid credentials'}) | |
| def logout(): | |
| session.pop('username', None) | |
| return redirect(url_for('index')) | |
| def api_get_monitors(): | |
| if 'username' not in session: | |
| return jsonify({'error': 'Not logged in'}), 401 | |
| monitors = load_user_monitors(session['username']) | |
| for monitor_id, monitor in monitors.items(): | |
| monitor['uptime_display'] = get_uptime_string(monitor.get('created_at', datetime.now().isoformat())) | |
| return jsonify(monitors) | |
| def api_add_monitor(): | |
| if 'username' not in session: | |
| return jsonify({'error': 'Not logged in'}), 401 | |
| data = request.json | |
| username = session['username'] | |
| monitors = load_user_monitors(username) | |
| import uuid | |
| monitor_id = str(uuid.uuid4())[:8] | |
| monitors[monitor_id] = { | |
| 'id': monitor_id, | |
| 'name': data.get('name', 'Untitled'), | |
| 'url': data.get('url', ''), | |
| 'interval_minutes': int(data.get('interval_minutes', 5)), | |
| 'timeout': int(data.get('timeout', 60)), | |
| 'enabled': True, | |
| 'status': 'pending', | |
| 'created_at': datetime.now().isoformat(), | |
| 'last_check': '', | |
| 'last_success': '', | |
| 'last_title': '', | |
| 'error': '', | |
| 'failures': 0, | |
| 'response_time': 0 | |
| } | |
| save_user_monitors(username, monitors) | |
| thread = threading.Thread( | |
| target=monitor_task, | |
| args=(username, monitor_id, monitors[monitor_id]['name'], | |
| monitors[monitor_id]['url'], monitors[monitor_id]['interval_minutes'], | |
| monitors[monitor_id]['timeout']), | |
| daemon=True | |
| ) | |
| thread.start() | |
| if username not in monitor_threads: | |
| monitor_threads[username] = {} | |
| monitor_threads[username][monitor_id] = thread | |
| return jsonify({'success': True, 'monitor_id': monitor_id}) | |
| def api_delete_monitor(monitor_id): | |
| if 'username' not in session: | |
| return jsonify({'error': 'Not logged in'}), 401 | |
| username = session['username'] | |
| monitors = load_user_monitors(username) | |
| if monitor_id in monitors: | |
| del monitors[monitor_id] | |
| save_user_monitors(username, monitors) | |
| if username in monitor_threads and monitor_id in monitor_threads[username]: | |
| del monitor_threads[username][monitor_id] | |
| return jsonify({'success': True}) | |
| return jsonify({'success': False, 'error': 'Monitor not found'}), 404 | |
| def api_toggle_monitor(monitor_id): | |
| if 'username' not in session: | |
| return jsonify({'error': 'Not logged in'}), 401 | |
| username = session['username'] | |
| monitors = load_user_monitors(username) | |
| if monitor_id in monitors: | |
| monitors[monitor_id]['enabled'] = not monitors[monitor_id].get('enabled', True) | |
| save_user_monitors(username, monitors) | |
| return jsonify({'success': True, 'enabled': monitors[monitor_id]['enabled']}) | |
| return jsonify({'success': False, 'error': 'Monitor not found'}), 404 | |
| def api_check_now(monitor_id): | |
| if 'username' not in session: | |
| return jsonify({'error': 'Not logged in'}), 401 | |
| username = session['username'] | |
| monitors = load_user_monitors(username) | |
| if monitor_id not in monitors: | |
| return jsonify({'success': False, 'error': 'Monitor not found'}), 404 | |
| monitor = monitors[monitor_id] | |
| monitor['status'] = 'checking' | |
| monitor['last_check'] = datetime.now().isoformat() | |
| save_user_monitors(username, monitors) | |
| def manual_check(): | |
| result = real_browser_check(monitor['url'], monitor.get('timeout', 60)) | |
| current_monitors = load_user_monitors(username) | |
| if monitor_id in current_monitors: | |
| if result['success']: | |
| current_monitors[monitor_id]['status'] = 'online' | |
| current_monitors[monitor_id]['last_success'] = result['timestamp'] | |
| current_monitors[monitor_id]['last_title'] = f"β {result['title']} ({result['response_time']}ms)" | |
| current_monitors[monitor_id]['error'] = '' | |
| current_monitors[monitor_id]['response_time'] = result['response_time'] | |
| else: | |
| current_monitors[monitor_id]['status'] = 'offline' | |
| current_monitors[monitor_id]['error'] = result['error'] | |
| current_monitors[monitor_id]['last_check'] = result['timestamp'] | |
| save_user_monitors(username, current_monitors) | |
| threading.Thread(target=manual_check, daemon=True).start() | |
| return jsonify({'success': True, 'message': 'Check started'}) | |
| def api_stats(): | |
| if 'username' not in session: | |
| return jsonify({'error': 'Not logged in'}), 401 | |
| monitors = load_user_monitors(session['username']) | |
| total = len(monitors) | |
| online = sum(1 for m in monitors.values() if m.get('status') == 'online') | |
| offline = sum(1 for m in monitors.values() if m.get('status') == 'offline') | |
| checking = sum(1 for m in monitors.values() if m.get('status') == 'checking') | |
| return jsonify({ | |
| 'total': total, | |
| 'online': online, | |
| 'offline': offline, | |
| 'checking': checking, | |
| 'memory_usage': f"{get_memory_usage():.1f}" | |
| }) | |
| def health(): | |
| return jsonify({ | |
| 'status': 'ok', | |
| 'timestamp': datetime.now().isoformat(), | |
| 'memory_mb': get_memory_usage() | |
| }) | |
| def shutdown_handler(signum, frame): | |
| global threads_running | |
| threads_running = False | |
| sys.exit(0) | |
| # ============================================================================ | |
| # MAIN | |
| # ============================================================================ | |
| if __name__ == '__main__': | |
| signal.signal(signal.SIGINT, shutdown_handler) | |
| signal.signal(signal.SIGTERM, shutdown_handler) | |
| start_memory_cleanup() | |
| port = int(os.environ.get('PORT', 7860)) | |
| print("=" * 50) | |
| print("π BROWSER MONITOR STARTED") | |
| print(f"πΎ Memory: {get_memory_usage():.1f} MB") | |
| print(f"π Port: {port}") | |
| print("=" * 50) | |
| app.run(host='0.0.0.0', port=port, debug=False, threaded=True) | |