domeneshop-updater/main.py

60 lines
2.0 KiB
Python

from domeneshop import Client
import os, httpx, pprint, toml
def get_pub_ip() -> str:
for endpoint, getter in {
"http://myip.tf": lambda resp: resp.text,
"https://ipinfo.io/json": lambda resp: resp.json()["ip"],
"https://api.ipify.org": lambda resp: resp.text,
"http://ip.42.pl/raw": lambda resp: resp.text,
}.items():
resp = httpx.get(endpoint)
if not resp.is_success: continue
try:
return resp.json()["ip"]
except:
pass
else:
raise Exception("Could not find external IP")
# https://www.domeneshop.no/admin?view=api
with open("/var/lib/secrets/domeneshop.toml") as f:
c = toml.load(f)
DOMENESHOP_TOKEN = os.environ.get("DOMENESHOP_TOKEN", c["secrets"]["DOMENESHOP_TOKEN"])
DOMENESHOP_SECRET = os.environ.get("DOMENESHOP_SECRET", c["secrets"]["DOMENESHOP_SECRET"])
IP_ADDRESS = get_pub_ip() # TODO: both ipv4 and ipv6
DOMAINS = {
"pbsds.net": {
#"olavtr": ["A"],
"spismeg": ["A"],
},
}
client = Client(DOMENESHOP_TOKEN, DOMENESHOP_SECRET)
for domain in client.get_domains():
if domain["domain"] not in DOMAINS:
continue
RECORDS = DOMAINS[domain["domain"]]
for record in client.get_records(domain["id"]):
if record["host"] in RECORDS \
and record["type"] in RECORDS[record["host"]]:
print("Found: ", end="")
pprint.pprint(record)
if record["data"] != IP_ADDRESS:
record["data"] = IP_ADDRESS
print("Push: ", end="")
pprint.pprint(record)
client.modify_record(domain_id=domain["id"], record_id=record.pop("id"), record=record)
else:
print("Nothing done")
RECORDS[record["host"]].remove(record["type"])
for k, v in list(RECORDS.items()):
if not v: RECORDS.pop(k)
if not RECORDS: DOMAINS.pop(domain["domain"])
if DOMAINS:
print("ERROR: The following records were not found:")
pprint.pprint(DOMAINS)
exit(1)
else:
print("Success")