slighted / sync_thread.py
abr00kx's picture
Upload folder using huggingface_hub
ae78352 verified
Raw History Blame Contribute Delete
6.42 kB
#!/usr/bin/env python3
"""
Synchronize to a specific awoo.cf thread over WebSocket.
Target: https://awoo.cf/g/1256858?last=100#bottom
"""
import asyncio
import json
import secrets
import sys
import time
from typing import Optional
import aiohttp
import websockets
from extract_firefox_cookies import extract_cookies
async def sync_to_thread(board: str = "g", thread_id: int = 1256858, duration: Optional[float] = None):
print(f"=== Synchronizing to https://awoo.cf/{board}/{thread_id} ===")
# 1. Cookies
print("Extracting Firefox session cookies...")
cookies = extract_cookies()
cookie_str = "; ".join(f"{k}={v}" for k, v in cookies.items())
meta_pass = cookies.get("meta_pass", "")
print(f"Loaded {len(cookies)} cookies (including mgc_fpc and cf_clearance)")
# 2. Token pre-binding
binding = secrets.token_urlsafe(32)
print("Registering token binding with backend...")
async with aiohttp.ClientSession() as http:
async with http.post(
"https://p.awoo.cf/v1/token",
json={"binding": binding},
headers={"Origin": "https://awoo.cf", "Cookie": cookie_str},
timeout=aiohttp.ClientTimeout(total=15),
) as resp:
if resp.status != 200:
raise RuntimeError(f"Token registration HTTP {resp.status}")
# 3. Open WebSocket
url = f"wss://p.awoo.cf/api/socket?binding={binding}"
headers = {"Origin": "https://awoo.cf", "Cookie": cookie_str}
print(f"Connecting to WebSocket: {url[:45]}...")
async with websockets.connect(url, additional_headers=headers, compression="deflate") as ws:
print("[WS] Connected. Solving challenge handshake...")
token = None
rounds = 0
while True:
msg = await asyncio.wait_for(ws.recv(), timeout=10.0)
if isinstance(msg, bytes):
msg = msg.decode("utf-8", errors="ignore")
msg = msg.strip()
if msg.isdigit():
val = int(msg)
if 100000 <= val <= 1999999:
rounds += 1
await ws.send(str(val + 1))
elif msg.startswith("v2."):
token = msg
print(f"[WS] Authenticated ({rounds} challenge rounds solved). Token: {token[:35]}...")
break
elif msg == "error":
raise RuntimeError("Server rejected challenge handshake")
# 4. Synchronize to thread
print(f"[WS] Sending SYNCHRONISE (44) for /{board}/{thread_id}...")
sync_payload = {
"board": board,
"thread": thread_id,
"protocolVersion": 1,
"loginData": None,
"seal": "noWASM",
"fp": token,
"meta_pass": meta_pass,
}
await ws.send("44" + json.dumps(sync_payload))
print(">>> SYNCHRONIZED TO THREAD! Streaming live updates (Ctrl+C to stop) <<<")
start_time = time.time()
last_ping = time.time()
while True:
if duration and (time.time() - start_time) >= duration:
print(f"Requested duration ({duration}s) reached.")
break
# Send periodic keepalive NOOP (48) every 20s
now = time.time()
if now - last_ping >= 20.0:
await ws.send("48")
last_ping = now
try:
msg = await asyncio.wait_for(ws.recv(), timeout=2.0)
if isinstance(msg, bytes):
msg = msg.decode("utf-8", errors="ignore")
# Parse message type prefix
prefix = msg[:2]
payload = msg[2:]
if prefix == "44":
try:
data = json.loads(payload)
recent = data.get("recent", {})
print(f"\n[SYNC UPDATE 44] Thread state received: {len(recent)} recent posts synced")
for pid, pdata in list(recent.items())[-5:]:
body = pdata.get("body", "")
closed = pdata.get("closed", False)
has_img = pdata.get("has_image", False)
status_desc = []
if closed:
status_desc.append("closed")
if has_img:
status_desc.append("image")
desc = f" ({', '.join(status_desc)})" if status_desc else ""
print(f" -> Post #{pid}{desc}: {repr(body[:80]) if body else ''}")
except Exception:
print(f"[FRAME 44] {msg[:160]}...")
elif prefix == "01":
print(f"\n[NEW POST 01] {payload}")
elif prefix == "02":
print(f"[APPEND 02] {payload}")
elif prefix == "04":
print(f"[SPLICE 04] {payload}")
elif prefix == "05":
print(f"[CLOSE POST 05] {payload}")
elif prefix == "50":
print(f"[SERVER TIME 50] {payload}")
elif prefix == "55":
print(f"[BOARD CONFIG 55] Title: {json.loads(payload).get('title')}")
elif prefix == "63":
print(f"[PRESENCE 63] {payload}")
elif prefix == "80":
print(f"[LIVE STATUS 80] {payload}")
else:
print(f"[FRAME {prefix}] {payload[:120]}")
except asyncio.TimeoutError:
continue
except websockets.exceptions.ConnectionClosed as e:
print(f"[WS CLOSED] Connection closed by server: {e}")
break
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Sync to awoo.cf thread")
parser.add_argument("--board", default="g", help="Board code")
parser.add_argument("--thread", type=int, default=1256858, help="Thread ID")
parser.add_argument("--duration", type=float, default=None, help="Duration to stay synced (seconds)")
args = parser.parse_args()
try:
asyncio.run(sync_to_thread(board=args.board, thread_id=args.thread, duration=args.duration))
except KeyboardInterrupt:
print("\nDisconnected.")