Skip to content

Commit 7437063

Browse files
committed
auto format
1 parent bfb6272 commit 7437063

2 files changed

Lines changed: 122 additions & 101 deletions

File tree

‎proxy_checker/proxy_checker.py‎

Lines changed: 120 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
import os
33
import random
44
import re
5-
from io import BytesIO
65
import time
6+
from io import BytesIO
77
from typing import Any, Optional, Union
88

99
import certifi
@@ -15,13 +15,13 @@ def __init__(self, timeout: int = 5000, verbose: bool = False):
1515
self.timeout = timeout
1616
self.verbose = verbose
1717
self.proxy_judges = [
18-
'https://wfuchs.de/azenv.php',
19-
'http://mojeip.net.pl/asdfa/azenv.php',
20-
'http://httpheader.net/azenv.php',
21-
'http://pascal.hoez.free.fr/azenv.php',
22-
'https://www.cooleasy.com/azenv.php',
23-
'http://azenv.net/',
24-
'http://sh.webmanajemen.com/data/azenv.php'
18+
"https://wfuchs.de/azenv.php",
19+
"http://mojeip.net.pl/asdfa/azenv.php",
20+
"http://httpheader.net/azenv.php",
21+
"http://pascal.hoez.free.fr/azenv.php",
22+
"https://www.cooleasy.com/azenv.php",
23+
"http://azenv.net/",
24+
"http://sh.webmanajemen.com/data/azenv.php",
2525
]
2626

2727
self.ip = self.get_device_ip()
@@ -34,23 +34,23 @@ def __init__(self, timeout: int = 5000, verbose: bool = False):
3434

3535
def change_timeout(self, timeout: int) -> None:
3636
"""
37-
Sets timeout for requests
38-
Args:
39-
:param timeout, int. Timeout in ms
37+
Sets timeout for requests
38+
Args:
39+
:param timeout, int. Timeout in ms
4040
"""
4141
self.timeout = timeout
4242

4343
def change_verbose(self, value: bool) -> None:
4444
"""
45-
Sets verbose for curl
45+
Sets verbose for curl
4646
"""
4747
self.verbose = value
4848

4949
def check_proxy_judges(self) -> None:
5050
"""
51-
This proxy checks several urls to get the proxy availability. These are the judges.
52-
There are several in this module. However, they can be nonoperational. This function
53-
removes the one not operative.
51+
This proxy checks several urls to get the proxy availability. These are the judges.
52+
There are several in this module. However, they can be nonoperational. This function
53+
removes the one not operative.
5454
"""
5555
checked_judges = []
5656

@@ -62,70 +62,79 @@ def check_proxy_judges(self) -> None:
6262
self.proxy_judges = checked_judges
6363

6464
if len(checked_judges) == 0:
65-
print("ERROR: JUDGES ARE OUTDATED. CREATE A GIT BRANCH AND UPDATE SELF.PROXY_JUDGES")
65+
print(
66+
"ERROR: JUDGES ARE OUTDATED. CREATE A GIT BRANCH AND UPDATE SELF.PROXY_JUDGES"
67+
)
6668
exit()
6769
elif len(checked_judges) == 1:
68-
print('WARNING! THERE\'S ONLY 1 JUDGE!')
70+
print("WARNING! THERE'S ONLY 1 JUDGE!")
6971

7072
def get_device_ip(self, cache_timeout: Optional[int] = 3600) -> str:
7173
"""
72-
Gets the IP address by checking it via various services.
74+
Gets the IP address by checking it via various services.
7375
74-
Parameters:
75-
cache_timeout (Optional[int]): Cache timeout in seconds. Default is 3600 seconds (1 hour).
76+
Parameters:
77+
cache_timeout (Optional[int]): Cache timeout in seconds. Default is 3600 seconds (1 hour).
7678
77-
Returns:
78-
str: IP address or an empty string if it couldn't find anything.
79+
Returns:
80+
str: IP address or an empty string if it couldn't find anything.
7981
"""
80-
cache = FileCache('tmp/device-ip.json')
82+
cache = FileCache("tmp/device-ip.json")
8183
# Read cache and check for expiration
8284
cached_value = cache.read_cache()
8385
if cached_value is not None:
8486
return cached_value
8587

8688
ip_services = [
87-
'https://api64.ipify.org',
88-
'https://ipinfo.io/ip',
89-
'https://api.myip.com',
90-
'https://ip.42.pl/raw',
91-
'https://ifconfig.me/ip',
92-
'https://cloudflare.com/cdn-cgi/trace',
93-
'https://httpbin.org/ip',
94-
'https://api.ipify.org'
89+
"https://api64.ipify.org",
90+
"https://ipinfo.io/ip",
91+
"https://api.myip.com",
92+
"https://ip.42.pl/raw",
93+
"https://ifconfig.me/ip",
94+
"https://cloudflare.com/cdn-cgi/trace",
95+
"https://httpbin.org/ip",
96+
"https://api.ipify.org",
9597
]
9698
for url in ip_services:
9799
r = self.send_query(url=url)
98100
if r:
99101
break
100102

