refactor: move cloudflare domain list to dynamic state file
This commit is contained in:
parent
837bafba09
commit
064144134e
3 changed files with 74 additions and 11 deletions
|
|
@ -1,16 +1,51 @@
|
|||
import requests
|
||||
import sys
|
||||
import json
|
||||
import os
|
||||
|
||||
class CloudflareManager:
|
||||
def __init__(self, config):
|
||||
self.token = config.get('cloudflare.token')
|
||||
self.ddns_domains = config.get('cloudflare.ddns_domains', [])
|
||||
# Path to store the dynamic list of domains
|
||||
self.state_file = config.get('cloudflare.ddns_state_file', '/etc/haproxy/dynamic/ddns_domains.json')
|
||||
self.api_url = "https://api.cloudflare.com/client/v4"
|
||||
self.headers = {
|
||||
"Authorization": f"Bearer {self.token}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
def _load_domains(self):
|
||||
if not os.path.exists(self.state_file):
|
||||
return []
|
||||
try:
|
||||
with open(self.state_file, 'r') as f:
|
||||
return json.load(f)
|
||||
except (json.JSONDecodeError, IOError):
|
||||
return []
|
||||
|
||||
def _save_domains(self, domains):
|
||||
os.makedirs(os.path.dirname(self.state_file), exist_ok=True)
|
||||
with open(self.state_file, 'w') as f:
|
||||
json.dump(list(set(domains)), f, indent=4)
|
||||
|
||||
def add_domain(self, domain):
|
||||
domains = self._load_domains()
|
||||
if domain not in domains:
|
||||
domains.append(domain)
|
||||
self._save_domains(domains)
|
||||
return True
|
||||
return False
|
||||
|
||||
def remove_domain(self, domain):
|
||||
domains = self._load_domains()
|
||||
if domain in domains:
|
||||
domains.remove(domain)
|
||||
self._save_domains(domains)
|
||||
return True
|
||||
return False
|
||||
|
||||
def list_domains(self):
|
||||
return self._load_domains()
|
||||
|
||||
def get_external_ip(self):
|
||||
try:
|
||||
return requests.get("https://checkip.amazonaws.com").text.strip()
|
||||
|
|
@ -30,8 +65,12 @@ class CloudflareManager:
|
|||
if not current_ip:
|
||||
return "Failed to determine current external IP."
|
||||
|
||||
domains = self._load_domains()
|
||||
if not domains:
|
||||
return "No domains configured for DDNS."
|
||||
|
||||
results = []
|
||||
for domain in self.ddns_domains:
|
||||
for domain in domains:
|
||||
zone_id = self.get_zone_id(domain)
|
||||
if not zone_id:
|
||||
results.append(f"[{domain}] Zone not found.")
|
||||
|
|
@ -42,7 +81,6 @@ class CloudflareManager:
|
|||
records = res.json().get('result', [])
|
||||
|
||||
if not records:
|
||||
# Create if missing? For now, just report
|
||||
results.append(f"[{domain}] No A record found to update.")
|
||||
continue
|
||||
|
||||
|
|
@ -67,7 +105,4 @@ class CloudflareManager:
|
|||
else:
|
||||
results.append(f"[{domain}] Update failed: {u_res.text}")
|
||||
|
||||
return "\n".join(results)
|
||||
|
||||
def list_domains(self):
|
||||
return self.ddns_domains
|
||||
return "\n".join(results)
|
||||
Loading…
Add table
Add a link
Reference in a new issue