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

64 lines
1.7 KiB
Python
Raw Normal View History

2024-01-21 17:45:01 +00:00
from __future__ import annotations
import itertools
from collections import Counter
2024-07-09 03:08:30 +03:00
from typing import TYPE_CHECKING
2024-01-21 17:45:01 +00:00
2024-11-22 14:32:29 +03:00
from proxy_scraper_checker import sort
2024-06-03 14:08:42 +05:00
if TYPE_CHECKING:
2024-10-17 14:18:27 +03:00
from collections.abc import Iterable, Iterator
2024-07-09 03:08:30 +03:00
2024-06-03 14:08:42 +05:00
from aiohttp_socks import ProxyType
2024-11-22 14:32:29 +03:00
from proxy_scraper_checker.proxy import Proxy
2024-01-21 17:45:01 +00:00
class ProxyStorage:
__slots__ = ("_proxies", "enabled_protocols")
2024-01-21 23:37:46 +03:00
def __init__(self, *, protocols: Iterable[ProxyType]) -> None:
self.enabled_protocols = set(protocols)
2024-06-03 14:08:42 +05:00
self._proxies: set[Proxy] = set()
2024-01-21 17:45:01 +00:00
def add(self, proxy: Proxy, /) -> None:
self.enabled_protocols.add(proxy.protocol)
self._proxies.add(proxy)
def remove(self, proxy: Proxy, /) -> None:
self._proxies.remove(proxy)
2024-06-03 14:08:42 +05:00
def get_grouped(self) -> dict[ProxyType, tuple[Proxy, ...]]:
2024-01-21 17:45:01 +00:00
key = sort.protocol_sort_key
2024-02-04 16:58:45 +03:00
return {
**{
proto: ()
for proto in sort.PROTOCOL_ORDER
if proto in self.enabled_protocols
},
**{
proto: tuple(v)
for (_, proto), v in itertools.groupby(
sorted(self, key=key), key=key
)
},
2024-01-21 17:45:01 +00:00
}
2024-06-03 14:08:42 +05:00
def get_count(self) -> dict[ProxyType, int]:
2024-02-04 16:58:45 +03:00
return {
**{
proto: 0
for proto in sort.PROTOCOL_ORDER
if proto in self.enabled_protocols
},
**Counter(proxy.protocol for proxy in self),
}
2024-01-21 17:45:01 +00:00
2024-09-18 18:23:01 +03:00
def remove_unchecked(self) -> None:
for p in self._proxies.copy():
if not p.is_checked:
self._proxies.remove(p)
2024-01-21 17:45:01 +00:00
def __iter__(self) -> Iterator[Proxy]:
return iter(self._proxies)