Files
proxy-scraper-checker/proxy_scraper_checker/proxy.py
T

71 lines
2.3 KiB
Python
Raw Normal View History

2023-01-02 00:09:55 +03:00
from __future__ import annotations
import asyncio
from time import perf_counter
2023-01-07 11:57:57 +03:00
from aiohttp import ClientSession, ClientTimeout
2023-01-04 20:24:44 +03:00
from aiohttp.abc import AbstractCookieJar
2023-01-04 17:49:45 +03:00
from aiohttp_socks import ProxyConnector, ProxyType
2023-01-02 00:09:55 +03:00
2023-01-15 13:05:16 +03:00
from .constants import USER_AGENT
2023-01-02 00:09:55 +03:00
class Proxy:
2023-01-04 17:49:45 +03:00
__slots__ = ("geolocation", "host", "is_anonymous", "port", "timeout")
def __init__(self, *, host: str, port: int) -> None:
self.host = host
self.port = port
2023-01-02 00:09:55 +03:00
2023-01-15 13:05:16 +03:00
@property
def default_check_website(self) -> str:
return "http://ip-api.com/json/?fields=8217"
2023-01-02 00:09:55 +03:00
async def check(
2023-01-04 20:24:44 +03:00
self,
*,
2023-01-15 13:05:16 +03:00
website: str,
2023-01-04 20:24:44 +03:00
sem: asyncio.Semaphore,
cookie_jar: AbstractCookieJar,
2023-01-15 00:22:17 +03:00
proto: ProxyType,
2023-01-07 11:57:57 +03:00
timeout: ClientTimeout,
2023-01-02 00:09:55 +03:00
) -> None:
2023-01-15 13:05:16 +03:00
check_website = (
self.default_check_website if website == "default" else website
)
2023-01-02 00:09:55 +03:00
async with sem:
start = perf_counter()
2023-01-15 13:05:16 +03:00
async with self.get_connector(proto) as connector, ClientSession(
connector=connector,
cookie_jar=cookie_jar,
timeout=timeout,
headers={"User-Agent": USER_AGENT},
) as session, session.get(
check_website, raise_for_status=True
) as response:
if website == "default":
await response.read()
2023-01-02 00:09:55 +03:00
self.timeout = perf_counter() - start
2023-01-15 13:05:16 +03:00
if website == "default":
data = await response.json()
self.is_anonymous = self.host != data["query"]
self.geolocation = "|{}|{}|{}".format(
data["country"], data["regionName"], data["city"]
)
2023-01-02 00:09:55 +03:00
2023-01-15 00:22:17 +03:00
def get_connector(self, proto: ProxyType) -> ProxyConnector:
return ProxyConnector(proxy_type=proto, host=self.host, port=self.port)
2023-01-04 17:49:45 +03:00
def as_str(self, include_geolocation: bool) -> str:
if include_geolocation:
return f"{self.host}:{self.port}{self.geolocation}"
return f"{self.host}:{self.port}"
2023-01-02 00:09:55 +03:00
def __eq__(self, other: object) -> bool:
if not isinstance(other, Proxy):
return NotImplemented
2023-01-04 17:49:45 +03:00
return self.host == other.host and self.port == other.port
2023-01-02 00:09:55 +03:00
def __hash__(self) -> int:
2023-01-04 17:49:45 +03:00
return hash((self.host, self.port))