118 lines
4.7 KiB
Python
118 lines
4.7 KiB
Python
import json
|
|
import re
|
|
import os
|
|
from config_utils import (
|
|
collect_layout_tokens, load_datasource, CONFIGS_DIR, relative_time,
|
|
)
|
|
from factory import load_ddns, load_json, build_table, table_token_key, iter_table_items, PAGES_DIR
|
|
import validation as validate
|
|
|
|
|
|
DDNS_LOG_MAX = 50
|
|
|
|
|
|
def _parse_interval_to_seconds(s):
|
|
m = re.match(r'^(\d+)([mhd])$', str(s).strip())
|
|
if not m:
|
|
return None
|
|
val, unit = int(m.group(1)), m.group(2)
|
|
return val * {'m': 60, 'h': 3600, 'd': 86400}[unit]
|
|
|
|
|
|
def _ddns_log_tail():
|
|
log_path = f'{CONFIGS_DIR}/ddns.log'
|
|
try:
|
|
log_max_kb = load_ddns().get('general', {}).get('log_max_kb', 1024)
|
|
size_kb = os.path.getsize(log_path) / 1024
|
|
with open(log_path) as f:
|
|
lines = f.readlines()
|
|
if not lines:
|
|
return '(log is empty)', ''
|
|
total = len(lines)
|
|
tail = lines[-DDNS_LOG_MAX:]
|
|
shown = len(tail)
|
|
hidden = total - shown
|
|
pct = min(100, round(size_kb / log_max_kb * 100)) if log_max_kb else 0
|
|
left = f'Showing {shown} of {total} lines ({hidden} not shown)' if hidden > 0 else f'Showing {shown} of {total} lines'
|
|
right = f'Log file size: {size_kb:.1f} KB ({pct}% of max)'
|
|
summary = (
|
|
'<div class="text-muted" style="display:flex;justify-content:space-between;margin-top:0.5em;">'
|
|
f'<span>{left}</span><span>{right}</span></div>'
|
|
)
|
|
return ''.join(tail).strip(), summary
|
|
except FileNotFoundError:
|
|
return '(log file not found)', ''
|
|
except Exception:
|
|
return '(error reading log)', ''
|
|
|
|
|
|
def _read_cached_ip():
|
|
try:
|
|
best_ip, best_mtime = '', 0.0
|
|
for fname in os.listdir(CONFIGS_DIR):
|
|
if fname.startswith('.ddns-last-ip-'):
|
|
path = f'{CONFIGS_DIR}/{fname}'
|
|
mtime = os.path.getmtime(path)
|
|
if mtime > best_mtime:
|
|
ip = open(path).read().strip()
|
|
if ip:
|
|
best_ip, best_mtime = ip, mtime
|
|
return best_ip, (best_mtime if best_ip else None)
|
|
except Exception:
|
|
return '', None
|
|
|
|
|
|
def public_ip_info(ddns_cfg):
|
|
from datetime import datetime, timezone
|
|
enabled_p = [p for p in ddns_cfg.get('providers', []) if p.get('enabled', True)]
|
|
all_hosts = []
|
|
for p in enabled_p:
|
|
all_hosts.extend(p.get('hostnames', p.get('subdomains', [])))
|
|
domains_sub = ', '.join(all_hosts)
|
|
ip, mtime = _read_cached_ip()
|
|
last_obtained = f'Obtained: {relative_time(mtime, datetime.now(tz=timezone.utc).timestamp())} ago' if mtime else ''
|
|
if ip:
|
|
return ip, domains_sub, last_obtained
|
|
return 'Offline', domains_sub, ''
|
|
|
|
|
|
def ddns_last_checked():
|
|
from datetime import datetime, timezone
|
|
try:
|
|
mtime = os.path.getmtime(f'{CONFIGS_DIR}/.ddns-last-service')
|
|
return f'Last checked: {relative_time(mtime, datetime.now(tz=timezone.utc).timestamp())} ago'
|
|
except OSError:
|
|
return 'Last checked: ---'
|
|
|
|
|
|
def collect_tokens(cfg):
|
|
tokens = collect_layout_tokens(cfg)
|
|
ddns = load_ddns()
|
|
ddns_gen = ddns.get('general', {})
|
|
tokens['DDNS_TIMER_INTERVAL'] = ddns_gen.get('timer_interval', '-')
|
|
interval_secs = _parse_interval_to_seconds(ddns_gen.get('timer_interval', '')) or 600
|
|
tokens['DDNS_TIMER_INTERVAL_MINS'] = str(interval_secs // 60)
|
|
tokens['DDNS_GEN_LOG_MAX_KB'] = str(ddns_gen.get('log_max_kb', 1024))
|
|
tokens['DDNS_GEN_LOG_ERRORS_ONLY'] = 'true' if ddns_gen.get('log_errors_only') else 'false'
|
|
ip_check = ddns.get('ip_check_services', [])
|
|
http_svc = [s['url'] for s in ip_check if s.get('type') == 'http']
|
|
dig_svc = [s['url'] for s in ip_check if s.get('type') == 'dig']
|
|
tokens['STAT_IP_CHECK_TOTAL'] = str(len(ip_check))
|
|
tokens['STAT_IP_CHECK_SUB'] = f'{len(http_svc)} http and {len(dig_svc)} dig'
|
|
tokens['IP_CHECK_HTTP_JSON'] = json.dumps(http_svc)
|
|
tokens['IP_CHECK_DIG_JSON'] = json.dumps(dig_svc)
|
|
ddns_labels = {'noip': 'No-IP', 'cloudflare': 'Cloudflare', 'duckdns': 'DuckDNS'}
|
|
tokens['DDNS_PROVIDER_OPTIONS'] = json.dumps([
|
|
{'value': p, 'label': ddns_labels.get(p, p.title())}
|
|
for p in validate.VALID_DDNS_PROVIDERS
|
|
])
|
|
ip_str, domains_sub, last_obtained = public_ip_info(ddns)
|
|
tokens['STAT_PUBLIC_IP'] = ip_str
|
|
tokens['STAT_PUBLIC_IP_LAST_OBTAINED'] = last_obtained
|
|
tokens['STAT_PUBLIC_IP_LAST_CHECKED'] = ddns_last_checked()
|
|
tokens['DDNS_LOG_TAIL'], tokens['DDNS_LOG_SUMMARY'] = _ddns_log_tail()
|
|
content = load_json(f'{PAGES_DIR}/ddns/content.json')
|
|
for table_item in iter_table_items(content.get('items', [])):
|
|
ds = table_item.get('datasource', '')
|
|
tokens[table_token_key(ds)] = build_table(table_item, tokens, load_datasource(ds))
|
|
return tokens
|