Compare commits

..

6 Commits

Author SHA1 Message Date
5e3805b567 fix StateHashFile encoding
All checks were successful
Docker Image CI / test (push) Successful in 44s
Docker Image CI / push (push) Successful in 53s
2024-03-03 14:32:12 +03:00
5861836852 fix docs for (sources/filters).files
All checks were successful
Docker Image CI / test (push) Successful in 30s
Docker Image CI / push (push) Successful in 39s
2024-03-02 18:33:09 +03:00
30d0270901 refactor files filters/outputs
All checks were successful
Docker Image CI / test (push) Successful in 31s
Docker Image CI / push (push) Successful in 38s
2024-03-02 18:18:28 +03:00
4d13416222 separate core from cli #6
All checks were successful
Docker Image CI / test (push) Successful in 31s
Docker Image CI / push (push) Successful in 39s
2024-03-02 17:20:44 +03:00
2bf42162ef refactor plugins.py
All checks were successful
Docker Image CI / test (push) Successful in 37s
Docker Image CI / push (push) Successful in 39s
2024-03-02 16:59:23 +03:00
440c33b8e5 upd README
All checks were successful
Docker Image CI / test (push) Successful in 36s
Docker Image CI / push (push) Successful in 40s
2024-02-29 15:56:53 +03:00
6 changed files with 409 additions and 360 deletions

View File

