File size: 4,614 Bytes
5c6037b
de50ad7
e96a62a
 
88e9f1a
5c6037b
e96a62a
 
de50ad7
 
3a2ce2a
 
5c6037b
e96a62a
de50ad7
5c6037b
cd03aa3
87175db
e96a62a
87175db
5c6037b
87175db
 
3a2ce2a
de50ad7
5c6037b
87175db
de50ad7
87175db
 
de50ad7
 
87175db
 
 
de50ad7
 
87175db
5c6037b
cd03aa3
de50ad7
87175db
5c6037b
3a2ce2a
 
 
e96a62a
88e9f1a
 
 
cd03aa3
 
 
 
 
 
88e9f1a
cd03aa3
 
88e9f1a
 
e96a62a
 
 
88e9f1a
cd03aa3
 
de50ad7
5c6037b
 
 
 
 
de50ad7
 
 
 
 
 
 
 
 
 
 
 
 
5c6037b
3a2ce2a
 
 
 
5c6037b
 
3a2ce2a
5c6037b
88e9f1a
 
5c6037b
3a2ce2a
 
5c6037b
 
 
3a2ce2a
cd03aa3
3a2ce2a
de50ad7
cd03aa3
88e9f1a
5c6037b
 
de50ad7
5c6037b
3a2ce2a
 
88e9f1a
 
3a2ce2a
e96a62a
88e9f1a
 
 
 
 
 
 
 
e96a62a
de50ad7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
from flask import Flask, render_template_string
from flask_socketio import SocketIO
from apscheduler.schedulers.background import BackgroundScheduler
import subprocess
import threading
from datetime import datetime

app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*")  # Enable WebSocket

execution_logs = []
MAX_LOG_ENTRIES = 20

def run_cli_script():
    """Runs cli.py and streams logs in real-time."""
    timestamp = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
    log_entry = {'time': timestamp, 'output': '', 'error': ''}

    try:
        process = subprocess.Popen(
            ["python", "cli.py"],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            bufsize=1
        )

        # Stream logs in real-time to UI
        for line in process.stdout:
            log_entry['output'] += line
            socketio.emit('log_update', {'time': timestamp, 'output': line, 'error': ''})  # Send to UI
            print(line, end="")  # Print to terminal for debugging

        for line in process.stderr:
            log_entry['error'] += line
            socketio.emit('log_update', {'time': timestamp, 'output': '', 'error': line})  # Send to UI
            print(line, end="")

    except Exception as e:
        log_entry['error'] = str(e)
        socketio.emit('log_update', {'time': timestamp, 'output': '', 'error': str(e)})  # Send error to UI

    finally:
        execution_logs.append(log_entry)
        if len(execution_logs) > MAX_LOG_ENTRIES:
            execution_logs.pop(0)

def start_initial_run():
    threading.Thread(target=run_cli_script, daemon=True).start()

scheduler = BackgroundScheduler(daemon=True)
scheduler.add_job(
    run_cli_script,
    'interval',
    hours=3,
    id='main_job',
    next_run_time=datetime.now()
)
scheduler.start()

start_initial_run()

@app.route('/')
def home():
    """Main UI displaying logs and next run time."""
    job = scheduler.get_job('main_job')
    next_run = job.next_run_time.strftime('%Y-%m-%d %H:%M:%S UTC') if job else 'N/A'

    return render_template_string('''
        <!DOCTYPE html>
        <html>
        <head>
            <title>Script Scheduler</title>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
            <script>
                var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
                socket.on('log_update', function(data) {
                    var logBox = document.getElementById("log-box");
                    var logEntry = "<div class='timestamp'>" + data.time + "</div>";
                    if (data.output) logEntry += "<div class='output'>" + data.output + "</div>";
                    if (data.error) logEntry += "<div class='error'>" + data.error + "</div>";
                    logEntry += "<hr>";
                    logBox.innerHTML += logEntry;  // Append new logs
                    logBox.scrollTop = logBox.scrollHeight;  // Auto-scroll to bottom
                });
            </script>
            <style>
                body { font-family: Arial, sans-serif; padding: 20px; }
                .log-box { 
                    background: #000; 
                    color: #0f0; 
                    padding: 15px; 
                    border-radius: 5px; 
                    margin-top: 20px;
                    white-space: pre-wrap;
                    max-height: 400px;
                    overflow-y: auto;
                }
                .timestamp { color: #888; margin-bottom: 10px; }
                .error { color: #ff4444; }
            </style>
        </head>
        <body>
            <h1>Script Scheduler</h1>
            <p>Next run: {{ next_run }}</p>
            <h2>Latest Execution Logs</h2>
            <div id="log-box" class="log-box"></div>
            <p><a href="/force-run">Trigger Manual Run</a></p>
            <p><a href="/run-check">Check Scheduler Status</a></p>
        </body>
        </html>
    ''', next_run=next_run)

@app.route('/force-run')
def force_run():
    """Manually trigger the script execution."""
    threading.Thread(target=run_cli_script, daemon=True).start()
    return "Script executed manually", 200

@app.route('/run-check')
def run_check():
    """Check if the scheduler is still running."""
    if not scheduler.running:
        print("Scheduler was stopped! Restarting...")
        scheduler.start()
    return "Scheduler is running", 200

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0', port=7860, allow_unsafe_werkzeug=True)