#!/usr/bin/env python3 """Raids Timer Linux Auto Farm helper. Same local API as the Windows PC helper (127.0.0.1:18765). BlueStacks has no official Linux build (Windows/Mac only). This helper drives Waydroid (waydroid show-full-ui), the closest native Android runtime, plus other X11 Android windows (Android Emulator / Genymotion) if they are already open. """ from __future__ import annotations import json import os import re import shutil import subprocess import threading import time import tkinter as tk from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from urllib.error import URLError from urllib.parse import quote, urlparse from urllib.request import Request, urlopen HELPER_VERSION = "1.0.2" LISTEN = ("127.0.0.1", 18765) HOME = Path(os.environ.get("XDG_DATA_HOME") or (Path.home() / ".local" / "share")) / "raidstimer" FARM_FILE = HOME / "linux-farm.json" ORDER_SERVER = "https://savemypet-backend.onrender.com" WAYDROID_DOCS = "https://docs.waydro.id/usage/install-on-desktops" SPLIT_MAX = 4 EMU_NAME_RE = re.compile( r"waydroid|android emulator|emulator - |genymotion|qemu|weston|cage|lineage", re.I, ) HELPER_NAME_RE = re.compile(r"raids timer linux", re.I) state = { "ok": True, "recording": False, "playing": False, "stop_play": False, "chatPaid": False, "farmGame": "kingshot", "uiLang": "en", "playLoop": False, "playDelay": 400, "events": [], "screens": [], "activeWid": "", "displayName": "", "allianceName": "", "serverNumber": "", "playerId": "", "marchSec": 0, "orderFireAt": 0, "orderKind": "land", "orderBody": "", "log": "Linux Auto Farm helper. Chat plan unlocks Record / Play, same as Windows.", } lock = threading.RLock() ui = {"root": None, "log": None, "paid": None, "how": None, "wins": None, "emu": None} def log(msg: str) -> None: line = str(msg or "").strip() with lock: state["log"] = line root = ui.get("root") box = ui.get("log") if root and box: try: root.after(0, lambda: _set_log(box, line)) except Exception: pass def _set_log(box, line: str) -> None: box.delete("1.0", "end") box.insert("end", line) def which(name: str) -> str: return shutil.which(name) or "" def have_xdotool() -> bool: return bool(which("xdotool")) def have_waydroid() -> bool: return bool(which("waydroid")) def run_xd(args: list[str], timeout: float = 6.0) -> str: if not have_xdotool(): raise RuntimeError("xdotool is missing") p = subprocess.run(["xdotool", *args], capture_output=True, text=True, timeout=timeout) if p.returncode != 0: err = (p.stderr or p.stdout or "xdotool failed").strip() raise RuntimeError(err) return (p.stdout or "").strip() def run_xd_ok(args: list[str], timeout: float = 6.0) -> str: try: return run_xd(args, timeout=timeout) except Exception: return "" def mouse_xy() -> tuple[int, int]: out = run_xd(["getmouselocation", "--shell"]) x = y = 0 for row in out.splitlines(): if row.startswith("X="): x = int(row.split("=", 1)[1]) elif row.startswith("Y="): y = int(row.split("=", 1)[1]) return x, y def window_title(wid: str) -> str: return run_xd_ok(["getwindowname", str(wid)]) or ("window " + str(wid)) def window_geo(wid: str) -> dict: out = run_xd_ok(["getwindowgeometry", "--shell", str(wid)]) geo = {"id": str(wid), "x": 0, "y": 0, "w": 0, "h": 0, "title": window_title(wid)} for row in out.splitlines(): if row.startswith("X="): geo["x"] = int(row.split("=", 1)[1] or 0) elif row.startswith("Y="): geo["y"] = int(row.split("=", 1)[1] or 0) elif row.startswith("WIDTH="): geo["w"] = int(row.split("=", 1)[1] or 0) elif row.startswith("HEIGHT="): geo["h"] = int(row.split("=", 1)[1] or 0) return geo def display_size() -> tuple[int, int]: out = run_xd_ok(["getdisplaygeometry"]) or "1920 1080" parts = re.split(r"[xX\s]+", out.strip()) try: return max(640, int(parts[0])), max(480, int(parts[1])) except Exception: return 1920, 1080 def search_wids(*extra: str) -> list[str]: seen = [] args_sets = [ ["search", "--onlyvisible", "--name", "Waydroid"], ["search", "--onlyvisible", "--name", "waydroid"], ["search", "--onlyvisible", "--class", "waydroid"], ["search", "--onlyvisible", "--class", "Waydroid"], ["search", "--onlyvisible", "--name", "Android Emulator"], ["search", "--onlyvisible", "--name", "Genymotion"], ["search", "--onlyvisible", "--class", "qemu-system"], ["search", "--onlyvisible", "--class", "Weston"], ] if extra: args_sets.append(["search", "--onlyvisible", "--name", extra[0]]) for args in args_sets: raw = run_xd_ok(args, timeout=1.8) for tok in raw.split(): if tok.isdigit() and tok not in seen: seen.append(tok) return seen def list_emu_windows() -> list[dict]: rows = [] helper_wid = "" try: helper_wid = str(ui.get("root").winfo_id()) if ui.get("root") else "" except Exception: helper_wid = "" for wid in search_wids(): if helper_wid and str(wid) == helper_wid: continue title = window_title(wid) if HELPER_NAME_RE.search(title): continue if not EMU_NAME_RE.search(title) and "waydroid" not in title.lower(): # Keep unnamed Waydroid / weston matches from class search. geo_try = window_geo(wid) if geo_try["w"] < 200 or geo_try["h"] < 200: continue geo = window_geo(wid) if geo["w"] < 120 or geo["h"] < 120: continue rows.append(geo) return rows def activate_window(wid: str) -> None: run_xd(["windowactivate", "--sync", str(wid)]) run_xd_ok(["windowfocus", "--sync", str(wid)]) run_xd_ok(["windowraise", str(wid)]) time.sleep(0.08) def click_xy(x: int, y: int) -> None: run_xd(["mousemove", "--sync", str(int(x)), str(int(y))]) time.sleep(0.02) run_xd(["click", "1"]) def click_in_window(wid: str, rx: int, ry: int) -> None: activate_window(wid) try: run_xd(["mousemove", "--window", str(wid), "--sync", str(int(rx)), str(int(ry))]) time.sleep(0.02) run_xd(["click", "--window", str(wid), "1"]) return except Exception: pass geo = window_geo(wid) click_xy(int(geo["x"]) + int(rx), int(geo["y"]) + int(ry)) def type_key(key: str) -> None: k = str(key or "").strip() if not k: return run_xd(["key", k]) def persist() -> dict: with lock: return { "events": list(state["events"]), "screens": list(state["screens"]), "activeWid": str(state["activeWid"] or ""), "displayName": str(state.get("displayName") or ""), "allianceName": str(state.get("allianceName") or ""), "serverNumber": str(state.get("serverNumber") or ""), "playerId": str(state.get("playerId") or ""), "marchSec": int(state.get("marchSec") or 0), } def load_farm() -> None: HOME.mkdir(parents=True, exist_ok=True) if not FARM_FILE.is_file(): return try: data = json.loads(FARM_FILE.read_text(encoding="utf-8")) if not isinstance(data, dict): return ev = data.get("events") screens = data.get("screens") with lock: if isinstance(ev, list): state["events"] = ev if isinstance(screens, list): state["screens"] = screens state["activeWid"] = str(data.get("activeWid") or "") for k in ("displayName", "allianceName", "serverNumber", "playerId"): if data.get(k): state[k] = str(data.get(k) or "") try: state["marchSec"] = max(0, int(data.get("marchSec") or 0)) except Exception: state["marchSec"] = 0 except Exception: pass def save_farm() -> None: HOME.mkdir(parents=True, exist_ok=True) FARM_FILE.write_text(json.dumps(persist(), indent=2), encoding="utf-8") def _slug(raw: str) -> str: s = re.sub(r"[^a-z0-9]+", "_", str(raw or "").strip().lower()).strip("_") return s[:48] def player_key() -> str: with lock: p = str(state.get("playerId") or "").strip() if not p: p = str(state.get("displayName") or "").strip() return p def helper_user_id() -> str: srv = _slug(state.get("serverNumber") or "") ply = _slug(player_key()) if not srv or not ply: return "" return "ks_s%s_p%s" % (srv, ply) def order_profile_ok() -> bool: with lock: return bool( str(state.get("displayName") or "").strip() and str(state.get("allianceName") or "").strip() and str(state.get("serverNumber") or "").strip() ) def parse_march_sec(raw: str) -> int: s = str(raw or "").strip() m = re.match(r"^(\d+)\s*:\s*(\d+)\s*:\s*(\d+)$", s) if m: return int(m.group(1)) * 3600 + int(m.group(2)) * 60 + int(m.group(3)) m = re.match(r"^(\d+)\s*:\s*(\d+)$", s) if m: return int(m.group(1)) * 60 + int(m.group(2)) try: return max(0, int(s)) except Exception: return 0 def _trpc_unwrap(obj): if not isinstance(obj, dict): return {} r = obj.get("result") or {} d = r.get("data") if isinstance(d, dict) and "json" in d: return d.get("json") or {} if isinstance(d, dict): return d return obj def trpc_query(path: str, payload: dict) -> dict: q = quote(json.dumps({"json": payload})) url = "%s/api/trpc/%s?input=%s" % (ORDER_SERVER, path, q) req = Request(url, headers={"Accept": "application/json"}) with urlopen(req, timeout=12) as r: return _trpc_unwrap(json.loads(r.read().decode("utf-8") or "{}")) def trpc_mutate(path: str, payload: dict) -> dict: body = json.dumps({"json": payload}).encode("utf-8") req = Request( "%s/api/trpc/%s" % (ORDER_SERVER, path), data=body, headers={"Content-Type": "application/json; charset=utf-8", "Accept": "application/json"}, ) with urlopen(req, timeout=16) as r: return _trpc_unwrap(json.loads(r.read().decode("utf-8") or "{}")) def next_order_fire(schedules: list, my_id: str, march_sec: int) -> dict: now = int(time.time() * 1000) best = 0 kind = "land" title = "" who = "" for s in schedules or []: if not isinstance(s, dict): continue st = str(s.get("status") or "") if re.search(r"cancel|complete", st, re.I): continue land = int(s.get("landAtUtcMs") or 0) send = int(s.get("sendAtUtcMs") or 0) if land <= 0: land = send my_m = int(march_sec or 0) for t in s.get("teams") or []: rows = list(t.get("picks") or []) + list(t.get("assignments") or []) for row in rows: if not isinstance(row, dict): continue uid = str(row.get("userId") or "") if my_id and uid and uid.lower() == my_id.lower(): try: m = int(row.get("marchDurationSec") or 0) if m > 0: my_m = m except Exception: pass fire = land k = "land" if my_m > 0 and land > 0: fire = land - my_m * 1000 k = "send" elif send > 0 and land > 0 and send < land: fire = send k = "send" if fire <= 0: continue if now - fire > 20000: continue if best == 0 or fire < best: best = fire kind = k title = str(s.get("title") or "") who = str(s.get("publishedByName") or s.get("senderName") or "") return {"fireAt": best, "kind": kind, "title": title, "who": who} def refresh_alliance_clock() -> None: if not order_profile_ok(): with lock: state["orderFireAt"] = 0 state["orderBody"] = "" return with lock: player = player_key() payload = { "playerId": player, "serverNumber": str(state.get("serverNumber") or ""), "allianceName": str(state.get("allianceName") or ""), } name = str(state.get("displayName") or "Commander") my_id = helper_user_id() march = int(state.get("marchSec") or 0) data = {} try: data = trpc_query("raids.listAllianceSends", payload) or {} except Exception: data = {} if not data.get("success"): try: sync = dict(payload) sync["displayName"] = name data = trpc_mutate("raids.syncAllianceSpace", sync) or {} except Exception: data = {} schedules = list(data.get("schedules") or []) try: recv_in = dict(payload) recv_in["displayName"] = name recv = trpc_query("raids.listReceivedOrders", recv_in) or {} for o in recv.get("orders") or []: if isinstance(o, dict): schedules.append(o) except Exception: pass hit = next_order_fire(schedules, my_id, march) who = str(hit.get("who") or "") ttl = str(hit.get("title") or "Rally") body = ("%s · %s" % (who, ttl)).strip(" ·") if who else ttl with lock: state["orderFireAt"] = int(hit.get("fireAt") or 0) state["orderKind"] = str(hit.get("kind") or "land") state["orderBody"] = body def publish_alliance_order(title: str, land_min: int, march_sec: int) -> None: if not order_profile_ok(): raise RuntimeError("Set in-game name, alliance, and server first (same as the website).") land_min = max(1, min(180, int(land_min or 5))) march_sec = max(0, int(march_sec or 0)) now = int(time.time() * 1000) land_ms = now + land_min * 60000 send_ms = land_ms - march_sec * 1000 if march_sec > 0 else land_ms ttl = (title or "Rally").strip()[:120] or "Rally" with lock: player = player_key() uid = helper_user_id() name = str(state.get("displayName") or "Commander") payload = { "playerId": player, "serverNumber": str(state.get("serverNumber") or ""), "allianceName": str(state.get("allianceName") or ""), "displayName": name, "title": ttl, "notes": "From Linux helper banner", "sendAtUtcMs": send_ms, "landAtUtcMs": land_ms, "teams": [], "inviteUserIds": [], "confirmSender": True, } if march_sec > 0 and uid: payload["teams"] = [ { "teamName": "Team 1", "sendAtUtcMs": send_ms, "kind": "rally", "landAtUtcMs": land_ms, "assignments": [ { "userId": uid, "displayName": name, "playerId": player, "marchDurationSec": march_sec, } ], } ] state["marchSec"] = march_sec res = trpc_mutate("raids.publishAllianceSend", payload) or {} if not res.get("success"): raise RuntimeError(str(res.get("error") or "Could not share the order.")) save_farm() with lock: state["orderFireAt"] = send_ms state["orderKind"] = "send" if march_sec > 0 else "land" state["orderBody"] = name + " · " + ttl def paint_order_banner() -> None: clock = ui.get("clock") if not clock: return with lock: fire = int(state.get("orderFireAt") or 0) kind = str(state.get("orderKind") or "land") body = str(state.get("orderBody") or "") if fire <= 0: clock.config(text="Orders: none yet. Send order uses the same alliance board as the website.") return now = int(time.time() * 1000) left = int(round((fire - now) / 1000.0)) if left < -8: clock.config(text="Orders: wave ended.") return mm = max(0, left) // 60 ss = max(0, left) % 60 clocktxt = "%02d:%02d" % (mm, ss) if left <= 0: clock.config(text=("SEND NOW " if kind == "send" else "LAND NOW ") + body) elif left <= 60: clock.config(text="GET READY %s %s" % (clocktxt, body)) else: head = "SEND" if kind == "send" else "LAND" clock.config(text="%s %s %s" % (head, clocktxt, body)) def order_poll_loop() -> None: while True: try: refresh_alliance_clock() except (URLError, TimeoutError, OSError): pass except Exception: pass root = ui.get("root") if root: try: root.after(0, paint_order_banner) except Exception: pass time.sleep(5) def show_send_order() -> None: dlg = tk.Toplevel(ui.get("root")) dlg.title("Send order") dlg.geometry("420x340") tk.Label(dlg, text="Same alliance board as the website. Chat plan not required.").pack(anchor="w", padx=10, pady=(8, 4)) fields = {} for key, label in ( ("displayName", "In-game name"), ("allianceName", "Alliance"), ("serverNumber", "Server number"), ("title", "Title"), ("landMin", "Land in minutes"), ("march", "March (sec or m:ss, optional)"), ): tk.Label(dlg, text=label).pack(anchor="w", padx=10) e = tk.Entry(dlg) e.pack(fill="x", padx=10, pady=(0, 4)) with lock: if key == "title": e.insert(0, "Rally") elif key == "landMin": e.insert(0, "5") elif key == "march": m = int(state.get("marchSec") or 0) if m: e.insert(0, str(m)) else: e.insert(0, str(state.get(key) or "")) fields[key] = e def go() -> None: with lock: state["displayName"] = fields["displayName"].get().strip() state["allianceName"] = fields["allianceName"].get().strip() state["serverNumber"] = fields["serverNumber"].get().strip() try: mins = int(fields["landMin"].get().strip() or "5") except Exception: mins = 5 try: publish_alliance_order(fields["title"].get(), mins, parse_march_sec(fields["march"].get())) paint_order_banner() dlg.destroy() log("Order shared. Alliance can see this land time.") except Exception as e: log("Send order failed: %s" % e) tk.Button(dlg, text="Lock and share", command=go).pack(pady=8) def selected_wid() -> str: box = ui.get("wins") if box: try: sel = box.curselection() if sel: line = box.get(sel[0]) m = re.match(r"^(\d+)", str(line)) if m: return m.group(1) except Exception: pass with lock: return str(state["activeWid"] or "") def refresh_window_list() -> list[dict]: rows = list_emu_windows() box = ui.get("wins") emu = ui.get("emu") if box: try: box.delete(0, "end") for r in rows: box.insert("end", "%s %sx%s %s" % (r["id"], r["w"], r["h"], r["title"][:48])) if rows: box.selection_set(0) except Exception: pass kind = "Waydroid" if have_waydroid() else "not installed" n = len(rows) if emu: try: emu.config( text="Android: %s · %s window(s). BlueStacks is Windows/Mac only." % (kind, n) ) except Exception: pass return rows def launch_waydroid() -> None: if not have_waydroid(): log("Waydroid is not installed. Install from %s then click Launch Waydroid." % WAYDROID_DOCS) return try: subprocess.Popen( ["waydroid", "show-full-ui"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True, ) except Exception as e: log("Could not start Waydroid: %s" % e) return log("Starting Waydroid full UI. After the Android window opens, Find windows then Use window.") root = ui.get("root") if root: root.after(2500, lambda: (refresh_window_list(), log("Find windows: pick the Waydroid window, then Use window."))) def use_window() -> None: wid = selected_wid() if not wid: rows = refresh_window_list() if rows: wid = str(rows[0]["id"]) else: try: wid = run_xd(["getactivewindow"]) except Exception: wid = "" if not wid: log("No Android window. Launch Waydroid, or open Android Emulator, then Find windows.") return geo = window_geo(wid) with lock: state["activeWid"] = str(wid) found = False for s in state["screens"]: if str(s.get("id")) == str(wid): s.update(geo) found = True break if not found: state["screens"].append({**geo, "events": []}) save_farm() try: activate_window(wid) except Exception as e: log("Use window failed: %s" % e) return log("Using %s (%sx%s). Record clicks on that Android window." % (geo["title"][:40], geo["w"], geo["h"])) refresh_window_list() def save_sizes() -> None: rows = refresh_window_list() if not rows: log("No Android windows to save. Launch Waydroid first.") return with lock: by_id = {str(s.get("id")): s for s in state["screens"]} screens = [] for r in rows: old = by_id.get(str(r["id"])) or {} screens.append({**old, **r, "events": list(old.get("events") or [])}) state["screens"] = screens if not state["activeWid"] and screens: state["activeWid"] = str(screens[0]["id"]) save_farm() log("Saved size + location for %s Android window(s)." % len(rows)) def restore_sizes() -> None: with lock: screens = list(state["screens"]) if not screens: log("Nothing saved. Place Waydroid, then Save size + location.") return n = 0 for s in screens: wid = str(s.get("id") or "") if not wid: continue try: activate_window(wid) run_xd(["windowmove", wid, str(int(s.get("x") or 0)), str(int(s.get("y") or 0))]) w, h = int(s.get("w") or 0), int(s.get("h") or 0) if w > 80 and h > 80: run_xd(["windowsize", wid, str(w), str(h)]) n += 1 except Exception: continue log("Restored size + location for %s window(s)." % n) refresh_window_list() def split_view() -> None: rows = refresh_window_list() if len(rows) < 2: log("Need 2 or more Android windows for split view. Open more Waydroid / emulator windows, then Find windows.") return n = min(SPLIT_MAX, len(rows)) if len(rows) > SPLIT_MAX: log("Tiling first %s windows. Extra screens farm one at a time on Play all." % SPLIT_MAX) sw, sh = display_size() gap = 6 targets = rows[:n] if n == 2: w = (sw - gap) // 2 layout = [(0, 0, w, sh), (w + gap, 0, w, sh)] elif n == 3: w = (sw - 2 * gap) // 3 layout = [(i * (w + gap), 0, w, sh) for i in range(3)] else: w = (sw - gap) // 2 h = (sh - gap) // 2 layout = [ (0, 0, w, h), (w + gap, 0, w, h), (0, h + gap, w, h), (w + gap, h + gap, w, h), ] saved = [] for i, r in enumerate(targets): x, y, ww, hh = layout[i] wid = str(r["id"]) try: activate_window(wid) run_xd(["windowmove", wid, str(x), str(y)]) run_xd(["windowsize", wid, str(ww), str(hh)]) geo = window_geo(wid) saved.append(geo) except Exception as e: log("Split failed on %s: %s" % (r.get("title") or wid, e)) with lock: by_id = {str(s.get("id")): s for s in state["screens"]} for geo in saved: old = by_id.get(str(geo["id"])) or {} by_id[str(geo["id"])] = {**old, **geo, "events": list(old.get("events") or [])} state["screens"] = list(by_id.values()) save_farm() log("Split view: tiled %s Android window(s)." % len(saved)) refresh_window_list() def relative_click_event() -> dict: x, y = mouse_xy() wid = selected_wid() ev = {"type": "click", "x": x, "y": y, "t": int(time.time() * 1000)} if wid: try: geo = window_geo(wid) ev["wid"] = str(wid) ev["rx"] = x - int(geo["x"]) ev["ry"] = y - int(geo["y"]) except Exception: pass return ev def mark_click() -> None: with lock: if not state["recording"]: log("Press Record first, then Mark click (or F8).") return if not state["chatPaid"]: log("Auto Farm needs a Chat plan (PayPal or Apple), same as Windows.") return try: ev = relative_click_event() except Exception as e: log("Could not read mouse: %s" % e) return with lock: state["events"].append(ev) n = len(state["events"]) wid = str(ev.get("wid") or state["activeWid"] or "") if wid: for s in state["screens"]: if str(s.get("id")) == wid: s.setdefault("events", []).append(ev) break save_farm() log("Saved click #%s at %s,%s" % (n, ev.get("x"), ev.get("y"))) def start_record() -> None: with lock: if not state["chatPaid"]: log("Auto Farm needs a Chat plan (PayPal or Apple), same as Windows.") return state["recording"] = True state["events"] = [] save_farm() log("Recording. Click the Waydroid / Android window, then Mark click or F8 for each step.") def stop_record() -> None: with lock: state["recording"] = False n = len(state["events"]) save_farm() log("Stopped record. %s step(s) saved." % n) def stop_play() -> None: with lock: state["stop_play"] = True state["playing"] = False state["recording"] = False log("Stopped.") def play_events_on(events: list, wid: str) -> bool: delay = max(80, int(state.get("playDelay") or 400)) for i, ev in enumerate(events, 1): with lock: if state["stop_play"]: log("Play stopped.") return False kind = str(ev.get("type") or "click") try: if kind == "key": if wid: activate_window(wid) type_key(str(ev.get("key") or "")) elif wid and ev.get("rx") is not None and ev.get("ry") is not None: click_in_window(wid, int(ev.get("rx") or 0), int(ev.get("ry") or 0)) elif wid: geo = window_geo(wid) rx = int(ev.get("x") or 0) - int(geo["x"]) ry = int(ev.get("y") or 0) - int(geo["y"]) click_in_window(wid, rx, ry) else: click_xy(int(ev.get("x") or 0), int(ev.get("y") or 0)) except Exception as e: log("Play step %s failed: %s" % (i, e)) return False time.sleep(delay / 1000.0) return True def play_targets() -> list[dict]: live = list_emu_windows() with lock: saved = list(state["screens"]) shared = list(state["events"]) active = str(state["activeWid"] or "") if live: out = [] for r in live: match = next((s for s in saved if str(s.get("id")) == str(r["id"])), None) ev = list((match or {}).get("events") or []) or shared out.append({**r, "events": ev}) return out if saved: return [{**s, "events": list(s.get("events") or []) or shared} for s in saved] if shared: return [{"id": active, "title": "screen", "events": shared}] return [] def play_loop() -> None: with lock: loop = bool(state["playLoop"]) state["playing"] = True state["stop_play"] = False targets = play_targets() if not targets or not any(t.get("events") for t in targets): log("Nothing to play. Record clicks on Waydroid first.") with lock: state["playing"] = False return sequential = len(targets) > SPLIT_MAX log( "Playing %s Android window(s)%s. Stop play to cancel." % (len(targets), " one at a time" if sequential else "") ) try: while True: for i, t in enumerate(targets, 1): with lock: if state["stop_play"]: log("Play stopped.") return wid = str(t.get("id") or "") events = list(t.get("events") or []) if not events: continue if sequential: for other in targets: oid = str(other.get("id") or "") if oid and oid != wid: run_xd_ok(["windowminimize", oid]) time.sleep(0.15) log("Farming screen %s/%s (%s)" % (i, len(targets), str(t.get("title") or wid)[:40])) if not play_events_on(events, wid): return with lock: if not loop or state["stop_play"]: break log("Play finished.") finally: with lock: state["playing"] = False def start_play() -> None: with lock: if not state["chatPaid"]: log("Auto Farm needs a Chat plan (PayPal or Apple), same as Windows.") return if state["playing"]: return threading.Thread(target=play_loop, daemon=True).start() def apply_action(act: str) -> None: a = str(act or "").strip().lower() if a in ("record",): start_record() elif a in ("stoprec", "stop-record"): stop_record() elif a in ("play", "today"): start_play() elif a in ("stop", "stopplay", "stop-play"): stop_play() elif a in ("how", "howto"): show_how() elif a in ("open",): raise_ui() elif a in ("mark", "click"): mark_click() elif a in ("split",): split_view() elif a in ("launch", "waydroid", "emu"): launch_waydroid() elif a in ("find", "windows"): refresh_window_list() log("Found %s Android window(s)." % len(list_emu_windows())) elif a in ("use", "use-window"): use_window() elif a in ("save-size", "savesize"): save_sizes() elif a in ("restore-size", "restore"): restore_sizes() elif a in ("send", "send-order"): show_send_order() def show_how() -> None: txt = ( "Linux Auto Farm (same Chat unlock as Windows PC)\n\n" "Orders: Send order publishes to the same alliance board as the website.\n" "Chat plan is not required for orders. Set in-game name, alliance, and server.\n" "When your alliance shares a wave, the banner counts down (GET READY / SEND NOW).\n" "Optional march time makes SEND = land minus march.\n\n" "BlueStacks has no Linux version (Windows and Mac only).\n" "Use Waydroid — native Android on Linux. Docs: %s\n\n" "1. sudo apt install python3 python3-tk xdotool waydroid\n" " Then: sudo waydroid init (once) waydroid show-full-ui\n" "2. chmod +x linux-farm.sh linux-farm.py && ./linux-farm.sh\n" "3. Open raidstimer.me. Chat plan unlocks Auto Farm Record / Play, not orders.\n" "4. In this helper: Launch Waydroid, Find windows, Use window.\n" "5. Record, then Mark click / F8 on the Android window. Play runs the list.\n" "6. Save size + location, Restore, or Split 2-4. Five or more farms one at a time.\n" "7. X11 session recommended. Wayland + Waydroid can work; xdotool needs XWayland.\n" " Android Studio emulator / Genymotion windows are used if already open.\n" % WAYDROID_DOCS ) how = ui.get("how") if how: try: how.delete("1.0", "end") how.insert("end", txt) except Exception: pass log("How to use is on this window.") def raise_ui() -> None: root = ui.get("root") if not root: return try: root.deiconify() root.lift() root.focus_force() except Exception: pass def health() -> dict: with lock: wins = [] try: wins = list_emu_windows() except Exception: wins = [] with lock: return { "ok": True, "recording": bool(state["recording"]), "playing": bool(state["playing"]), "helper": "linux-farm", "version": HELPER_VERSION, "lang": state["uiLang"], "farmGame": state["farmGame"], "chatPaid": bool(state["chatPaid"]), "platform": "linux", "emu": "waydroid" if have_waydroid() else "", "windows": len(wins), "orderFireAt": int(state.get("orderFireAt") or 0), } class FarmHandler(BaseHTTPRequestHandler): def log_message(self, fmt: str, *args) -> None: return def _cors(self) -> None: self.send_header("Access-Control-Allow-Origin", "*") self.send_header("Access-Control-Allow-Methods", "GET,POST,OPTIONS") self.send_header("Access-Control-Allow-Headers", "Content-Type") self.send_header("Access-Control-Allow-Private-Network", "true") def _json(self, obj: dict, code: int = 200) -> None: raw = json.dumps(obj).encode("utf-8") self.send_response(code) self.send_header("Content-Type", "application/json; charset=utf-8") self._cors() self.send_header("Content-Length", str(len(raw))) self.end_headers() self.wfile.write(raw) def _body(self) -> dict: n = int(self.headers.get("Content-Length") or 0) if n <= 0: return {} try: return json.loads(self.rfile.read(n).decode("utf-8") or "{}") except Exception: return {} def do_OPTIONS(self) -> None: self.send_response(204) self._cors() self.end_headers() def do_GET(self) -> None: path = urlparse(self.path).path.rstrip("/").lower() or "/" if path in ("/", "/health"): self._json(health()) return self._json({"ok": False, "error": "not found"}, 404) def do_POST(self) -> None: path = urlparse(self.path).path.rstrip("/").lower() body = self._body() if path == "/ui/farmgame": gid = str(body.get("game") or "kingshot").strip().lower() or "kingshot" with lock: state["farmGame"] = gid self._json({"ok": True, "farmGame": gid}) return if path == "/ui/open": raise_ui() self._json({"ok": True, "open": True}) return if path == "/ui/chat-paid": on = body.get("active") is True or body.get("paid") is True with lock: if on: state["chatPaid"] = True paid = bool(state["chatPaid"]) if on: log("Chat unlock received. Auto Farm Record / Play are on.") paid_lbl = ui.get("paid") if paid_lbl and ui.get("root"): ui["root"].after(0, lambda: paid_lbl.config(text="Chat: unlocked")) self._json({"ok": True, "chatPaid": paid}) return if path == "/ui/lang": lang = str(body.get("lang") or "en").strip().lower()[:2] or "en" with lock: state["uiLang"] = lang self._json({"ok": True, "lang": lang}) return if path == "/ui/farm-action": act = str(body.get("action") or "open").strip().lower() if body.get("loop") is not None: with lock: state["playLoop"] = bool(body.get("loop")) if body.get("delay") is not None: try: with lock: state["playDelay"] = int(body.get("delay")) except Exception: pass with lock: paid = bool(state["chatPaid"]) if act in ("record", "play", "today") and not paid: self._json({"ok": True, "action": act, "chatPaid": False}) log("Auto Farm needs a Chat plan (PayPal or Apple), same as Windows.") return apply_action(act) self._json({"ok": True, "action": act, "chatPaid": paid}) return if path == "/record/start": start_record() self._json({"ok": True, "recording": True}) return if path == "/record/stop": stop_record() with lock: ev = list(state["events"]) self._json({"ok": True, "events": ev, "count": len(ev)}) return if path == "/stop": stop_play() self._json({"ok": True}) return if path == "/play": start_play() self._json({"ok": True}) return self._json({"ok": False, "error": "not found"}, 404) def serve() -> None: httpd = ThreadingHTTPServer(LISTEN, FarmHandler) log( "Listening on http://127.0.0.1:18765 (xdotool %s, waydroid %s)" % ("ok" if have_xdotool() else "MISSING", "ok" if have_waydroid() else "not installed") ) httpd.serve_forever() def build_ui() -> None: root = tk.Tk() ui["root"] = root root.title("Raids Timer Linux helper %s" % HELPER_VERSION) root.geometry("640x700") tk.Label(root, text="Linux Auto Farm · Waydroid (BlueStacks is Windows/Mac only)", font=("sans-serif", 11, "bold")).pack( anchor="w", padx=10, pady=(10, 4) ) clock = tk.Label( root, text="Orders: set name · alliance · server, then Send order. Countdown appears when you get a wave.", wraplength=600, justify="left", fg="#1a3a12", ) clock.pack(anchor="w", padx=10, pady=(0, 4)) ui["clock"] = clock tk.Button(root, text="Send order", command=show_send_order).pack(anchor="w", padx=10, pady=(0, 4)) paid = tk.Label(root, text="Chat: waiting for the website (open Raids Timer in the browser)") paid.pack(anchor="w", padx=10) ui["paid"] = paid emu = tk.Label(root, text="Android: checking…") emu.pack(anchor="w", padx=10) ui["emu"] = emu row = tk.Frame(root) row.pack(fill="x", padx=10, pady=6) tk.Button(row, text="Record", command=start_record).pack(side="left", padx=2) tk.Button(row, text="Stop record", command=stop_record).pack(side="left", padx=2) tk.Button(row, text="Mark click / F8", command=mark_click).pack(side="left", padx=2) tk.Button(row, text="Play", command=start_play).pack(side="left", padx=2) tk.Button(row, text="Stop", command=stop_play).pack(side="left", padx=2) row2 = tk.Frame(root) row2.pack(fill="x", padx=10, pady=2) tk.Button(row2, text="Launch Waydroid", command=launch_waydroid).pack(side="left", padx=2) tk.Button(row2, text="Find windows", command=lambda: (refresh_window_list(), log("Found %s Android window(s)." % len(list_emu_windows())))).pack( side="left", padx=2 ) tk.Button(row2, text="Use window", command=use_window).pack(side="left", padx=2) tk.Button(row2, text="Save size", command=save_sizes).pack(side="left", padx=2) tk.Button(row2, text="Restore size", command=restore_sizes).pack(side="left", padx=2) tk.Button(row2, text="Split 2-4", command=split_view).pack(side="left", padx=2) wins = tk.Listbox(root, height=4) wins.pack(fill="x", padx=10, pady=4) ui["wins"] = wins logbox = tk.Text(root, height=4, wrap="word") logbox.pack(fill="x", padx=10, pady=4) ui["log"] = logbox how = tk.Text(root, height=12, wrap="word") how.pack(fill="both", expand=True, padx=10, pady=(4, 10)) ui["how"] = how root.bind("", lambda _e: mark_click()) root.protocol("WM_DELETE_WINDOW", root.destroy) show_how() refresh_window_list() if os.environ.get("WAYLAND_DISPLAY") and not os.environ.get("DISPLAY"): log("Wayland only — xdotool often fails. Use an X11 session, or XWayland. Waydroid itself prefers Wayland.") elif not have_xdotool(): log("Install xdotool (sudo apt install xdotool) then restart this helper.") elif not have_waydroid(): log("Install Waydroid (%s), then Launch Waydroid. Chat plan required, same as PC." % WAYDROID_DOCS) else: log("Ready. Launch Waydroid, then raidstimer.me → Auto Farm. Chat plan required, same as PC.") def main() -> None: load_farm() threading.Thread(target=serve, daemon=True).start() threading.Thread(target=order_poll_loop, daemon=True).start() build_ui() ui["root"].mainloop() if __name__ == "__main__": main()