@@ -11,11 +11,10 @@ python -m pddnsc.cli
либо в [docker](https://www.docker.com)/[podman](https://podman.io) (для запуска по расписанию в `cron`):
~~~bash
docker build -t my/pddnsc .
docker run -v .state:/app/state:rw \
-v .settings:/app/settings:ro \
-e SCHEDULE=@hourly \
my/pddnsc
gitea.b4tman.ru/b4tman/pddnsc
~~~
## Конфигурация
@@ -60,7 +59,7 @@ docker run -v .state:/app/state:rw \
- `filters` - фильтры, если хоть один вернет ложь то программа ничего никуда не запишет и не отправит, например проверка, что ip адрес не изменился
- `outputs` - модули вывода, например вывод в консоль, запись в файл или создание dns записей на сервере
Все модули источников/фильтров/вывода работают конкурентно через `asyncio`.
Все модули источников/фильтров/вывода работают конкурентно через [asyncio](https://docs.python.org/3/library/asyncio.html#module-asyncio) и [httpx](https://www.python-httpx.org).
### Подробная документация

View File

@@ -1,297 +1,10 @@
""" модуль запуска """
import httpx
import asyncio
import toml
from .base import BaseFilterProvider, BaseSourceProvider, BaseOutputProvider, IPAddreses
from .plugins import use_plugins
from typing import Optional, NamedTuple
import asyncio
class NeededAddrs(NamedTuple):
ipv4: bool
ipv6: bool
@classmethod
def from_config(cls, config: dict) -> "NeededAddrs":
need_ipv4 = config.get("require_ipv4", False)
need_ipv6 = config.get("require_ipv6", False)
if "require_ipv4" not in config and "require_ipv6" not in config:
need_ipv4 = need_ipv6 = True
return cls(need_ipv4, need_ipv6)
def is_valid_addreses(addrs: IPAddreses, config: dict) -> bool:
"""Проверка валидности IP адресов
Args:
addrs (IPAddreses): IP адреса - результат одного из источников
config (dict): общая конфигурация
Returns:
bool: валиден или нет
"""
result = addrs.ipv4 or addrs.ipv6
if config.get("require_ipv4"):
result = result and addrs.ipv4
if config.get("require_ipv6"):
result = result and addrs.ipv6
return bool(result)
def is_ipv4_ok(ipv4: str, config: dict) -> bool:
"""Проверка IPv4 адреса, подходит или нет
Args:
ipv4 (str): IPv4 адрес
config (dict): общая конфигурация
Returns:
bool: подходит или нет
"""
return bool(ipv4) if NeededAddrs.from_config(config).ipv4 else True
def is_ipv6_ok(ipv6: str, config: dict) -> bool:
"""Проверка IPv6 адреса, подходит или нет
Args:
ipv6 (str): IPv6 адрес
config (dict): общая конфигурация
Returns:
bool: подходит или нет
"""
return bool(ipv6) if NeededAddrs.from_config(config).ipv6 else True
async def get_ip_addresses(config: dict) -> Optional[IPAddreses]:
"""Получение всех IP адресов из всех источников
Args:
config (dict): общая конфигурация
Returns:
Optional[IPAddreses]: результат получения, либо None
"""
unit_mode = config.get("unit_mode", False)
if unit_mode:
result = await get_ip_addresses_unit(config)
else:
result = await get_ip_addresses_any(config)
return result
async def get_ip_addresses_any(config: dict) -> Optional[IPAddreses]:
"""Получение всех IP адресов из всех источников (режим any)
Получает разные адреса от любых источников
Args:
config (dict): общая конфигурация
Returns:
Optional[IPAddreses]: результат получения, либо None
"""
need = NeededAddrs.from_config(config)
providers = BaseSourceProvider.registred.values()
ip_addresses, is_done = None, False
last_src, last_ipv4, last_ipv6 = "", "", ""
ok_ipv4, ok_ipv6 = False, False
drop = []
pending = []
if need.ipv4:
pending += [
asyncio.create_task(p.fetch_v4(), name=f"{p.name}.v4") for p in providers
]
if need.ipv6:
pending += [
asyncio.create_task(p.fetch_v6(), name=f"{p.name}.v6") for p in providers
]
while not is_done and pending:
done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
for x in done:
ip_addr = x.result()
if x.get_name().endswith(".v6"):
last_ipv6 = last_ipv6 if ok_ipv6 else ip_addr
else:
last_ipv4 = last_ipv4 if ok_ipv4 else ip_addr
if config.get("debug"):
print("debug:", "get", x.get_name(), ip_addr)
last_src = x.get_name().rsplit(".", maxsplit=1)[0]
ok_ipv4 = is_ipv4_ok(last_ipv4, config)
ok_ipv6 = is_ipv6_ok(last_ipv6, config)
pending_v4 = [*filter(lambda i: i.get_name().endswith(".v4"), pending)]
pending_v6 = [*filter(lambda i: i.get_name().endswith(".v6"), pending)]
if ok_ipv4 and pending_v4:
drop += pending_v4
pending = pending_v6
for i in pending_v4:
i.cancel()
pending_v4 = []
if ok_ipv6 and pending_v6:
drop += pending_v6
pending = pending_v4
for i in pending_v6:
i.cancel()
pending_v6 = []
if not (ok_ipv4 and ok_ipv6):
continue
ip_addresses = IPAddreses(last_src, last_ipv4, last_ipv6)
if is_valid_addreses(ip_addresses, config):
is_done = True
break
ip_addresses = None
if not (ok_ipv4 and ok_ipv6):
ip_addresses = IPAddreses(last_src, last_ipv4, last_ipv6)
drop = drop + list(pending)
if drop:
gather = asyncio.gather(*drop)
gather.cancel()
try:
await gather
except asyncio.CancelledError:
pass
return ip_addresses
async def get_ip_addresses_unit(config: dict) -> Optional[IPAddreses]:
"""Получение всех IP адресов из всех источников (режим unit)
Получает адреса только от одного источника
Args:
config (dict): общая конфигурация
Returns:
Optional[IPAddreses]: результат получения, либо None
"""
providers = BaseSourceProvider.registred.values()
ip_addresses = None
is_done = False
pending = [asyncio.create_task(p.fetch_all(), name=p.name) for p in providers]
while not is_done and pending:
done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
for x in done:
ip_addresses = x.result()
if is_valid_addreses(ip_addresses, config):
is_done = True
break
ip_addresses = None
if pending:
gather = asyncio.gather(*pending)
gather.cancel()
try:
await gather
except asyncio.CancelledError:
pass
return ip_addresses
async def check_ip_addresses(ip_addresses: IPAddreses) -> bool:
"""Проверка результата получения IP адресов с помощью фильтров
Args:
ip_addresses (IPAddreses): IP адреса
Returns:
bool: корректны ли адреса (изменились ли они),
надо ли продолжать обработку и отправлять их на сервер
"""
providers = BaseFilterProvider.registred.values()
result = True
failed = ""
pending = [
asyncio.create_task(p.check(*ip_addresses), name=p.name) for p in providers
]
while result and pending:
done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
for x in done:
result = x.result()
if not result:
failed = x.get_name()
if pending:
gather = asyncio.gather(*pending)
gather.cancel()
try:
await gather
except asyncio.CancelledError:
pass
if not result:
print("failed filter:", failed)
return result
async def send_ip_addreses(ip_addresses: IPAddreses):
"""Отправка адресов на все плагины вывода
Args:
ip_addresses (IPAddreses): IP адреса
"""
providers = BaseOutputProvider.registred.values()
await asyncio.gather(
*(
asyncio.create_task(p.set_addrs(*ip_addresses), name=p.name)
for p in providers
)
)
def print_debug_info(config: dict):
"""Вывод всех зарегистрированных плагинов и другой отладочной информации"""
debug = config.get("debug", False)
if debug:
print("DEBUG info:")
print(
f"source classes: {[*BaseSourceProvider._childs]}, {[*map(str, BaseSourceProvider._childs.values())]}"
)
print(
f"filter classes: {[*BaseFilterProvider._childs]}, {[*map(str, BaseFilterProvider._childs.values())]}"
)
print(
f"output classes: {[*BaseOutputProvider._childs]}, {[*map(str, BaseOutputProvider._childs.values())]}"
)
print(
f"source providers: {[*BaseSourceProvider.registred]}, {[*map(str, BaseSourceProvider.registred.values())]}"
)
print(
f"filter providers: {[*BaseFilterProvider.registred]}, {[*map(str, BaseFilterProvider.registred.values())]}"
)
print(
f"output providers: {[*BaseOutputProvider.registred]}, {[*map(str, BaseOutputProvider.registred.values())]}"
)
async def app(
config: dict, ipv4t: httpx.AsyncHTTPTransport, ipv6t: httpx.AsyncHTTPTransport
):
"""Запуск приложения
Args:
config (dict): общая конфигурация
ipv4t (httpx.AsyncHTTPTransport): транспорт IPv4
ipv6t (httpx.AsyncHTTPTransport): транспорт IPv6
"""
use_plugins(config, ipv4t, ipv6t)
print_debug_info(config)
ip_addreses = await get_ip_addresses(config)
if ip_addreses is None:
print("no IP addresses")
return
if not await check_ip_addresses(ip_addreses):
print("stop by filters")
return
await send_ip_addreses(ip_addreses)
print("done")
from pddnsc.core import app
async def main():

285
pddnsc/core.py Normal file
View File

@@ -0,0 +1,285 @@
import httpx
import asyncio
from .base import BaseFilterProvider, BaseSourceProvider, BaseOutputProvider, IPAddreses
from .plugins import use_plugins
from typing import Optional, NamedTuple
class NeededAddrs(NamedTuple):
ipv4: bool
ipv6: bool
@classmethod
def from_config(cls, config: dict) -> "NeededAddrs":
need_ipv4 = config.get("require_ipv4", False)
need_ipv6 = config.get("require_ipv6", False)
if "require_ipv4" not in config and "require_ipv6" not in config:
need_ipv4 = need_ipv6 = True
return cls(need_ipv4, need_ipv6)
def is_valid_addreses(addrs: IPAddreses, config: dict) -> bool:
"""Проверка валидности IP адресов
Args:
addrs (IPAddreses): IP адреса - результат одного из источников
config (dict): общая конфигурация
Returns:
bool: валиден или нет
"""
result = addrs.ipv4 or addrs.ipv6
if config.get("require_ipv4"):
result = result and addrs.ipv4
if config.get("require_ipv6"):
result = result and addrs.ipv6
return bool(result)
def is_ipv4_ok(ipv4: str, config: dict) -> bool:
"""Проверка IPv4 адреса, подходит или нет
Args:
ipv4 (str): IPv4 адрес
config (dict): общая конфигурация
Returns:
bool: подходит или нет
"""
return bool(ipv4) if NeededAddrs.from_config(config).ipv4 else True
def is_ipv6_ok(ipv6: str, config: dict) -> bool:
"""Проверка IPv6 адреса, подходит или нет
Args:
ipv6 (str): IPv6 адрес
config (dict): общая конфигурация
Returns:
bool: подходит или нет
"""
return bool(ipv6) if NeededAddrs.from_config(config).ipv6 else True
async def get_ip_addresses(config: dict) -> Optional[IPAddreses]:
"""Получение всех IP адресов из всех источников
Args:
config (dict): общая конфигурация
Returns:
Optional[IPAddreses]: результат получения, либо None
"""
unit_mode = config.get("unit_mode", False)
if unit_mode:
result = await get_ip_addresses_unit(config)
else:
result = await get_ip_addresses_any(config)
return result
async def get_ip_addresses_any(config: dict) -> Optional[IPAddreses]:
"""Получение всех IP адресов из всех источников (режим any)
Получает разные адреса от любых источников
Args:
config (dict): общая конфигурация
Returns:
Optional[IPAddreses]: результат получения, либо None
"""
need = NeededAddrs.from_config(config)
providers = BaseSourceProvider.registred.values()
ip_addresses, is_done = None, False
last_src, last_ipv4, last_ipv6 = "", "", ""
ok_ipv4, ok_ipv6 = False, False
drop = []
pending = []
if need.ipv4:
pending += [
asyncio.create_task(p.fetch_v4(), name=f"{p.name}.v4") for p in providers
]
if need.ipv6:
pending += [
asyncio.create_task(p.fetch_v6(), name=f"{p.name}.v6") for p in providers
]
while not is_done and pending:
done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
for x in done:
ip_addr = x.result()
if x.get_name().endswith(".v6"):
last_ipv6 = last_ipv6 if ok_ipv6 else ip_addr
else:
last_ipv4 = last_ipv4 if ok_ipv4 else ip_addr
if config.get("debug"):
print("debug:", "get", x.get_name(), ip_addr)
last_src = x.get_name().rsplit(".", maxsplit=1)[0]
ok_ipv4 = is_ipv4_ok(last_ipv4, config)
ok_ipv6 = is_ipv6_ok(last_ipv6, config)
pending_v4 = [*filter(lambda i: i.get_name().endswith(".v4"), pending)]
pending_v6 = [*filter(lambda i: i.get_name().endswith(".v6"), pending)]
if ok_ipv4 and pending_v4:
drop += pending_v4
pending = pending_v6
for i in pending_v4:
i.cancel()
pending_v4 = []
if ok_ipv6 and pending_v6:
drop += pending_v6
pending = pending_v4
for i in pending_v6:
i.cancel()
pending_v6 = []
if not (ok_ipv4 and ok_ipv6):
continue
ip_addresses = IPAddreses(last_src, last_ipv4, last_ipv6)
if is_valid_addreses(ip_addresses, config):
is_done = True
break
ip_addresses = None
if not (ok_ipv4 and ok_ipv6):
ip_addresses = IPAddreses(last_src, last_ipv4, last_ipv6)
drop = drop + list(pending)
if drop:
gather = asyncio.gather(*drop)
gather.cancel()
try:
await gather
except asyncio.CancelledError:
pass
return ip_addresses
async def get_ip_addresses_unit(config: dict) -> Optional[IPAddreses]:
"""Получение всех IP адресов из всех источников (режим unit)
Получает адреса только от одного источника
Args:
config (dict): общая конфигурация
Returns:
Optional[IPAddreses]: результат получения, либо None
"""
providers = BaseSourceProvider.registred.values()
ip_addresses = None
is_done = False
pending = [asyncio.create_task(p.fetch_all(), name=p.name) for p in providers]
while not is_done and pending:
done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
for x in done:
ip_addresses = x.result()
if is_valid_addreses(ip_addresses, config):
is_done = True
break
ip_addresses = None
if pending:
gather = asyncio.gather(*pending)
gather.cancel()
try:
await gather
except asyncio.CancelledError:
pass
return ip_addresses
async def check_ip_addresses(ip_addresses: IPAddreses) -> bool:
"""Проверка результата получения IP адресов с помощью фильтров
Args:
ip_addresses (IPAddreses): IP адреса
Returns:
bool: корректны ли адреса (изменились ли они),
надо ли продолжать обработку и отправлять их на сервер
"""
providers = BaseFilterProvider.registred.values()
result = True
failed = ""
pending = [
asyncio.create_task(p.check(*ip_addresses), name=p.name) for p in providers
]
while result and pending:
done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
for x in done:
result = x.result()
if not result:
failed = x.get_name()
if pending:
gather = asyncio.gather(*pending)
gather.cancel()
try:
await gather
except asyncio.CancelledError:
pass
if not result:
print("failed filter:", failed)
return result
async def send_ip_addreses(ip_addresses: IPAddreses):
"""Отправка адресов на все плагины вывода
Args:
ip_addresses (IPAddreses): IP адреса
"""
providers = BaseOutputProvider.registred.values()
await asyncio.gather(
*(
asyncio.create_task(p.set_addrs(*ip_addresses), name=p.name)
for p in providers
)
)
def print_debug_info(config: dict):
"""Вывод всех зарегистрированных плагинов и другой отладочной информации"""
def format_registred(name, base):
result = f"{name}:\n"
result += f" classes: {[*base._childs]}\n"
result += f" .values: {[*map(str, base._childs.values())]}\n"
result += f" providers: {[*base.registred]}\n"
result += f" .values: {[*map(str, base.registred.values())]}\n"
return result
if config.get("debug", False):
print("DEBUG ->")
bases = BaseSourceProvider, BaseFilterProvider, BaseOutputProvider
for info in map(format_registred, "sources filters outputs".split(), bases):
print(info)
print("DEBUG <-")
async def app(
config: dict, ipv4t: httpx.AsyncHTTPTransport, ipv6t: httpx.AsyncHTTPTransport
):
"""Запуск приложения
Args:
config (dict): общая конфигурация
ipv4t (httpx.AsyncHTTPTransport): транспорт IPv4
ipv6t (httpx.AsyncHTTPTransport): транспорт IPv6
"""
use_plugins(config, ipv4t, ipv6t)
print_debug_info(config)
ip_addreses = await get_ip_addresses(config)
if ip_addreses is None:
print("no IP addresses")
return
if not await check_ip_addresses(ip_addreses):
print("stop by filters")
return
await send_ip_addreses(ip_addreses)
print("done")

View File

@@ -1,4 +1,3 @@
import asyncio
import hashlib
import json
import aiofiles
@@ -7,63 +6,79 @@ from os.path import isfile
from pddnsc.base import BaseFilterProvider
class StateHashFilter(BaseFilterProvider):
"""Проверка на то что хотябы один IP адрес изменился по хешу сохраненному в файле
class GenericTextFileFilter(BaseFilterProvider):
"""Проверка на то что хотябы один IP адрес изменился по сравнению с текстом в файле
Конфигурация:
- filepath: имя файла
- encoding: кодировка, по умолчанию "utf-8"
- mode: режим открытия, по умолчанию "r"
- check_ipv4: проверять ли IPv4, по умолчанию нет если check_ipv6 есть в конфиге иначе да
- check_ipv6: проверять ли IPv6, по умолчанию нет если check_ipv4 есть в конфиге иначе да
"""
async def check_imp(self, source_provider: str, addr_v4: str, addr_v6: str) -> bool:
if not isfile(self.config["filepath"]):
return True
def post_init(self):
super().post_init()
self.filepath = self.config["filepath"]
self.encoding = self.config.get("encoding", "utf-8")
self.mode = self.config.get("mode", "r")
self.check_ipv4 = self.config.get("check_ipv4", False)
self.check_ipv6 = self.config.get("check_ipv6", False)
if "check_ipv4" not in self.config and "check_ipv4" not in self.config:
self.check_ipv4 = self.check_ipv6 = True
self.content = ""
new_state_str = (addr_v4 or "") + (addr_v6 or "")
new_sha = hashlib.sha256(new_state_str.encode(encoding="utf-8"))
async def read(self) -> str:
async with aiofiles.open(
self.config["filepath"], mode="r", encoding="utf-8"
self.filepath, mode=self.mode, encoding=self.encoding
) as f:
old_state_hash = await f.read()
return old_state_hash != new_sha.hexdigest()
class StateFileFilter(BaseFilterProvider):
"""Проверка на то что хотябы один IP адрес изменился по сравнению с данными в json файле
Конфигурация:
- filepath: имя файла
- check_ipv4: проверка ipv4 адреса
- check_ipv6: проверка ipv6 адреса
если нет ни одного параметра то проверка выполняется для всех адресов
"""
self.content = await f.read()
async def check_imp(self, source_provider: str, addr_v4: str, addr_v6: str) -> bool:
if not isfile(self.config["filepath"]):
lst = []
if self.check_ipv4:
lst.append(addr_v4)
if self.check_ipv4:
lst.append(addr_v6)
new_content = "\n".join(lst)
return new_content != self.content
async def check(self, source_provider: str, addr_v4: str, addr_v6: str) -> bool:
if not isfile(self.filepath):
return True
await self.read()
return await self.check_imp(source_provider, addr_v4, addr_v6)
new_state = {
"ipv4": addr_v4,
"ipv6": addr_v6,
}
async with aiofiles.open(
self.config["filepath"], mode="r", encoding="utf-8"
) as f:
old_state = json.loads(await f.read())
class StateHashFilter(GenericTextFileFilter):
"""Проверка на то что хотябы один IP адрес изменился по хешу сохраненному в файле"""
async def check_imp(self, source_provider: str, addr_v4: str, addr_v6: str) -> bool:
new_state_str = (self.check_ipv4 and addr_v4 or "") + (
self.check_ipv6 and addr_v6 or ""
)
new_sha = hashlib.sha256(new_state_str.encode(encoding=self.encoding))
return self.content != new_sha.hexdigest()
class StateFileFilter(GenericTextFileFilter):
"""Проверка на то что хотябы один IP адрес изменился по сравнению с данными в json файле"""
async def check_imp(self, source_provider: str, addr_v4: str, addr_v6: str) -> bool:
new_state = {}
if self.check_ipv4:
new_state["ipv4"] = addr_v4 or ""
if self.check_ipv6:
new_state["ipv6"] = addr_v6 or ""
old_state = json.loads(self.content)
result = True
if "check_ipv4" not in self.config and "check_ipv4" not in self.config:
return new_state != old_state
if self.config.get("check_ipv4", False):
if self.check_ipv4:
result = result and new_state["ipv4"] != old_state["ipv4"]
if self.config.get("check_ipv6", False):
if self.check_ipv6:
result = result and new_state["ipv6"] != old_state["ipv6"]
return result

View File

@@ -5,38 +5,70 @@ import hashlib
from pddnsc.base import BaseOutputProvider
class StateFile(BaseOutputProvider):
"""Схранение всех IP адресов в json файл
class GenericTextFile(BaseOutputProvider):
"""Сохранение IP адресов в текстовый файл
Конфигурация:
- filepath: имя файла
- encoding: кодировка, по умолчанию "utf-8"
- mode: режим открытия, по умолчанию "w"
- save_ipv4: сохранять ли IPv4, по умолчанию нет если save_ipv6 есть в конфиге иначе да
- save_ipv6: сохранять ли IPv6, по умолчанию нет если save_ipv4 есть в конфиге иначе да
"""
async def set_addrs_imp(self, source_provider: str, addr_v4: str, addr_v6: str):
state = {
"ipv4": addr_v4 or "",
"ipv6": addr_v6 or "",
}
state_str = json.dumps(state)
def post_init(self):
super().post_init()
self.filepath = self.config["filepath"]
self.encoding = self.config.get("encoding", "utf-8")
self.mode = self.config.get("mode", "w")
self.save_ipv4 = self.config.get("save_ipv4", False)
self.save_ipv6 = self.config.get("save_ipv6", False)
if "save_ipv4" not in self.config and "save_ipv4" not in self.config:
self.save_ipv4 = self.save_ipv6 = True
self.content = ""
async def read(self):
async with aiofiles.open(self.filepath, mode="r", encoding=self.encoding) as f:
self.content = await f.read()
def set_content(self, ipv4: str, ipv6: str):
lst = []
if self.save_ipv4:
lst.append(ipv4)
if self.save_ipv6:
lst.append(ipv6)
self.content = "\n".join(lst)
async def write(self):
async with aiofiles.open(
self.config["filepath"], mode="w", encoding="utf-8"
self.filepath, mode=self.mode, encoding=self.encoding
) as f:
await f.write(state_str)
class StateHashFile(BaseOutputProvider):
"""Сохранение хеша от всех IP адресов в файл
Конфигурация:
- filepath: имя файла
"""
await f.write(self.content)
async def set_addrs_imp(self, source_provider: str, addr_v4: str, addr_v6: str):
state_str = (addr_v4 or "") + (addr_v6 or "")
sha = hashlib.sha256(state_str.encode(encoding="utf-8"))
async with aiofiles.open(
self.config["filepath"], mode="w", encoding="utf-8"
) as f:
await f.write(sha.hexdigest())
await self.set_content(addr_v4, addr_v6)
await self.write()
class StateFile(GenericTextFile):
"""Сохранение всех IP адресов в json файл"""
async def set_content(self, addr_v4: str, addr_v6: str):
state = {}
if self.save_ipv4:
state["ipv4"] = addr_v4 or ""
if self.save_ipv6:
state["ipv6"] = addr_v6 or ""
self.content = json.dumps(state)
class StateHashFile(GenericTextFile):
"""Сохранение хеша от всех IP адресов в файл"""
async def set_content(self, addr_v4: str, addr_v6: str):
state_str = (self.save_ipv4 and addr_v4 or "") + (
self.save_ipv6 and addr_v6 or ""
)
sha = hashlib.sha256(state_str.encode(encoding=self.encoding))
self.content = sha.hexdigest()

View File

@@ -3,23 +3,28 @@
from httpx import AsyncHTTPTransport
from .base import BaseSourceProvider, BaseFilterProvider, BaseOutputProvider
from . import sources
from . import outputs
from . import filters
from . import outputs
def unused():
"""Чтобы убрать предупреждение о неиспользуемых импортах"""
return sources, filters, outputs
def use_plugins(config: dict, ipv4t: AsyncHTTPTransport, ipv6t: AsyncHTTPTransport):
"""Регистрация всех плагинов указаных в конфигурации"""
for source_name in config["sources"]:
for source_name in config.get("sources", []):
BaseSourceProvider.register_provider(
source_name, config["sources"][source_name], ipv4t, ipv6t
)
for filter_name in config["filters"]:
for filter_name in config.get("filters", []):
BaseFilterProvider.register_provider(
filter_name, config["filters"][filter_name], ipv4t, ipv6t
)
for output_name in config["outputs"]:
for output_name in config.get("outputs", []):
BaseOutputProvider.register_provider(
output_name, config["outputs"][output_name], ipv4t, ipv6t
)