Files
pokerfreak-shell/werkzeuge/hover.py
T

173 lines
5.1 KiB
Python

#!/usr/bin/env python3
"""Lernt die Aktionsknöpfe, indem es mit der Maus darüber fährt.
Der Client meldet beim Überfahren selbst, was unter dem Zeiger liegt
(TABLE_PLAYER_ACTION_SHOW). Wir klicken dabei nichts - reines Überfahren.
python3 hover.py [--minutes 30]
"""
import os as _os, sys as _sys
_w = _os.path.dirname(_os.path.abspath(__file__))
while _w != "/" and not _os.path.isdir(_os.path.join(_w, "hand")):
_w = _os.path.dirname(_w)
WURZEL = _w
for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb", "mock"):
_q = _os.path.join(_w, _u)
if _os.path.isdir(_q) and _q not in _sys.path:
_sys.path.insert(0, _q)
import ctypes
import json
import os
import re
import subprocess
import sys
import time
BASE = os.path.dirname(os.path.abspath(__file__))
LOG = os.path.expanduser("~/Library/Logs/CoinPoker/main.log")
OUT = os.path.join(BASE, "scratch", "hover-log.txt")
FW = "/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices"
AS = ctypes.cdll.LoadLibrary(FW)
class CGPoint(ctypes.Structure):
_fields_ = [("x", ctypes.c_double), ("y", ctypes.c_double)]
AS.CGEventCreateMouseEvent.restype = ctypes.c_void_p
AS.CGEventCreateMouseEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint32, CGPoint,
ctypes.c_uint32]
AS.CGEventPost.argtypes = [ctypes.c_uint32, ctypes.c_void_p]
MOUSE_MOVED = 5
EVENT = re.compile(
r'"BeanData":"((?:[^"\\]|\\.)*)","Cmd":"([a-zA-Z_.]+)","RoomName":"((?:[^"\\]|\\.)*)"'
)
USER = re.compile(r"username=([A-Za-z0-9_]+)")
SHOW = "TABLE_PLAYER_ACTION"
class LogTail:
def __init__(self, path):
self.path, self.handle, self.inode = path, None, None
self._open(True)
def _open(self, from_end):
if self.handle:
self.handle.close()
self.handle = open(self.path, errors="replace")
if from_end:
self.handle.seek(0, 2)
self.inode = os.fstat(self.handle.fileno()).st_ino
def line(self):
found = self.handle.readline()
if found:
return found
try:
if os.stat(self.path).st_ino != self.inode:
self._open(False)
except FileNotFoundError:
pass
return ""
def osa(script):
r = subprocess.run(["osascript", "-e", script], capture_output=True, text=True)
return (r.stdout or r.stderr).strip()
def window_rect():
pid = subprocess.run(["pgrep", "-f", "CoinPoker Game"], capture_output=True,
text=True).stdout.split()
if not pid:
return None
proc = f'(first process whose unix id is {pid[0]})'
pos = osa(f'tell application "System Events" to tell {proc} to get position of window 1')
size = osa(f'tell application "System Events" to tell {proc} to get size of window 1')
try:
x, y = [float(v) for v in pos.replace(" ", "").split(",")[:2]]
w, h = [float(v) for v in size.replace(" ", "").split(",")[:2]]
except Exception:
return None
return x, y, w, h
def move_to(x, y):
ev = AS.CGEventCreateMouseEvent(None, MOUSE_MOVED, CGPoint(x, y), 0)
AS.CGEventPost(0, ev)
def sweep(tail):
rect = window_rect()
if not rect:
return []
x, y, w, h = rect
hits = []
lane = y + h - 45
step = 14
for px in range(int(x) + 30, int(x + w) - 20, step):
move_to(px, lane)
time.sleep(0.10)
while True:
line = tail.line()
if not line:
break
if SHOW in line:
hits.append((px, line.strip()[:170]))
return hits
def main():
minutes = 30.0
if "--minutes" in sys.argv:
minutes = float(sys.argv[sys.argv.index("--minutes") + 1])
out = open(OUT, "w")
def note(t):
out.write(t + "\n")
out.flush()
tail = LogTail(LOG)
note(f"# Überfahren gestartet {time.strftime('%H:%M:%S')} | "
f"Fenster {window_rect()}")
me, armed, end = None, True, time.time() + minutes * 60
while time.time() < end:
line = tail.line()
if not line:
time.sleep(0.1)
continue
who = USER.search(line)
if who:
me = who.group(1)
if "advance_player_action" in line:
armed = True
hit = EVENT.search(line)
if not hit or hit.group(2) != "game.user_turn":
continue
try:
data = json.loads(json.loads('"' + hit.group(1) + '"'))
except Exception:
continue
opts = {s: v for s, v in (data.get("userTurnOptions") or {}).items() if v}
if opts:
me = data.get("whoseTurn") or me
elif me is None or data.get("whoseTurn") != me:
continue
if not armed:
continue
armed = False
note(f"\n=== Zug {time.strftime('%H:%M:%S')} Hand {data.get('gameHandId')} "
f"Call {data.get('callAmount')} - fahre über die Knopfleiste")
hits = sweep(tail)
note(f" Meldungen des Clients: {len(hits)}")
for px, text in hits:
note(f" bei x={px}: {text}")
note("\n# Ende")
out.close()
if __name__ == "__main__":
main()