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4b6
 
 
ae1cf78
 
c1ec4b6
ae1cf78
 
c1ec4b6
 
 
 
ae1cf78
c1ec4b6
 
ae1cf78
c1ec4b6
 
 
 
 
 
ae1cf78
 
27cb2fd
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
"""
CroxyProxy Rotating Proxy API - HuggingFace Spaces
90 servers: Paris, LA, Dallas, Warsaw, Amsterdam...

GET  /health         - Status
GET  /servers        - List 90 servers
POST /proxy/fetch    - Rotating proxy
POST /proxy/random   - Random server
POST /proxy/batch    - Multiple URLs
"""

import json, base64, re, random, time, threading
from datetime import datetime, timezone
from flask import Flask, request, jsonify
from bs4 import BeautifulSoup
import cloudscraper
from html import unescape
import warnings
warnings.filterwarnings("ignore")

BASE = "https://www.croxyproxy.com"
app = Flask(__name__)

KEEP_HEADERS = {
    "content-type", "content-length", "content-encoding",
    "server", "date", "connection",
    "access-control-allow-origin",
    "access-control-allow-credentials",
    "cache-control", "etag", "last-modified",
    "x-ratelimit-limit", "x-ratelimit-remaining",
    "x-request-id", "location", "retry-after",
}

DROP_HEADERS = {
    "set-cookie", "__cph", "__cpc",
    "content-security-policy", "strict-transport-security",
    "referrer-policy", "access-control-allow-headers",
    "x-frame-options", "x-content-type-options",
    "permissions-policy", "cross-origin-opener-policy",
    "cross-origin-embedder-policy",
}


class S:
    servers = []
    idx = 0
    lock = threading.Lock()
    last = None
    stats = {"req": 0, "ok": 0, "fail": 0}


def dec(e):
    try:
        return json.loads(bytes.fromhex(base64.b64decode(e).decode()).decode())
    except Exception:
        return None


def filter_headers(raw_headers, include_all=False):
    if include_all:
        return dict(raw_headers)
    cleaned = {}
    for k, v in raw_headers.items():
        kl = k.lower()
        if kl in DROP_HEADERS:
            continue
        if kl in KEEP_HEADERS:
            cleaned[k] = v
    return cleaned


def parse_body(text, content_type=""):
    if not text:
        return None
    if "json" in content_type.lower() or text.strip().startswith(("{", "[")):
        try:
            return json.loads(text)
        except (json.JSONDecodeError, ValueError):
            pass
    if "html" in content_type.lower() or text.strip().startswith("<"):
        return {
            "_type": "html",
            "_length": len(text),
            "content": text,
            "_preview": text[:300].strip() + ("..." if len(text) > 300 else ""),
        }
    if len(text) > 2000:
        return {
            "_type": "text",
            "_length": len(text),
            "content": text,
            "_preview": text[:500].strip() + "...",
        }
    return text


def extract_ip(url_str):
    return (url_str or "").replace("https://", "").replace("http://", "").split("/")[0]


def format_result(raw, include_raw_headers=False):
    if not raw.get("success"):
        return {
            "success": False,
            "error": raw.get("error"),
            "server": raw.get("server"),
        }
    ct = ""
    if raw.get("headers"):
        ct = raw["headers"].get("Content-Type", raw["headers"].get("content-type", ""))
    result = {
        "success": True,
        "status": raw.get("status"),
        "url": raw.get("url"),
        "body": parse_body(raw.get("body", ""), ct),
        "proxy": raw.get("proxy"),
        "servers_available": raw.get("servers_available"),
    }
    if raw.get("headers"):
        result["headers"] = filter_headers(raw["headers"], include_all=include_raw_headers)
    return result


