linuxrouter/docker/routlin-dash/app/pages/ddns/action.py
2026-06-05 01:48:27 -04:00

220 lines
8.7 KiB
Python

from pathlib import Path
import copy
import os
from flask import Blueprint, request, redirect, flash, send_file, abort
from auth import require_level
from config_utils import load_config, verify_config_hash, record_group, diff_fields, CONFIGS_DIR
import sanitize
import mod_validation as validate
_PAGE = Path(__file__).parent.name
bp = Blueprint(_PAGE, __name__)
LOG_FILE = f'{CONFIGS_DIR}/ddns.log'
@bp.route('/action/ddns/addaccount_add', methods=['POST'])
@require_level('administrator')
def addaccount_add():
provider_type = sanitize.filtervalue(request.form.get('provider', ''), validate.VALID_DDNS_PROVIDERS)
description = sanitize.description(request.form.get('description', ''))
hostnames = sanitize.domainlist(request.form.get('hostnames', '').splitlines())
if not description:
flash('Description is required.', 'error')
return redirect(f'/{_PAGE}')
if not hostnames:
flash('At least one hostname is required.', 'error')
return redirect(f'/{_PAGE}')
if not provider_type:
flash('Unknown provider type.', 'error')
return redirect(f'/{_PAGE}')
if not verify_config_hash(request.form.get('config_hash', '')):
flash('Configuration was modified by another session. Please refresh and try again.', 'error')
return redirect(f'/{_PAGE}')
entry = {
'description': description,
'provider': provider_type,
'enabled': True,
'hostnames': hostnames,
}
if provider_type == 'noip':
entry['username'] = request.form.get('username', '').strip()
entry['password'] = request.form.get('password', '').strip()
else:
entry['api_token'] = request.form.get('api_token', '').strip()
cfg = load_config()
cfg.setdefault('ddns', {}).setdefault('providers', []).append(entry)
changes = diff_fields(None, entry)
flash(record_group(cfg, 'ddns.providers', 'description', description, changes, 'ddns update', queue=False), 'success')
return redirect(f'/{_PAGE}')
@bp.route('/action/ddns/accounts_edit', methods=['POST'])
@require_level('administrator')
def accounts_edit():
try:
row_index = int(request.form.get('row_index', -1))
except (TypeError, ValueError):
flash('Invalid row index.', 'error')
return redirect(f'/{_PAGE}')
provider_type = sanitize.filtervalue(request.form.get('provider', ''), validate.VALID_DDNS_PROVIDERS)
description = sanitize.description(request.form.get('description', ''))
hostnames = [h.strip() for h in request.form.get('hostnames', '').splitlines() if h.strip()]
enabled = request.form.get('enabled') == 'on'
if not provider_type:
flash('Unknown provider type.', 'error')
return redirect(f'/{_PAGE}')
if not verify_config_hash(request.form.get('config_hash', '')):
flash('Configuration was modified by another session. Please refresh and try again.', 'error')
return redirect(f'/{_PAGE}')
cfg = load_config()
providers = cfg.setdefault('ddns', {}).setdefault('providers', [])
if row_index < 0 or row_index >= len(providers):
flash('Invalid provider index.', 'error')
return redirect(f'/{_PAGE}')
before = copy.deepcopy(providers[row_index])
entry = {
'description': description,
'provider': provider_type,
'enabled': enabled,
'hostnames': hostnames,
}
if provider_type == 'noip':
entry['username'] = request.form.get('username', '').strip()
entry['password'] = request.form.get('password', '').strip()
else:
entry['api_token'] = request.form.get('api_token', '').strip()
providers[row_index] = entry
changes = diff_fields(before, entry)
flash(record_group(cfg, 'ddns.providers', 'description', description, changes, 'ddns update', queue=False), 'success')
return redirect(f'/{_PAGE}')
@bp.route('/action/ddns/accounts_delete', methods=['POST'])
@require_level('administrator')
def accounts_delete():
try:
row_index = int(request.form.get('row_index', -1))
except (TypeError, ValueError):
flash('Invalid row index.', 'error')
return redirect(f'/{_PAGE}')
if not verify_config_hash(request.form.get('config_hash', '')):
flash('Configuration was modified by another session. Please refresh and try again.', 'error')
return redirect(f'/{_PAGE}')
cfg = load_config()
providers = cfg.setdefault('ddns', {}).setdefault('providers', [])
if row_index < 0 or row_index >= len(providers):
flash('Invalid provider index.', 'error')
return redirect(f'/{_PAGE}')
before = copy.deepcopy(providers[row_index])
description = before.get('description', str(row_index))
del providers[row_index]
changes = diff_fields(before, None)
flash(record_group(cfg, 'ddns.providers', 'description', description, changes, 'ddns update', queue=False), 'success')
return redirect(f'/{_PAGE}')
@bp.route('/action/ddns/ipcheckinterval_save', methods=['POST'])
@require_level('administrator')
def ipcheckinterval_save():
raw = request.form.get('timer_interval', '').strip()
try:
mins = int(raw)
if mins < 1:
raise ValueError
except ValueError:
flash('Interval must be a whole number of minutes >= 1.', 'error')
return redirect(f'/{_PAGE}')
timer_interval = f'{mins}m'
if not verify_config_hash(request.form.get('config_hash', '')):
flash('Configuration was modified by another session. Please refresh and try again.', 'error')
return redirect(f'/{_PAGE}')
cfg = load_config()
before = copy.deepcopy(cfg.get('ddns', {}).get('general', {}))
cfg.setdefault('ddns', {}).setdefault('general', {})['timer_interval'] = timer_interval
changes = diff_fields(before, cfg['ddns']['general'])
flash(record_group(cfg, 'ddns.general', None, None, changes, 'core apply'), 'success')
return redirect(f'/{_PAGE}')
@bp.route('/action/ddns/ipcheckservices_save', methods=['POST'])
@require_level('administrator')
def ipcheckservices_save():
if not verify_config_hash(request.form.get('config_hash', '')):
flash('Configuration was modified by another session. Please refresh and try again.', 'error')
return redirect(f'/{_PAGE}')
http_services = [u.strip() for u in request.form.getlist('http_services') if u.strip()]
dig_services = [u.strip() for u in request.form.getlist('dig_services') if u.strip()]
if not http_services and not dig_services:
flash('At least one IP check service is required.', 'error')
return redirect(f'/{_PAGE}')
cfg = load_config()
before = copy.deepcopy(cfg.get('ddns', {}).get('ip_check_services', []))
services = [{'type': 'http', 'url': u} for u in http_services]
services += [{'type': 'dig', 'url': u} for u in dig_services]
cfg.setdefault('ddns', {})['ip_check_services'] = services
changes = diff_fields({'ip_check_services': before}, {'ip_check_services': services})
flash(record_group(cfg, 'ddns', None, None, changes, 'ddns update', queue=False), 'success')
return redirect(f'/{_PAGE}')
@bp.route('/action/ddns/logging_save', methods=['POST'])
@require_level('administrator')
def logging_save():
log_max_kb = validate.int_range(request.form.get('log_max_kb', '').strip(), 64, None)
if log_max_kb is None:
flash('Max Log Size must be a number >= 64.', 'error')
return redirect(f'/{_PAGE}')
log_errors_only = 'log_errors_only' in request.form
if not verify_config_hash(request.form.get('config_hash', '')):
flash('Configuration was modified by another session. Please refresh and try again.', 'error')
return redirect(f'/{_PAGE}')
cfg = load_config()
before = copy.deepcopy(cfg.get('ddns', {}).get('general', {}))
cfg.setdefault('ddns', {}).setdefault('general', {}).update({
'log_max_kb': log_max_kb,
'log_errors_only': log_errors_only,
})
changes = diff_fields(before, cfg['ddns']['general'])
flash(record_group(cfg, 'ddns.general', None, None, changes, 'ddns update', queue=False), 'success')
return redirect(f'/{_PAGE}')
@bp.route('/action/ddns/logging_clear', methods=['POST'])
@require_level('administrator')
def logging_clear():
try:
open(LOG_FILE, 'w').close()
flash('DDNS log cleared.', 'success')
except Exception as ex:
flash(f'Could not clear log: {ex}', 'error')
return redirect(f'/{_PAGE}')
@bp.route('/action/ddns/logging_download', methods=['GET'])
@require_level('administrator')
def logging_download():
if not os.path.isfile(LOG_FILE):
abort(404)
return send_file(LOG_FILE, as_attachment=True, download_name='ddns.log', mimetype='text/plain')