event_server.py
6.71 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
"""
Android Event Bus Server
Runs in Termux, receives events from Android APK (Accessibility, Notification, Clipboard)
and serves them to Hermes via polling.
Usage:
uvicorn event_server:app --host 127.0.0.1 --port 8765
"""
import sqlite3
import json
import time
import os
from pathlib import Path
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, Query
from pydantic import BaseModel
from typing import Any
DB_PATH = Path(os.environ.get("EVENT_BUS_DB", str(Path.home() / ".hermes" / "event_bus" / "events.db")))
MAX_EVENTS = int(os.environ.get("EVENT_BUS_MAX", "20000"))
def get_db() -> sqlite3.Connection:
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
def init_db():
with get_db() as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT NOT NULL,
app TEXT,
data TEXT NOT NULL,
ts REAL NOT NULL,
source TEXT DEFAULT 'monitor'
)
""")
conn.execute("CREATE INDEX IF NOT EXISTS idx_events_ts ON events(ts)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_events_type ON events(type)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_events_source ON events(source)")
# Migration: add source column if it doesn't exist yet (for existing DBs)
try:
conn.execute("ALTER TABLE events ADD COLUMN source TEXT DEFAULT 'monitor'")
except sqlite3.OperationalError:
pass # column already exists
conn.commit()
@asynccontextmanager
async def lifespan(app: FastAPI):
init_db()
yield
# trim old events on shutdown
_trim_events()
app = FastAPI(title="Android Event Bus", lifespan=lifespan)
class Event(BaseModel):
type: str # e.g. "notification", "ui_event", "clipboard", "app_lifecycle"
app: str | None = None # package name, e.g. "com.tencent.mm"
data: dict[str, Any] = {}
source: str = "monitor" # "monitor" (dumpsys) or "apk" (Android APK)
class EventOut(BaseModel):
id: int
type: str
app: str | None
data: dict[str, Any]
ts: float
source: str = "monitor"
def _trim_events():
with get_db() as conn:
conn.execute(f"""
DELETE FROM events WHERE id NOT IN (
SELECT id FROM events ORDER BY id DESC LIMIT {MAX_EVENTS}
)
""")
conn.commit()
@app.post("/events", status_code=201)
def post_event(event: Event):
"""Android APK posts events here."""
with get_db() as conn:
cursor = conn.execute(
"INSERT INTO events (type, app, data, ts, source) VALUES (?, ?, ?, ?, ?)",
(event.type, event.app, json.dumps(event.data), time.time(), event.source)
)
conn.commit()
return {"id": cursor.lastrowid}
@app.post("/events/batch", status_code=201)
def post_events_batch(events: list[Event]):
"""Android APK posts multiple events at once."""
if not events:
return {"count": 0, "last_id": None}
ts = time.time()
rows = [(e.type, e.app, json.dumps(e.data), ts, e.source) for e in events]
with get_db() as conn:
conn.executemany(
"INSERT INTO events (type, app, data, ts, source) VALUES (?, ?, ?, ?, ?)", rows
)
conn.commit()
last_id = conn.execute("SELECT last_insert_rowid()").fetchone()[0]
return {"count": len(events), "last_id": last_id}
@app.get("/events", response_model=list[EventOut])
def get_events(
since_id: int = Query(default=0, description="Return events with id > since_id"),
limit: int = Query(default=50, le=500),
type: str | None = Query(default=None, description="Filter by event type"),
app: str | None = Query(default=None, description="Filter by app package"),
source: str | None = Query(default=None, description="Filter by source: 'monitor' or 'apk'"),
):
"""Hermes MCP polls here."""
sql = "SELECT id, type, app, data, ts, source FROM events WHERE id > ?"
params: list[Any] = [since_id]
if type:
sql += " AND type = ?"
params.append(type)
if app:
sql += " AND app = ?"
params.append(app)
if source:
sql += " AND source = ?"
params.append(source)
sql += " ORDER BY id ASC LIMIT ?"
params.append(limit)
with get_db() as conn:
rows = conn.execute(sql, params).fetchall()
return [
EventOut(id=r["id"], type=r["type"], app=r["app"],
data=json.loads(r["data"]), ts=r["ts"],
source=r["source"] or "monitor")
for r in rows
]
@app.get("/events/latest", response_model=list[EventOut])
def get_latest_events(
limit: int = Query(default=20, le=200),
type: str | None = Query(default=None),
app: str | None = Query(default=None),
source: str | None = Query(default=None, description="Filter by source: 'monitor' or 'apk'"),
):
"""Get the most recent N events (for debugging / initial load)."""
sql = "SELECT id, type, app, data, ts, source FROM events WHERE 1=1"
params: list[Any] = []
if type:
sql += " AND type = ?"
params.append(type)
if app:
sql += " AND app = ?"
params.append(app)
if source:
sql += " AND source = ?"
params.append(source)
sql += " ORDER BY id DESC LIMIT ?"
params.append(limit)
with get_db() as conn:
rows = conn.execute(sql, params).fetchall()
return [
EventOut(id=r["id"], type=r["type"], app=r["app"],
data=json.loads(r["data"]), ts=r["ts"],
source=r["source"] or "monitor")
for r in reversed(rows)
]
@app.get("/stats")
def get_stats():
"""Event queue stats."""
with get_db() as conn:
total = conn.execute("SELECT COUNT(*) FROM events").fetchone()[0]
last = conn.execute("SELECT id, type, app, ts FROM events ORDER BY id DESC LIMIT 1").fetchone()
oldest = conn.execute("SELECT id, ts FROM events ORDER BY id ASC LIMIT 1").fetchone()
return {
"total_events": total,
"last_event_id": last["id"] if last else None,
"last_event_type": last["type"] if last else None,
"last_event_app": last["app"] if last else None,
"oldest_event_ts": oldest["ts"] if oldest else None,
"db_path": str(DB_PATH),
"max_events": MAX_EVENTS,
}
@app.delete("/events")
def clear_events():
"""Clear all events (dev/debug only)."""
with get_db() as conn:
conn.execute("DELETE FROM events")
conn.commit()
return {"cleared": True}
@app.get("/health")
def health():
return {"status": "ok", "ts": time.time()}