def fetch_raw(url, sid=None):
    sc = cloudscraper.create_scraper(
        browser={"browser": "chrome", "platform": "windows", "desktop": True}
    )
    S.stats["req"] += 1
    try:
        r1 = sc.get(BASE, timeout=30)
        if r1.status_code != 200:
            S.stats["fail"] += 1
            return {"success": False, "error": f"Homepage {r1.status_code}"}

        s1 = BeautifulSoup(r1.text, "lxml")
        ci = s1.find("input", {"name": "csrf"})
        if not ci:
            S.stats["fail"] += 1
            return {"success": False, "error": "No CSRF"}

        r2 = sc.post(
            f"{BASE}/servers",
            data={
                "url": url, "proxyServerId": "274",
                "csrf": ci["value"], "demo": "0",
                "frontOrigin": BASE,
            },
            headers={
                "Content-Type": "application/x-www-form-urlencoded",
                "Origin": BASE,
                "Referer": BASE + "/",
            },
            allow_redirects=True,
            timeout=30,
        )

        if r2.status_code != 200:
            S.stats["fail"] += 1
            return {"success": False, "error": f"Servers {r2.status_code}"}

        s2 = BeautifulSoup(r2.text, "lxml")
        sel = s2.find("script", {"id": "serverSelectorScript"})
        if not sel:
            S.stats["fail"] += 1
            return {"success": False, "error": "No selector"}

        ss = [
            x for x in (dec(i) for i in json.loads(unescape(sel.get("data-ss", ""))))
            if x and x.get("id")
        ]
        csrf2 = unescape(sel.get("data-csrf", "")).strip('"')
        fo = unescape(sel.get("data-fo", "")).strip('"')

        if not ss:
            S.stats["fail"] += 1
            return {"success": False, "error": "No servers"}

        S.servers = ss
        S.last = datetime.now(timezone.utc).isoformat()

        ch = None
        if sid:
            ch = next((x for x in ss if x["id"] == sid), None)
        if not ch:
            with S.lock:
                ch = ss[S.idx % len(ss)]
                S.idx += 1

        r3 = sc.post(
            f"{BASE}/requests?fso=",
            data={
                "url": url, "proxyServerId": str(ch["id"]),
                "csrf": csrf2, "demo": "0", "frontOrigin": fo,
            },
            headers={
                "Content-Type": "application/x-www-form-urlencoded",
                "Origin": BASE,
                "Referer": f"{BASE}/servers",
            },
            allow_redirects=False,
            timeout=30,
        )

        loc = r3.headers.get("Location") or r3.headers.get("location")
        if not loc:
            S.stats["fail"] += 1
            return {
                "success": False,
                "error": f"No redirect ({r3.status_code})",
                "server": ch.get("name"),
            }

        r4 = sc.get(loc, timeout=30, allow_redirects=True)
        dr = re.search(r'data-r="([^"]+)"', r4.text)
        if not dr:
            S.stats["fail"] += 1
            return {"success": False, "error": "No data-r", "server": ch.get("name")}

        final = base64.b64decode(dr.group(1)).decode()
        r5 = sc.get(final, timeout=30, allow_redirects=True)

        S.stats["ok"] += 1
        return {
            "success": True,
            "status": r5.status_code,
            "headers": dict(r5.headers),
            "body": r5.text,
            "url": url,
            "proxy": {
                "server_id": ch["id"],
                "server_name": ch.get("name"),
                "ip": extract_ip(ch.get("url", "")),
            },
            "servers_available": len(ss),
        }
    except Exception as e:
        S.stats["fail"] += 1
        return {"success": False, "error": str(e)}


def warmup():
    """Populate server list on startup."""
    print("Warming up β€” populating server list...")
    result = fetch_raw("https://httpbin.org/ip")
    if result.get("success"):
        print(f"βœ“ {len(S.servers)} servers loaded")
    else:
        print(f"βœ— Warm-up failed: {result.get('error')}")


# Gunicorn hook β€” runs in each worker after fork
def post_fork(server, worker):
    warmup()


# Runs at import time β€” works for both gunicorn and direct python
warmup()


# ═══════════════════════════════════════════════
#  ROUTES
# ═══════════════════════════════════════════════

@app.route("/")
def index():
    return jsonify({
        "name": "CroxyProxy Rotating Proxy API",
        "version": "2.0",
        "endpoints": {
            "GET /health": "Status + stats",
            "GET /servers": "List all servers",
            "POST /proxy/fetch": "Rotating proxy {url, server_id?, raw_headers?}",
            "POST /proxy/random": "Random server {url, raw_headers?}",
            "POST /proxy/batch": "Multiple URLs {urls: [...], raw_headers?}",
        },
        "notes": {
            "raw_headers": "Set to true to get ALL response headers (default: filtered)",
            "body": "JSON bodies are auto-parsed. HTML is truncated with preview.",
        },
    })


@app.route("/health")
def health():
    return jsonify({
        "status": "ready",
        "servers": len(S.servers),
        "last_refresh": S.last,
        "stats": S.stats,
    })


@app.route("/servers")
def servers():
    return jsonify({
        "count": len(S.servers),
        "servers": [
            {
                "id": s.get("id"),
                "name": s.get("name"),
                "ip": extract_ip(s.get("url", "")),
            }
            for s in S.servers
        ],
    })


@app.route("/proxy/fetch", methods=["POST"])
def proxy_fetch():
    d = request.get_json() or {}
    if not d.get("url"):
        return jsonify({"error": "url required"}), 400
    raw = fetch_raw(d["url"], d.get("server_id"))
    return jsonify(format_result(raw, include_raw_headers=d.get("raw_headers", False)))


@app.route("/proxy/random", methods=["POST"])
def proxy_random():
    d = request.get_json() or {}
    if not d.get("url"):
        return jsonify({"error": "url required"}), 400
    sid = random.choice(S.servers)["id"] if S.servers else None
    raw = fetch_raw(d["url"], sid)
    return jsonify(format_result(raw, include_raw_headers=d.get("raw_headers", False)))


@app.route("/proxy/batch", methods=["POST"])
def proxy_batch():
    d = request.get_json() or {}
    urls = d.get("urls", [])
    if not urls:
        return jsonify({"error": "urls required"}), 400
    include_raw = d.get("raw_headers", False)
    results = []
    for u in urls:
        raw = fetch_raw(u)
        results.append(format_result(raw, include_raw_headers=include_raw))
        time.sleep(0.5)
    return jsonify({
        "count": len(results),
        "success_count": sum(1 for r in results if r.get("success")),
        "results": results,
    })


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=7860)