linuxrouter/docker/routlin-dash/app/pages/ddns/view.py
2026-06-02 00:47:03 -04:00

71 lines
2.9 KiB
Python

import json
import re
import os
from view_common import load_ddns, public_ip_info, ddns_last_checked, CONFIGS_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 collect_tokens(cfg):
tokens = {}
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()
return tokens