-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
188 lines (159 loc) · 5.98 KB
/
Copy pathapp.py
File metadata and controls
188 lines (159 loc) · 5.98 KB
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import os
import subprocess
import threading
import uuid
import time
from queue import Queue
from flask import Flask, render_template, request, jsonify
app = Flask(__name__)
# Thread-safe task state storage
tasks_lock = threading.Lock()
task_list = [] # List of all task dicts (to preserve order and historical status)
active_process = None # Current running subprocess
# Queue for pending tasks (stores task IDs)
pending_queue = Queue()
def worker_loop():
global active_process
while True:
# Blocks until a task ID is available in the queue
task_id = pending_queue.get()
# Find the task
task = None
with tasks_lock:
for t in task_list:
if t["id"] == task_id:
task = t
break
if not task or task["status"] == "cancelled":
pending_queue.task_done()
continue
# Update status to running
with tasks_lock:
task["status"] = "running"
print(f"[Worker] Starting task {task_id}: {task['action_type']}...")
# Build command
script_path = os.path.join(os.path.dirname(__file__), 'run_automation.py')
cmd = [
"python", script_path,
"--action-type", task["action_type"],
"--max-friends", str(task["max_friends"]),
"--idx", str(task["window_idx"]),
"--min-delay", str(task["min_delay"]),
"--max-delay", str(task["max_delay"]),
"--reaction", task["reaction"]
]
try:
# Run the command and wait for completion
active_process = subprocess.Popen(cmd)
return_code = active_process.wait()
active_process = None
with tasks_lock:
# If it was cancelled in the meantime, keep it cancelled
if task["status"] == "running":
if return_code == 0:
task["status"] = "completed"
else:
task["status"] = "failed"
task["error"] = f"Exit code {return_code}"
except Exception as e:
with tasks_lock:
if task["status"] == "running":
task["status"] = "failed"
task["error"] = str(e)
active_process = None
print(f"[Worker] Finished task {task_id} with status: {task['status']}.")
pending_queue.task_done()
# Start background thread
worker_thread = threading.Thread(target=worker_loop, daemon=True)
worker_thread.start()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/queue', methods=['GET'])
def get_queue():
with tasks_lock:
return jsonify({
"success": True,
"tasks": list(task_list)
})
@app.route('/api/queue/enqueue', methods=['POST'])
def enqueue_task():
data = request.json
action_type = data.get('action_type', 'accept')
max_friends = data.get('max_friends', 5)
window_idx = data.get('window_idx', 0)
min_delay = data.get('min_delay', 2.0)
max_delay = data.get('max_delay', 5.0)
reaction = data.get('reaction', 'like')
try:
max_friends = int(max_friends)
window_idx = int(window_idx)
min_delay = float(min_delay)
max_delay = float(max_delay)
if reaction not in ["like", "love", "haha", "wow", "sad", "angry", "care", "decide"]:
reaction = "like"
except ValueError:
return jsonify({"success": False, "message": "Invalid input types."}), 400
task_id = str(uuid.uuid4())[:8]
new_task = {
"id": task_id,
"action_type": action_type,
"max_friends": max_friends,
"window_idx": window_idx,
"min_delay": min_delay,
"max_delay": max_delay,
"reaction": reaction,
"status": "pending",
"error": None
}
with tasks_lock:
task_list.append(new_task)
pending_queue.put(task_id)
return jsonify({
"success": True,
"message": f"Task enqueued! Mode: {action_type.upper()} ({max_friends} actions).",
"task": new_task
})
# Backward compatibility for the legacy dashboard button
@app.route('/api/start-automation', methods=['POST'])
def start_automation():
return enqueue_task()
@app.route('/api/queue/clear', methods=['POST'])
def clear_queue():
global active_process
with tasks_lock:
if active_process:
try:
active_process.terminate()
except Exception:
pass
active_process = None
task_list.clear()
global pending_queue
with pending_queue.mutex:
pending_queue.queue.clear()
return jsonify({"success": True, "message": "All tasks cleared and cancelled."})
@app.route('/api/queue/remove/<task_id>', methods=['POST'])
def remove_task(task_id):
global active_process
with tasks_lock:
for task in task_list:
if task["id"] == task_id:
if task["status"] == "running":
if active_process:
try:
active_process.terminate()
except Exception:
pass
active_process = None
task["status"] = "cancelled"
elif task["status"] == "pending":
task["status"] = "cancelled"
else:
# Clear completed/failed history if clicked remove
task_list.remove(task)
return jsonify({"success": True, "message": "Task removed from history."})
return jsonify({"success": True, "message": f"Task {task_id} cancelled."})
return jsonify({"success": False, "message": "Task not found."}), 404
if __name__ == '__main__':
app.run(debug=True, port=5000, use_reloader=False)