File size: 7,315 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
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
#!/usr/bin/env python3
"""
Open and maintain concurrent WebSocket connections to awoo.cf.
Handles token registration, 6-step challenge-response handshake, and live stream synchronization.
"""

import argparse
import asyncio
import json
import secrets
import sys
import time
from typing import List, Optional

import aiohttp
from aiohttp_socks import ProxyConnector

from extract_firefox_cookies import extract_cookies


async def run_connection(
    index: int,
    cookie_str: str,
    meta_pass: str,
    proxy_url: Optional[str] = None,
    stop_event: Optional[asyncio.Event] = None,
    board: str = "all",
    stats_dict: Optional[dict] = None,
):
    """Establish and maintain an authenticated WebSocket connection."""
    tag = f"[{index:02d}]"
    if stats_dict is not None:
        stats_dict[index] = "CONNECTING"

    while not (stop_event and stop_event.is_set()):
        session = None
        try:
            connector = ProxyConnector.from_url(proxy_url) if proxy_url else None
            session = aiohttp.ClientSession(connector=connector)

            binding = secrets.token_urlsafe(32)

            # 1. Register token binding with backend
            async with session.post(
                "https://p.awoo.cf/v1/token",
                json={"binding": binding},
                headers={
                    "Content-Type": "application/json",
                    "Origin": "https://awoo.cf",
                    "Cookie": cookie_str,
                },
                timeout=aiohttp.ClientTimeout(total=15),
            ) as token_resp:
                if token_resp.status != 200:
                    raise RuntimeError(f"Token registration HTTP {token_resp.status}")

            # 2. Upgrade to WebSocket
            endpoint = f"wss://p.awoo.cf/api/socket?binding={binding}"
            headers = {
                "Origin": "https://awoo.cf",
                "Cookie": cookie_str,
            }

            async with session.ws_connect(
                endpoint,
                headers=headers,
                timeout=aiohttp.ClientTimeout(total=15),
            ) as ws:
                # 3. Solve 6-round challenge-response handshake
                token = None
                while True:
                    msg = await asyncio.wait_for(ws.receive(), timeout=10.0)
                    if msg.type != aiohttp.WSMsgType.TEXT:
                        raise RuntimeError(f"Unexpected WS frame type: {msg.type}")

                    data = msg.data.strip()
                    if data.isdigit():
                        val = int(data)
                        if 100000 <= val <= 1999999:
                            await ws.send_str(str(val + 1))
                    elif data.startswith("v2."):
                        token = data
                        break
                    elif data == "error":
                        raise RuntimeError("Server rejected challenge handshake")

                # 4. Synchronize to target board
                sync_payload = {
                    "board": board,
                    "thread": None,
                    "protocolVersion": 1,
                    "loginData": None,
                    "seal": "noWASM",
                    "fp": token,
                    "meta_pass": meta_pass,
                }
                await ws.send_str("44" + json.dumps(sync_payload))
                if stats_dict is not None:
                    stats_dict[index] = "ONLINE"
                print(f"{tag} Connected and synchronized to /{board}/")

                # 5. Maintain streaming connection and keepalive pings
                last_ping = time.time()
                while not (stop_event and stop_event.is_set()):
                    now = time.time()
                    if now - last_ping >= 20.0:
                        await ws.send_str("48")
                        last_ping = now

                    try:
                        msg = await asyncio.wait_for(ws.receive(), timeout=5.0)
                        if msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.CLOSING):
                            print(f"{tag} Connection closed by server")
                            break
                        elif msg.type == aiohttp.WSMsgType.ERROR:
                            print(f"{tag} WebSocket error: {ws.exception()}")
                            break
                    except asyncio.TimeoutError:
                        continue

        except Exception as e:
            if stats_dict is not None:
                stats_dict[index] = f"ERROR: {e}"
            print(f"{tag} Worker error: {e}")

            if stop_event and stop_event.is_set():
                break
            await asyncio.sleep(5)
        finally:
            if session:
                await session.close()


async def main():
    parser = argparse.ArgumentParser(description="Multi-instance WebSocket runner for awoo.cf")
    parser.add_argument("-n", "--connections", type=int, default=30, help="Number of concurrent connections (default: 30)")
    parser.add_argument("-b", "--board", default="all", help="Board to synchronize (default: all)")
    parser.add_argument("-d", "--duration", type=float, default=None, help="Duration to run in seconds (default: indefinite)")
    parser.add_argument("--proxy-file", default=None, help="Optional path to a file with proxy URLs (one per line)")
    args = parser.parse_args()

    print("Extracting session cookies from Firefox...")
    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)")

    proxies = []
    if args.proxy_file:
        with open(args.proxy_file, "r") as f:
            proxies = [line.strip() for line in f if line.strip() and not line.startswith("#")]
        print(f"Loaded {len(proxies)} proxies from {args.proxy_file}")

    stop_event = asyncio.Event()
    stats_dict = {}

    print(f"Launching {args.connections} concurrent connections to /{args.board}/...")
    tasks = []
    for i in range(args.connections):
        proxy_url = proxies[i % len(proxies)] if proxies else None
        task = asyncio.create_task(
            run_connection(
                i,
                cookie_str,
                meta_pass,
                proxy_url=proxy_url,
                stop_event=stop_event,
                board=args.board,
                stats_dict=stats_dict,
            )
        )
        tasks.append(task)
        await asyncio.sleep(0.08)

    print(f"All {args.connections} workers launched. Press Ctrl+C to stop.")

    try:
        if args.duration:
            await asyncio.sleep(args.duration)
            print(f"\nTarget duration ({args.duration}s) reached.")
        else:
            while True:
                await asyncio.sleep(10)
                online = sum(1 for v in stats_dict.values() if v == "ONLINE")
                print(f"[STATUS] {online}/{args.connections} connections active")
    except KeyboardInterrupt:
        print("\nStopping connections...")
    finally:
        stop_event.set()
        await asyncio.gather(*tasks, return_exceptions=True)
        print("Shutdown complete.")


if __name__ == "__main__":
    asyncio.run(main())