-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutils.py
More file actions
108 lines (95 loc) · 3.3 KB
/
Copy pathutils.py
File metadata and controls
108 lines (95 loc) · 3.3 KB
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
"""Async helpers for proxy IP checks."""
import asyncio
import ipaddress
import json
import ssl
import aiohttp
import certifi
ssl_ctx = ssl.create_default_context(cafile=certifi.where())
DEFAULT_CHECK_URL = "https://api.myip.com"
DEFAULT_TIMEOUT = 5
def extract_ip_from_response(response_body: str):
"""Extract IP from JSON/plain-text check service responses."""
stripped = response_body.strip()
if not stripped:
return None
parsed = stripped
try:
parsed = json.loads(stripped)
except json.JSONDecodeError:
parsed = stripped
candidates = []
if isinstance(parsed, dict):
for key in ("ip", "origin", "query"):
value = parsed.get(key)
if isinstance(value, str):
candidates.append(value)
elif isinstance(parsed, str):
candidates.append(parsed)
for candidate in candidates:
first_part = candidate.split(",")[0].strip()
try:
ipaddress.ip_address(first_part)
return first_part
except ValueError:
continue
return None
async def _get_starship(
proxy: str,
check_url: str = DEFAULT_CHECK_URL,
timeout: int = DEFAULT_TIMEOUT,
):
"""Fetch the caller's IP via the proxy using a default SSL context."""
async with aiohttp.ClientSession() as session:
try:
async with session.get(
url=check_url,
proxy=proxy,
timeout=timeout
) as response:
response.raise_for_status()
body = await response.text()
ip = extract_ip_from_response(body)
if ip is None:
return {
"status": False,
"message": f"IP not found in response from {check_url}",
"proxy": proxy,
}
return {
"status": True,
"message": {"ip": ip},
"proxy": proxy,
}
except (aiohttp.ClientError, asyncio.TimeoutError, ssl.SSLError) as e:
return {"status": False, "message": str(e), "proxy": proxy}
async def get_starship(
proxy: str,
check_url: str = DEFAULT_CHECK_URL,
timeout: int = DEFAULT_TIMEOUT,
):
"""Fetch the caller's IP via the proxy using the shared SSL context."""
async with aiohttp.ClientSession() as session:
try:
async with session.get(
url=check_url,
proxy=proxy,
ssl=ssl_ctx,
timeout=timeout
) as response:
response.raise_for_status()
body = await response.text()
ip = extract_ip_from_response(body)
if ip is None:
return {
"status": False,
"message": f"IP not found in response from {check_url}",
"proxy": proxy,
}
return {
"status": True,
"message": {"ip": ip},
"proxy": proxy,
}
except (aiohttp.ClientError, asyncio.TimeoutError, ssl.SSLError) as e:
return {"status": False, "message": str(e), "proxy": proxy}