bird-filter/aspa/data.py

43 lines
1,016 B
Python
Raw Permalink Normal View History

2024-10-29 01:25:05 -04:00
import json
import re
from dataclasses import dataclass
2024-11-01 18:50:19 -04:00
from typing import Optional, Union
2024-10-29 01:25:05 -04:00
reasn = re.compile(r"^AS(\d+)$")
2024-11-01 18:50:19 -04:00
def parse_asn(value: Union[str, int]) -> Optional[int]:
if isinstance(value, int):
return value
match = reasn.match(value)
2024-10-29 01:25:05 -04:00
if match:
return int(match.group(1))
@dataclass
class ASPA:
customer: int
providers: list[int]
2024-11-01 18:50:19 -04:00
ta: Optional[str]
2024-10-29 01:25:05 -04:00
@classmethod
def from_dict(cls, d):
try:
2024-11-01 18:50:19 -04:00
if 'customer' in d:
customer = parse_asn(d['customer'])
elif 'customer_asid' in d:
customer = parse_asn(d['customer_asid'])
else:
return None
2024-10-29 01:25:05 -04:00
providers = list(map(parse_asn, d['providers']))
2024-11-01 18:50:19 -04:00
return cls(customer, providers, d.get('ta'))
2024-10-29 01:25:05 -04:00
except (KeyError, TypeError):
return None
def parse_json(data: str) -> list[ASPA]:
data = json.loads(data)
return list(filter(None, map(ASPA.from_dict, data.get('aspas', []))))