101103
if not r:
102-
return ''
104+
return ""
103105

104106
# parse IP using regex
105107
ip_address_match = re.search(
106108
r"(?!0)(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)",
107-
r['response'])
109+
r["response"],
110+
)
108111
if ip_address_match:
109112
result = ip_address_match.group(0)
110113
if result:
111114
# Write cache with a value and expiration time in seconds
112115
cache.write_cache(result, cache_timeout)
113116
return result
114117

115-
return r['response']
118+
return r["response"]
116119

117-
def send_query(self, proxy: Union[str, bool] = False, url: str = None, tls=1.3,
118-
user: str = None, password: str = None) -> Union[bool, dict]:
120+
def send_query(
121+
self,
122+
proxy: Union[str, bool] = False,
123+
url: str = None,
124+
tls=1.3,
125+
user: str = None,
126+
password: str = None,
127+
) -> Union[bool, dict]:
119128
"""
120-
Sends a query to a judge to get info from judge.
121-
Args:
122-
:param proxy: "IP:Port". Proxy to use in the connection
123-
:param url: Url judge to use
124-
:param tls
125-
:param user: Username for proxy
126-
:param password: Password for proxy
127-
Returns:
128-
False if response is not 200. Otherwise: 'timeout': timeout,'response': response}
129+
Sends a query to a judge to get info from judge.
130+
Args:
131+
:param proxy: "IP:Port". Proxy to use in the connection
132+
:param url: Url judge to use
133+
:param tls
134+
:param user: Username for proxy
135+
:param password: Password for proxy
136+
Returns:
137+
False if response is not 200. Otherwise: 'timeout': timeout,'response': response}
129138
"""
130139
response = BytesIO()
131140
c = pycurl.Curl()
@@ -144,7 +153,7 @@ def send_query(self, proxy: Union[str, bool] = False, url: str = None, tls=1.3,
144153

145154
if proxy:
146155
c.setopt(c.PROXY, proxy)
147-
if proxy.startswith('https'):
156+
if proxy.startswith("https"):
148157
# c.setopt(c.SSL_VERIFYHOST, 1)
149158
# c.setopt(pycurl.SSL_VERIFYHOST, 2)
150159
# c.setopt(c.SSL_VERIFYPEER, 1)
@@ -173,62 +182,69 @@ def send_query(self, proxy: Union[str, bool] = False, url: str = None, tls=1.3,
173182
timeout = round(c.getinfo(c.CONNECT_TIME) * 1000)
174183

175184
# Decode the response content
176-
response = response.getvalue().decode('iso-8859-1')
185+
response = response.getvalue().decode("iso-8859-1")
177186

178-
return {
179-
'timeout': timeout,
180-
'response': response
181-
}
187+
return {"timeout": timeout, "response": response}
182188

183189
def parse_anonymity(self, r: str) -> str:
184190
"""
185-
Obtain the anonymity of the proxy
186-
Args:
187-
:param, str. IP
188-
Return: Transparent, Anonymous, Elite. Empty for failed get anonymity
191+
Obtain the anonymity of the proxy
192+
Args:
193+
:param, str. IP
194+
Return: Transparent, Anonymous, Elite. Empty for failed get anonymity
189195
"""
190-
if self.ip == '':
191-
return ''
196+
if self.ip == "":
197+
return ""
192198

193199
if self.ip in r:
194200
# device ip is found in proxy judges response headers
195-
return 'Transparent'
201+
return "Transparent"
196202

197203
privacy_headers = [
198-
'VIA',
199-
'X-FORWARDED-FOR',
200-
'X-FORWARDED',
201-
'FORWARDED-FOR',
202-
'FORWARDED-FOR-IP',
203-
'FORWARDED',
204-
'CLIENT-IP',
205-
'PROXY-CONNECTION'
204+
"VIA",
205+
"X-FORWARDED-FOR",
206+
"X-FORWARDED",
207+
"FORWARDED-FOR",
208+
"FORWARDED-FOR-IP",
209+
"FORWARDED",
210+
"CLIENT-IP",
211+
"PROXY-CONNECTION",
206212
]
207213

208214
if any([header in r for header in privacy_headers]):
209215
# contains spesific headers
210-
return 'Anonymous'
216+
return "Anonymous"
211217

212218
# perfect
213-
return 'Elite'
219+
return "Elite"
214220

215221
def get_country(self, ip: str) -> list:
216222
"""
217-
Checks in https://ip2c.org the country from a given IP
218-
Args:
219-
:param ip, str. Including dots, but not port
220-
Return: [country, country shortname Alpha-2 code]
223+
Checks in https://ip2c.org the country from a given IP
224+
Args:
225+
:param ip, str. Including dots, but not port
226+
Return: [country, country shortname Alpha-2 code]
221227
"""
222-
r = self.send_query(url='https://ip2c.org/' + ip)
228+
r = self.send_query(url="https://ip2c.org/" + ip)
223229

224-
if r and r['response'][0] == '1':
225-
r = r['response'].split(';')
230+
if r and r["response"][0] == "1":
231+
r = r["response"].split(";")
226232
return [r[3], r[1]]
227233

228-
return ['-', '-']
229-
230-
def check_proxy(self, proxy: str, check_country: bool = True, check_address: bool = False, check_all_protocols: bool = False,
231-
protocol: Union[str, list] = None, retries: int = 1, tls: float = 1.3, user: str = None, password: str = None) -> Union[bool, dict]:
234+
return ["-", "-"]
235+
236+
def check_proxy(
237+
self,
238+
proxy: str,
239+
check_country: bool = True,
240+
check_address: bool = False,
241+
check_all_protocols: bool = False,
242+
protocol: Union[str, list] = None,
243+
retries: int = 1,
244+
tls: float = 1.3,
245+
user: str = None,
246+
password: str = None,
247+
) -> Union[bool, dict]:
232248
"""
233249
Checks if the proxy is working.
234250
Args:
@@ -253,7 +269,7 @@ def check_proxy(self, proxy: str, check_country: bool = True, check_address: boo
253269
timeout = 0
254270

255271
# Select protocols to check
256-
protocols_to_test = ['http', 'https', 'socks4', 'socks5']
272+
protocols_to_test = ["http", "https", "socks4", "socks5"]
257273

258274
if isinstance(protocol, list):
259275
temp = []
@@ -270,14 +286,19 @@ def check_proxy(self, proxy: str, check_country: bool = True, check_address: boo
270286
# Test the proxy for each protocol
271287
for retry in range(retries):
272288
for protocol in protocols_to_test:
273-
r = self.send_query(proxy=protocol + '://' + proxy, user=user, password=password, tls=tls)
289+
r = self.send_query(
290+
proxy=protocol + "://" + proxy,
291+
user=user,
292+
password=password,
293+
tls=tls,
294+
)
274295

275296
# Check if the request failed
276297
if not r:
277298
continue
278299

279300
protocols[protocol] = r
280-
timeout += r['timeout']
301+
timeout += r["timeout"]
281302

282303
if not check_all_protocols:
283304
break
@@ -290,11 +311,11 @@ def check_proxy(self, proxy: str, check_country: bool = True, check_address: boo
290311
if len(protocols) == 0:
291312
return False
292313

293-
r = protocols[random.choice(list(protocols.keys()))]['response']
314+
r = protocols[random.choice(list(protocols.keys()))]["response"]
294315

295316
# Get country
296317
if check_country:
297-
country = self.get_country(proxy.split(':')[0])
318+
country = self.get_country(proxy.split(":")[0])
298319

299320
# Check anonymity
300321
anonymity = self.parse_anonymity(r)
@@ -304,23 +325,23 @@ def check_proxy(self, proxy: str, check_country: bool = True, check_address: boo
304325

305326
# Check remote address
306327
if check_address:
307-
remote_regex = r'REMOTE_ADDR = (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
328+
remote_regex = r"REMOTE_ADDR = (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})"
308329
remote_addr = re.search(remote_regex, r)
309330
if remote_addr:
310331
remote_addr = remote_addr.group(1)
311332

312333
results = {
313-
'protocols': list(protocols.keys()),
314-
'anonymity': anonymity,
315-
'timeout': timeout
334+
"protocols": list(protocols.keys()),
335+
"anonymity": anonymity,
336+
"timeout": timeout,
316337
}
317338

318339
if check_country:
319-
results['country'] = country[0]
320-
results['country_code'] = country[1]
340+
results["country"] = country[0]
341+
results["country_code"] = country[1]
321342

322343
if check_address:
323-
results['remote_address'] = remote_addr
344+
results["remote_address"] = remote_addr
324345

325346
return results
326347

@@ -361,11 +382,11 @@ def write_cache(self, value: Any, expires_in: int) -> None:
361382
os.makedirs(os.path.dirname(self.file_path), exist_ok=True)
362383

363384
cache_data = {
364-
'value': value,
365-
'timestamp': time.time(),
366-
'expires_in': expires_in
385+
"value": value,
386+
"timestamp": time.time(),
387+
"expires_in": expires_in,
367388
}
368-
with open(self.file_path, 'w') as cache_file:
389+
with open(self.file_path, "w") as cache_file:
369390
json.dump(cache_data, cache_file)
370391

371392
def read_cache(self) -> Optional[Any]:
@@ -379,16 +400,16 @@ def read_cache(self) -> Optional[Any]:
379400
return None
380401

381402
try:
382-
with open(self.file_path, 'r') as cache_file:
403+
with open(self.file_path, "r") as cache_file:
383404
cache_data = json.load(cache_file)
384405

385406
current_time = time.time()
386-
cache_time = cache_data['timestamp']
387-
expires_in = cache_data['expires_in']
407+
cache_time = cache_data["timestamp"]
408+
expires_in = cache_data["expires_in"]
388409

389410
if current_time - cache_time > expires_in:
390411
return None
391412

392-
return cache_data['value']
413+
return cache_data["value"]
393414
except Exception:
394415
return None

0 commit comments

Comments
 (0)