#!/usr/bin/env python3 """A loopback stand-in for the Pipelines server's notification socket. For checking Android background delivery on the managed emulator without the real server: the emulator reaches it at ws://10.0.2.2:/connect. python3 -I tool/fake_notification_server.py --port 0 --log /tmp/notify.log * GET /login answers 302, so the app treats the device as signed in. * /connect speaks the notification protocol: `subscribe_notifications` (replayed with `notifications_subscribed`), `clear_notifications` (logged and echoed to every socket as `notifications_cleared`). Any other request gets an `error` reply so the app does not wait for its timeout. * POST /push?id=&kind=&title=&message=&click=&priority=&group= pushes `{"type":"notification","notification":{...}}`. * POST /clear?id=a,b pushes `notifications_cleared` (another device cleared). Every frame received is appended to --log as one JSON line. Standard library only; not a general websocket server (text frames, no fragmentation). """ import argparse import base64 import datetime import hashlib import json import socketserver import struct import threading import urllib.parse from http.server import BaseHTTPRequestHandler GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" clients = [] store = [] # active notifications, oldest first cleared = [] # recently cleared ids, sent with notifications_subscribed lock = threading.Lock() log_path = None def log(entry): line = json.dumps(entry) print(line, flush=True) if log_path: with open(log_path, "a", encoding="utf-8") as handle: handle.write(line + "\n") def frame(text): data = text.encode() header = bytearray([0x81]) if len(data) < 126: header.append(len(data)) elif len(data) < 65536: header += bytes([126]) + struct.pack(">H", len(data)) else: header += bytes([127]) + struct.pack(">Q", len(data)) return bytes(header) + data def broadcast(message): payload = frame(json.dumps(message)) with lock: for wfile in list(clients): try: wfile.write(payload) wfile.flush() except OSError: clients.remove(wfile) def read_frame(rfile): head = rfile.read(2) if len(head) < 2: return None, None opcode = head[0] & 0x0F length = head[1] & 0x7F if length == 126: length = struct.unpack(">H", rfile.read(2))[0] elif length == 127: length = struct.unpack(">Q", rfile.read(8))[0] mask = rfile.read(4) if head[1] & 0x80 else b"\0\0\0\0" data = bytes(b ^ mask[i % 4] for i, b in enumerate(rfile.read(length))) return opcode, data class Handler(BaseHTTPRequestHandler): # Clients reject an "HTTP/1.0 101" upgrade. protocol_version = "HTTP/1.1" def log_message(self, *args): pass def do_GET(self): path = urllib.parse.urlparse(self.path).path if path == "/login": self.send_response(302) self.send_header("Location", "/") self.send_header("Content-Length", "0") self.end_headers() elif path == "/connect" and self.headers.get("Upgrade", "").lower() == "websocket": self.websocket() else: self.send_response(404) self.send_header("Content-Length", "0") self.end_headers() def do_POST(self): url = urllib.parse.urlparse(self.path) query = {k: v[-1] for k, v in urllib.parse.parse_qs(url.query).items()} if url.path == "/push": notification = { "id": query.get("id", "n-%d" % len(store)), "kind": query.get("kind", "run_failed"), "title": query.get("title", "Run failed"), "message": query.get("message", "A step failed"), "click": query.get("click", "pipelines://run/1"), "priority": int(query.get("priority", "3")), "tags": [], "created_at": datetime.datetime.now(datetime.timezone.utc).isoformat(), "group": query.get("group", ""), } store.append(notification) broadcast({"type": "notification", "notification": notification}) elif url.path == "/clear": ids = [i for i in query.get("id", "").split(",") if i] store[:] = [n for n in store if n["id"] not in ids] cleared.extend(ids) broadcast({"type": "notifications_cleared", "ids": ids}) else: self.send_response(404) self.send_header("Content-Length", "0") self.end_headers() return self.send_response(204) self.send_header("Content-Length", "0") self.end_headers() def websocket(self): key = self.headers["Sec-WebSocket-Key"] accept = base64.b64encode(hashlib.sha1((key + GUID).encode()).digest()).decode() self.send_response(101) self.send_header("Upgrade", "websocket") self.send_header("Connection", "Upgrade") self.send_header("Sec-WebSocket-Accept", accept) self.end_headers() self.wfile.flush() log({"event": "connect", "cookie": self.headers.get("Cookie", ""), "agent": self.headers.get("User-Agent", "")}) with lock: clients.append(self.wfile) try: while True: opcode, data = read_frame(self.rfile) if opcode is None or opcode == 0x8: break if opcode == 0x9: # ping -> pong with lock: self.wfile.write(bytes([0x8A, len(data)]) + data) self.wfile.flush() continue if opcode != 0x1: continue self.on_message(json.loads(data)) finally: with lock: if self.wfile in clients: clients.remove(self.wfile) log({"event": "disconnect"}) def send(self, message): with lock: self.wfile.write(frame(json.dumps(message))) self.wfile.flush() def on_message(self, message): log({"event": "received", "message": message}) kind, request = message.get("type"), message.get("id") if kind == "subscribe_notifications": after = message.get("after") ids = [n["id"] for n in store] replay = store[ids.index(after) + 1:] if after in ids else list(store) self.send({"type": "notifications_subscribed", "id": request, "notifications": replay, "ids": cleared[-50:]}) elif kind == "clear_notifications": ids = message.get("ids", []) store[:] = [n for n in store if n["id"] not in ids] cleared.extend(ids) self.send({"type": "notifications_cleared", "id": request, "ids": ids}) broadcast({"type": "notifications_cleared", "ids": ids}) elif request: self.send({"type": "error", "id": request, "error": "fake server: %s" % kind}) class Server(socketserver.ThreadingMixIn, socketserver.TCPServer): allow_reuse_address = True daemon_threads = True def main(): global log_path parser = argparse.ArgumentParser() parser.add_argument("--host", default="127.0.0.1") parser.add_argument("--port", type=int, default=0) parser.add_argument("--log") args = parser.parse_args() log_path = args.log with Server((args.host, args.port), Handler) as server: log({"event": "listening", "port": server.server_address[1]}) server.serve_forever() if __name__ == "__main__": main()