-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
560 lines (477 loc) · 19.4 KB
/
main.py
File metadata and controls
560 lines (477 loc) · 19.4 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
import sys
import os
import time
import threading
import queue
import logging
import comtypes
import re
from typing import Optional, List, Sequence, Tuple, Set
import json
import psutil
import pyautogui
import win32gui
import win32process
from colorama import init as colorama_init, Fore, Style
from flask import Flask, request, jsonify
from pycaw.pycaw import AudioUtilities, IAudioMeterInformation, AudioSession
# -----------------------
# Tunables
# -----------------------
PROCESS_NAME = "hackmud_win.exe" # can be overridden via argv[1]
WINDOW_TITLE_REGEX = r".*hackmud.*" # used to find the correct top-level window
PEAK_THRESHOLD = 0.02 # 0..1 activity threshold
CHECK_INTERVAL_SEC = 0.1 # audio polling period
DEBOUNCE_ABOVE = 3 # samples above threshold to switch ACTIVE
DEBOUNCE_BELOW = 8 # samples below threshold to switch IDLE
IDLE_GRACE_SEC = 0.30 # extra idle hold before typing
TYPE_PER_COMMAND_DELAY = 0.05 # small delay between characters
PRESS_ENTER = True # send Enter after each command
SERVER_HOST = "127.0.0.1"
SERVER_PORT = 5005
# Game log file produced by "flush"
GAME_LOG_PATH = r"C:\Users\tsomm\AppData\Roaming\hackmud\shell.txt"
FILE_STABLE_FOR_SEC = 0.35
FILE_POLL_INTERVAL = 0.1
FILE_TIMEOUT_SEC = 15
# -----------------------
# ------------- Logging -------------
colorama_init()
class ColorFormatter(logging.Formatter):
COLORS = {
logging.DEBUG: Fore.BLUE,
logging.INFO: Fore.GREEN,
logging.WARNING: Fore.YELLOW,
logging.ERROR: Fore.RED,
logging.CRITICAL: Fore.MAGENTA + Style.BRIGHT,
}
def format(self, record):
base = super().format(record)
color = self.COLORS.get(record.levelno, "")
return f"{color}{base}{Style.RESET_ALL}"
logger = logging.getLogger("audio-idle")
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(ColorFormatter("[%(asctime)s] %(levelname)s: %(message)s"))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
# -----------------------------------
# ------------- Audio watcher -------------
def find_sessions_for_process(proc_name: str) -> List[Tuple[AudioSession, IAudioMeterInformation]]:
matches = []
for session in AudioUtilities.GetAllSessions():
if session.Process is None:
continue
try:
name = session.Process.name()
except psutil.Error:
continue
if name and name.lower() == proc_name.lower():
try:
meter = session._ctl.QueryInterface(IAudioMeterInformation)
matches.append((session, meter))
except Exception:
continue
return matches
def max_peak(meters: Sequence[Tuple[object, IAudioMeterInformation]]) -> Optional[float]:
if not meters:
return None
peaks = []
for _, m in meters:
try:
peak = m.GetPeakValue()
if isinstance(peak, float):
peaks.append(peak)
except Exception:
continue
return max(peaks) if peaks else None
class AudioIdleWatcher(threading.Thread):
def __init__(self, proc_name: str):
super().__init__(daemon=True)
self.proc_name = proc_name
self.state = "IDLE"
self.above = 0
self.below = 0
self.peak: Optional[float] = None
self.pidset: Set[int] = set()
self._stop = threading.Event()
def run(self):
comtypes.CoInitialize()
logger.info(f"Watching audio for process: {self.proc_name}")
last_pids = set()
while not self._stop.is_set():
sessions = find_sessions_for_process(self.proc_name)
self.pidset = {s.Process.pid for s, _ in sessions if s.Process is not None} if sessions else set()
if self.pidset != last_pids:
if self.pidset:
logger.info(f"Found {len(self.pidset)} audio session(s) for {self.proc_name}: {sorted(self.pidset)}")
else:
logger.warning(f"No audio sessions found for {self.proc_name}. Waiting...")
last_pids = set(self.pidset)
self.peak = max_peak(sessions)
if self.peak is None:
self.above = 0
self.below += 1
else:
if self.peak >= PEAK_THRESHOLD:
self.above += 1
self.below = 0
else:
self.below += 1
self.above = 0
if self.state == "IDLE" and self.above >= DEBOUNCE_ABOVE:
self.state = "ACTIVE"
self.above = 0
logger.info("STATE: ACTIVE (sound detected)")
elif self.state == "ACTIVE" and self.below >= DEBOUNCE_BELOW:
self.state = "IDLE"
self.below = 0
logger.info("STATE: IDLE (no sound)")
time.sleep(CHECK_INTERVAL_SEC)
def stop(self):
self._stop.set()
def is_idle(self) -> bool:
return self.state == "IDLE"
# -----------------------------------------
# ------------- Window control -------------
import win32con
import win32api
import pyautogui
def bring_to_foreground(hwnd: int) -> None:
"""
Robustly bring the target window to the foreground using several strategies:
restore if minimized, SetForegroundWindow, ALT key workaround, bring-to-top,
and a final click in client area to steal focus.
"""
try:
if win32gui.IsIconic(hwnd):
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
time.sleep(0.15)
# Try direct foreground
try:
win32gui.SetForegroundWindow(hwnd)
except Exception:
# ALT key trick to allow foreground switch
win32api.keybd_event(win32con.VK_MENU, 0, 0, 0) # ALT down
win32gui.SetForegroundWindow(hwnd)
win32api.keybd_event(win32con.VK_MENU, 0, win32con.KEYEVENTF_KEYUP, 0) # ALT up
# Bring to top and show
win32gui.BringWindowToTop(hwnd)
win32gui.ShowWindow(hwnd, win32con.SW_SHOW)
time.sleep(0.10)
except Exception as e:
logger.warning(f"Foreground sequence partial failure: {e}")
def click_client_center(hwnd: int) -> None:
"""
Click the center of the window client area to ensure the input control has focus.
"""
try:
rect = win32gui.GetWindowRect(hwnd)
cx = int((rect[0] + rect[2]) / 2)
cy = int((rect[1] + rect[3]) / 2)
pyautogui.click(cx, cy)
time.sleep(0.05)
except Exception as e:
logger.debug(f"click_client_center failed (non-fatal): {e}")
def find_window_by_process(process_name: str, title_contains: str = "") -> Optional[int]:
def callback(hwnd, hwnds):
if win32gui.IsWindowVisible(hwnd):
_, pid = win32process.GetWindowThreadProcessId(hwnd)
try:
proc = psutil.Process(pid)
if proc.name().lower() == process_name.lower():
title = win32gui.GetWindowText(hwnd) or ""
if title_contains is None or title_contains.lower() in title.lower():
hwnds.append(hwnd)
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
return True
hwnds = []
win32gui.EnumWindows(callback, hwnds)
return hwnds[0] if hwnds else None
def focus_and_type(process_name: str, text: str, press_enter: bool = True):
"""
Find and focus the game window, click into it, then type using pyautogui.
"""
hwnd = find_window_by_process(process_name, title_contains="hackmud")
if not hwnd or not win32gui.IsWindow(hwnd):
raise RuntimeError(f"Window not found for process: {process_name}")
bring_to_foreground(hwnd)
click_client_center(hwnd)
logger.debug(f"Typing text: {text!r}")
pyautogui.write(text, interval=TYPE_PER_COMMAND_DELAY)
if press_enter:
time.sleep(0.06)
pyautogui.press('enter')
time.sleep(0.06)
def ensure_cleared_before_command(max_attempts: int = 3) -> None:
"""
Ensure the in-game console is cleared before sending a command:
- send 'clear' and 'flush'
- wait for file quiescence
- truncate the file to zero to guarantee a clean slate for the next flush
Retries the sequence if focus/typing failed.
"""
for attempt in range(1, max_attempts + 1):
try:
logger.info(f"Clearing console (attempt {attempt})")
focus_and_type(PROCESS_NAME, "clear", press_enter=True)
time.sleep(0.10)
focus_and_type(PROCESS_NAME, "flush", press_enter=True)
ok = wait_for_file_quiescence(GAME_LOG_PATH)
if not ok:
logger.warning("Waiting for flush after clear timed out")
continue
# Zero the file so the upcoming command’s flush only contains fresh output
try:
with open(GAME_LOG_PATH, "w", encoding="utf-8", errors="ignore") as f:
f.truncate(0)
except Exception as fe:
logger.debug(f"Truncate failed (non-fatal): {fe}")
logger.info("Console cleared and output file reset")
return
except Exception as e:
logger.warning(f"Clear step failed: {e}")
time.sleep(0.20)
# If we reach here, we tried our best — fail fast so the caller can decide
raise RuntimeError("Failed to clear console reliably after multiple attempts")
# ------------------------------------------
# ------------- File quiescence + output read -------------
def wait_for_file_quiescence(path: str,
stable_for: float = FILE_STABLE_FOR_SEC,
timeout: float = FILE_TIMEOUT_SEC,
poll: float = FILE_POLL_INTERVAL) -> bool:
"""
Wait until file exists and its size/mtime remain unchanged for 'stable_for' seconds.
Returns True if stable, False on timeout.
"""
start = time.time()
# Wait until file appears
while not os.path.exists(path):
if time.time() - start > timeout:
return False
time.sleep(poll)
last_size = -1
last_mtime = -1.0
stable_start = None
while True:
try:
stat = os.stat(path)
size = stat.st_size
mtime = stat.st_mtime
except FileNotFoundError:
if time.time() - start > timeout:
return False
time.sleep(poll)
continue
if size == last_size and mtime == last_mtime:
if stable_start is None:
stable_start = time.time()
if time.time() - stable_start >= stable_for:
return True
else:
stable_start = None
last_size = size
last_mtime = mtime
if time.time() - start > timeout:
return False
time.sleep(poll)
def strip_color_tags(text: str) -> str:
"""
Remove color tags like <color=#FFFFFFFF> and </color> from the text.
"""
# Remove opening color tags: <color=#FFFFFFFF>
text = re.sub(r'<color=#[0-9A-Fa-f]{8}>', '', text)
# Remove closing color tags: </color>
text = re.sub(r'</color>', '', text)
return text
def read_game_json(path: str) -> Optional[dict]:
"""
Reads the file and attempts to parse JSON.
Looks for JSON wrapped in {{json_block}} tags or standalone JSON.
Strips color tags from game output before parsing.
Returns dict with 'data' and 'ok' keys, or None if parse fails.
"""
try:
with open(path, "r", encoding="utf-8", errors="replace") as f:
data = f.read().strip()
logger.debug(f"Raw file content:\n{data}\n--- End of file content ---")
if not data:
return None
# Strip color tags from the entire content
data = strip_color_tags(data)
logger.debug(f"After stripping color tags:\n{data}\n--- End of stripped content ---")
# Look for JSON wrapped in {{json_block}} tags (changed from <json_block>)
json_block_pattern = r'\{\{json_block([^}]*)\}\}\s*(.*?)\s*\{\{/json_block\}\}'
match = re.search(json_block_pattern, data, re.DOTALL)
if match:
attributes = match.group(1)
json_str = match.group(2).strip()
# Extract 'ok' attribute value
ok_match = re.search(r'ok\s*=\s*["\']?(true|false)["\']?', attributes, re.IGNORECASE)
ok_value = ok_match.group(1).lower() == 'true' if ok_match else None
logger.info(f"Found {{{{json_block}}}} wrapper with ok={ok_value}, extracting JSON content")
logger.debug(f"JSON string to parse:\n{json_str}")
try:
parsed_json = json.loads(json_str)
return {
'data': parsed_json,
'ok': ok_value
}
except json.JSONDecodeError as e:
logger.error(f"Failed to parse JSON from {{{{json_block}}}}: {e}")
logger.error(f"Problematic JSON string:\n{json_str}")
return None
# Fallback: try to parse the entire content as JSON (no 'ok' status)
try:
parsed_json = json.loads(data)
return {
'data': parsed_json,
'ok': None
}
except json.JSONDecodeError:
# fallback: try last non-empty line
lines = [ln for ln in data.splitlines() if ln.strip()]
if not lines:
return None
parsed_json = json.loads(lines[-1])
return {
'data': parsed_json,
'ok': None
}
except Exception as e:
logger.error(f"Failed to read/parse game output: {e}")
return None
# ----------------------------------------------------------
# ------------- Command server and worker -------------
app = Flask(__name__)
command_queue: "queue.Queue[CommandItem]" = queue.Queue()
watcher: Optional[AudioIdleWatcher] = None
# Make Flask use our logger
flask_logger = logging.getLogger("werkzeug")
flask_logger.handlers = logger.handlers
flask_logger.setLevel(logger.level)
app.logger.handlers = logger.handlers
app.logger.setLevel(logger.level)
class CommandItem:
def __init__(self, text: str):
self.text = text
self.event = threading.Event()
self.result: Optional[object] = None
self.error: Optional[str] = None
@app.route("/status", methods=["GET"])
def status():
data = {
"process": PROCESS_NAME,
"state": watcher.state if watcher else "UNKNOWN",
"peak": watcher.peak if watcher else None,
"sessions": sorted(list(watcher.pidset)) if watcher else [],
"queued": command_queue.qsize(),
"threshold": PEAK_THRESHOLD,
"debounce": {"above": DEBOUNCE_ABOVE, "below": DEBOUNCE_BELOW},
}
return jsonify(data)
@app.route("/command", methods=["POST"])
def command():
try:
payload = request.get_json(force=True, silent=False)
except Exception:
return jsonify({"ok": False, "error": "Invalid JSON"}), 400
if not payload or "text" not in payload:
return jsonify({"ok": False, "error": "Provide JSON with 'text'"}), 400
text = str(payload["text"]).strip("\r\n")
if not text:
return jsonify({"ok": False, "error": "Empty text"}), 400
item = CommandItem(text)
command_queue.put(item)
logger.info(f"Queued command: {text!r} (queue size {command_queue.qsize()})")
# Block until processed so we can return the game result
item.event.wait(FILE_TIMEOUT_SEC + 10)
resp = {
"result": item.result if item.error is None else None,
"error": item.error,
}
return jsonify(resp), (200 if item.error is None else 500)
def command_worker():
logger.info("Command worker started")
while True:
item: CommandItem = command_queue.get()
if not item or not item.text:
command_queue.task_done()
continue
try:
logger.info(f"Processing command: {item.text!r}")
# Wait until idle
while not (watcher and watcher.is_idle()):
logger.info("Waiting for idle state...")
time.sleep(0.05)
time.sleep(IDLE_GRACE_SEC)
if not watcher.is_idle():
# requeue if it flipped active
logger.info("Became active again, re-queuing command")
command_queue.put(item)
time.sleep(0.2)
continue
logger.info(f"Sending command: {item.text!r}")
# Step 1: clear
try:
logger.info(f"Clearing console for command: {item.text!r}")
focus_and_type(PROCESS_NAME, "clear", press_enter=PRESS_ENTER)
except Exception as e:
logger.error(f"Failed to send 'clear': {e}")
item.error = f"Failed to send 'clear': {e}"
continue
# Small settle so the console actually clears
time.sleep(0.1)
# Step 2: command
try:
logger.info(f"Sending command: {item.text!r}")
focus_and_type(PROCESS_NAME, item.text, press_enter=PRESS_ENTER)
except Exception as e:
logger.error(f"Failed to send command {item.text!r}: {e}")
item.error = f"Failed to send command: {e}"
continue
# wait for game to become idle again
while not (watcher and watcher.is_idle()):
logger.info("Waiting for idle state...")
time.sleep(0.05)
# Step 3: flush
try:
logger.info(f"Sending 'flush' for command: {item.text!r}")
focus_and_type(PROCESS_NAME, "flush", press_enter=PRESS_ENTER)
except Exception as e:
logger.error(f"Failed to send 'flush': {e}")
item.error = f"Failed to send 'flush': {e}"
continue
# Step 4: wait for file quiescence and read JSON
if not wait_for_file_quiescence(GAME_LOG_PATH):
item.error = f"Timed out waiting for output file to stabilize: {GAME_LOG_PATH}"
logger.error(item.error)
else:
result = read_game_json(GAME_LOG_PATH)
if result is None:
item.error = "No valid JSON found in game output"
logger.error(item.error)
else:
item.result = result # Now contains {'data': ..., 'ok': ...}
logger.info(f"Captured game output JSON (ok={result.get('ok')})")
except Exception as e:
item.error = f"Unhandled error: {e}"
logger.error(item.error)
finally:
item.event.set()
command_queue.task_done()
# -----------------------------------------------------
def main():
global PROCESS_NAME, watcher
if len(sys.argv) > 1:
PROCESS_NAME = sys.argv[1]
# Start audio watcher
watcher = AudioIdleWatcher(PROCESS_NAME)
watcher.start()
# Start command worker
t = threading.Thread(target=command_worker, daemon=True, name="command-worker")
t.start()
logger.info(f"HTTP server on http://{SERVER_HOST}:{SERVER_PORT}")
app.run(host=SERVER_HOST, port=SERVER_PORT, threaded=True)
if __name__ == "__main__":
main()