File size: 6,423 Bytes
ae78352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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.")