mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-10-13 18:46:37 +00:00
fix(web): partial JSON saves to /config/main change only what they send
A JSON body with one field reset every checkbox in the sections it touched: the MQTT bridge's brightness slider turned off disable_hardware_pulsing, inverse_colors, show_refresh_rate and use_short_date_format, and a timezone-only save turned off web-UI autostart and weekly auto-updates. Missing-means-unchecked now applies only to form posts: form-encoded bodies and the v3 forms, which mark themselves with a hidden __form_section input. Also on the config routes: - vegas_min/max_cycle_duration no longer match the generic *_duration rule, so they stop landing in display_durations and a blank one no longer rejects the whole Display save; - saving from the Raw JSON editor calls start_setup_if_needed like the General form, so enabling auto-update there finishes its setup; - the schedule and dim-schedule POSTs accept the per-day days.<day> shape their GETs return, as well as the flat form keys. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,277 @@
|
|||||||
|
"""POST /config/main: a partial JSON body changes only what it sends.
|
||||||
|
|
||||||
|
The settings forms post every field, and a browser leaves an unchecked box out,
|
||||||
|
so for a form a missing checkbox means False. JSON API clients send only what
|
||||||
|
they change. Treating their missing keys as unchecked meant:
|
||||||
|
|
||||||
|
- the MQTT bridge's Home Assistant brightness slider (``{"brightness": N}``)
|
||||||
|
turned off disable_hardware_pulsing, inverse_colors, show_refresh_rate and
|
||||||
|
use_short_date_format on every change;
|
||||||
|
- the documented timezone/location update turned off web_display_autostart and
|
||||||
|
weekly automatic updates.
|
||||||
|
|
||||||
|
The v3 forms post JSON as well (htmx json-enc), so they mark themselves with a
|
||||||
|
hidden ``__form_section`` input; these tests pin both halves of that contract.
|
||||||
|
|
||||||
|
Also here: the Vegas cycle-time fields no longer land in display_durations
|
||||||
|
(and a blank one no longer 400s the Display save), the Raw JSON editor starts
|
||||||
|
auto-update setup like the General form does, and both schedule POSTs accept
|
||||||
|
the per-day shape their GETs return.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import copy
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from test._api_v3_test_helpers import api_v3_client, api_v3_module # noqa: F401
|
||||||
|
|
||||||
|
REPO = Path(__file__).resolve().parent.parent
|
||||||
|
PARTIALS = REPO / 'web_interface' / 'templates' / 'v3' / 'partials'
|
||||||
|
|
||||||
|
STORED = {
|
||||||
|
'web_display_autostart': True,
|
||||||
|
'auto_update': {'enabled': True},
|
||||||
|
'timezone': 'America/Chicago',
|
||||||
|
'plugin_system': {'auto_discover': True, 'auto_load_enabled': True,
|
||||||
|
'development_mode': True},
|
||||||
|
'display': {
|
||||||
|
'hardware': {'rows': 32, 'cols': 64, 'chain_length': 2, 'brightness': 90,
|
||||||
|
'disable_hardware_pulsing': True, 'inverse_colors': True,
|
||||||
|
'show_refresh_rate': True},
|
||||||
|
'runtime': {'gpio_slowdown': 4},
|
||||||
|
'use_short_date_format': True,
|
||||||
|
'double_sided': {'enabled': True, 'copies': 2, 'axis': 'horizontal'},
|
||||||
|
'vegas_scroll': {'enabled': True, 'auto_trim': True,
|
||||||
|
'dynamic_duration_enabled': True,
|
||||||
|
'continuous_scroll': True, 'smooth_scroll': True},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def saved(api_v3_module, monkeypatch):
|
||||||
|
captured = {}
|
||||||
|
api_v3_module.api_v3.config_manager.load_config.side_effect = \
|
||||||
|
lambda *a, **k: copy.deepcopy(STORED)
|
||||||
|
|
||||||
|
def fake_save(_manager, config, **_kwargs):
|
||||||
|
captured['config'] = config
|
||||||
|
return True, ''
|
||||||
|
|
||||||
|
monkeypatch.setattr(api_v3_module, '_save_config_atomic', fake_save)
|
||||||
|
from web_interface import auto_update
|
||||||
|
monkeypatch.setattr(auto_update, 'start_setup_if_needed', lambda *a, **k: None)
|
||||||
|
return captured
|
||||||
|
|
||||||
|
|
||||||
|
def _post_json(client, body):
|
||||||
|
return client.post('/api/v3/config/main', data=json.dumps(body),
|
||||||
|
content_type='application/json')
|
||||||
|
|
||||||
|
|
||||||
|
class TestJsonPartialSaves:
|
||||||
|
def test_mqtt_bridge_brightness_changes_only_brightness(self, api_v3_client, saved):
|
||||||
|
# integrations/mqtt_bridge/ledmatrix_mqtt_bridge.py set_brightness
|
||||||
|
resp = _post_json(api_v3_client, {'brightness': 40})
|
||||||
|
assert resp.status_code == 200, resp.get_json()
|
||||||
|
display = saved['config']['display']
|
||||||
|
assert display['hardware']['brightness'] == 40
|
||||||
|
assert display['hardware']['disable_hardware_pulsing'] is True
|
||||||
|
assert display['hardware']['inverse_colors'] is True
|
||||||
|
assert display['hardware']['show_refresh_rate'] is True
|
||||||
|
assert display['use_short_date_format'] is True
|
||||||
|
|
||||||
|
def test_timezone_only_keeps_autostart_and_auto_update(self, api_v3_client, saved):
|
||||||
|
resp = _post_json(api_v3_client, {'timezone': 'UTC'})
|
||||||
|
assert resp.status_code == 200, resp.get_json()
|
||||||
|
config = saved['config']
|
||||||
|
assert config['timezone'] == 'UTC'
|
||||||
|
assert config['web_display_autostart'] is True
|
||||||
|
assert config['auto_update'] == {'enabled': True}
|
||||||
|
|
||||||
|
def test_location_only_keeps_plugin_system_toggles(self, api_v3_client, saved):
|
||||||
|
resp = _post_json(api_v3_client, {'city': 'Paris', 'plugins_directory': 'plugin-repos'})
|
||||||
|
assert resp.status_code == 200, resp.get_json()
|
||||||
|
assert saved['config']['plugin_system'] == {
|
||||||
|
'auto_discover': True, 'auto_load_enabled': True,
|
||||||
|
'development_mode': True, 'plugins_directory': 'plugin-repos'}
|
||||||
|
|
||||||
|
def test_vegas_speed_only_keeps_vegas_toggles(self, api_v3_client, saved):
|
||||||
|
resp = _post_json(api_v3_client, {'vegas_scroll_speed': 80})
|
||||||
|
assert resp.status_code == 200, resp.get_json()
|
||||||
|
vegas = saved['config']['display']['vegas_scroll']
|
||||||
|
assert vegas['scroll_speed'] == 80
|
||||||
|
for key in ('enabled', 'auto_trim', 'dynamic_duration_enabled',
|
||||||
|
'continuous_scroll', 'smooth_scroll'):
|
||||||
|
assert vegas[key] is True, key
|
||||||
|
|
||||||
|
def test_double_sided_axis_only_keeps_enabled(self, api_v3_client, saved):
|
||||||
|
resp = _post_json(api_v3_client, {'double_sided_axis': 'horizontal'})
|
||||||
|
assert resp.status_code == 200, resp.get_json()
|
||||||
|
assert saved['config']['display']['double_sided']['enabled'] is True
|
||||||
|
|
||||||
|
def test_json_can_still_turn_a_checkbox_off(self, api_v3_client, saved):
|
||||||
|
resp = _post_json(api_v3_client, {'inverse_colors': False, 'auto_update_enabled': False})
|
||||||
|
assert resp.status_code == 200, resp.get_json()
|
||||||
|
assert saved['config']['display']['hardware']['inverse_colors'] is False
|
||||||
|
assert saved['config']['display']['hardware']['disable_hardware_pulsing'] is True
|
||||||
|
assert saved['config']['auto_update'] == {'enabled': False}
|
||||||
|
|
||||||
|
def test_json_with_charset_is_still_json(self, api_v3_client, saved):
|
||||||
|
resp = api_v3_client.post('/api/v3/config/main', data=json.dumps({'brightness': 41}),
|
||||||
|
content_type='application/json; charset=utf-8')
|
||||||
|
assert resp.status_code == 200, resp.get_json()
|
||||||
|
assert saved['config']['display']['hardware']['brightness'] == 41
|
||||||
|
assert saved['config']['display']['hardware']['inverse_colors'] is True
|
||||||
|
|
||||||
|
def test_a_non_object_body_is_refused(self, api_v3_client, saved):
|
||||||
|
assert _post_json(api_v3_client, [1, 2]).status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
class TestFormSavesStillUncheck:
|
||||||
|
"""Unchecking a box in the UI must still save false."""
|
||||||
|
|
||||||
|
def test_marked_json_form_post_unchecks_missing_display_boxes(self, api_v3_client, saved):
|
||||||
|
resp = _post_json(api_v3_client, {'__form_section': 'display', 'brightness': '40',
|
||||||
|
'vegas_scroll_speed': '50'})
|
||||||
|
assert resp.status_code == 200, resp.get_json()
|
||||||
|
display = saved['config']['display']
|
||||||
|
for key in ('disable_hardware_pulsing', 'inverse_colors', 'show_refresh_rate'):
|
||||||
|
assert display['hardware'][key] is False, key
|
||||||
|
assert display['use_short_date_format'] is False
|
||||||
|
assert display['vegas_scroll']['enabled'] is False
|
||||||
|
assert '__form_section' not in saved['config']
|
||||||
|
|
||||||
|
def test_marked_json_form_post_keeps_checked_boxes(self, api_v3_client, saved):
|
||||||
|
resp = _post_json(api_v3_client, {'__form_section': 'display', 'brightness': '40',
|
||||||
|
'inverse_colors': 'on'})
|
||||||
|
assert resp.status_code == 200, resp.get_json()
|
||||||
|
assert saved['config']['display']['hardware']['inverse_colors'] is True
|
||||||
|
assert saved['config']['display']['hardware']['show_refresh_rate'] is False
|
||||||
|
|
||||||
|
def test_marked_general_form_unchecks_autostart_and_auto_update(self, api_v3_client, saved):
|
||||||
|
resp = _post_json(api_v3_client, {'__form_section': 'general', 'timezone': 'UTC'})
|
||||||
|
assert resp.status_code == 200, resp.get_json()
|
||||||
|
assert saved['config']['web_display_autostart'] is False
|
||||||
|
assert saved['config']['auto_update'] == {'enabled': False}
|
||||||
|
|
||||||
|
def test_form_encoded_post_unchecks_missing_boxes(self, api_v3_client, saved):
|
||||||
|
resp = api_v3_client.post('/api/v3/config/main', data={'brightness': '40'},
|
||||||
|
content_type='application/x-www-form-urlencoded')
|
||||||
|
assert resp.status_code == 200, resp.get_json()
|
||||||
|
assert saved['config']['display']['hardware']['inverse_colors'] is False
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('partial', ['general.html', 'display.html', 'durations.html'])
|
||||||
|
def test_every_config_main_form_carries_the_marker(self, partial):
|
||||||
|
html = (PARTIALS / partial).read_text(encoding='utf-8')
|
||||||
|
form = re.search(r'<form hx-post="/api/v3/config/main".*?</form>', html, re.S)
|
||||||
|
assert form, f'{partial} no longer posts to /config/main'
|
||||||
|
assert re.search(r'<input type="hidden" name="__form_section" value="\w+">',
|
||||||
|
form.group(0)), f'{partial} form lost its __form_section marker'
|
||||||
|
|
||||||
|
|
||||||
|
class TestVegasCycleDurations:
|
||||||
|
def test_cycle_durations_are_not_display_durations(self, api_v3_client, saved):
|
||||||
|
resp = api_v3_client.post('/api/v3/config/main', data={
|
||||||
|
'vegas_scroll_enabled': 'on', 'vegas_min_cycle_duration': '90',
|
||||||
|
'vegas_max_cycle_duration': '300'})
|
||||||
|
assert resp.status_code == 200, resp.get_json()
|
||||||
|
display = saved['config']['display']
|
||||||
|
assert display['vegas_scroll']['min_cycle_duration'] == 90
|
||||||
|
assert display['vegas_scroll']['max_cycle_duration'] == 300
|
||||||
|
durations = display.get('display_durations', {})
|
||||||
|
assert 'vegas_min_cycle_duration' not in durations
|
||||||
|
assert 'vegas_max_cycle_duration' not in durations
|
||||||
|
assert 'vegas_min_cycle_duration' not in saved['config']
|
||||||
|
|
||||||
|
def test_blank_cycle_duration_does_not_reject_the_save(self, api_v3_client, saved):
|
||||||
|
resp = api_v3_client.post('/api/v3/config/main', data={
|
||||||
|
'vegas_scroll_enabled': 'on', 'vegas_scroll_speed': '60',
|
||||||
|
'vegas_min_cycle_duration': ''})
|
||||||
|
assert resp.status_code == 200, resp.get_json()
|
||||||
|
assert saved['config']['display']['vegas_scroll']['scroll_speed'] == 60
|
||||||
|
|
||||||
|
def test_real_display_durations_still_save(self, api_v3_client, saved):
|
||||||
|
resp = _post_json(api_v3_client, {'clock_duration': '45'})
|
||||||
|
assert resp.status_code == 200, resp.get_json()
|
||||||
|
assert saved['config']['display']['display_durations']['clock_duration'] == 45
|
||||||
|
|
||||||
|
|
||||||
|
class TestRawSaveStartsAutoUpdateSetup:
|
||||||
|
@pytest.fixture
|
||||||
|
def raw_env(self, api_v3_module, monkeypatch):
|
||||||
|
cm = api_v3_module.api_v3.config_manager
|
||||||
|
cm.get_raw_file_content.return_value = {'timezone': 'UTC', 'auto_update': {'enabled': False}}
|
||||||
|
calls = []
|
||||||
|
from web_interface import auto_update
|
||||||
|
monkeypatch.setattr(auto_update, 'start_setup_if_needed',
|
||||||
|
lambda was, config: calls.append((was, config)) or 'Setup note.')
|
||||||
|
return cm, calls
|
||||||
|
|
||||||
|
def test_enabling_from_raw_json_calls_setup(self, api_v3_client, raw_env):
|
||||||
|
cm, calls = raw_env
|
||||||
|
body = {'timezone': 'UTC', 'auto_update': {'enabled': True}}
|
||||||
|
resp = api_v3_client.post('/api/v3/config/raw/main', json=body)
|
||||||
|
assert resp.status_code == 200, resp.get_json()
|
||||||
|
cm.save_raw_file_content.assert_called_once_with('main', body)
|
||||||
|
assert calls == [(False, body)]
|
||||||
|
assert 'Setup note.' in resp.get_json()['message']
|
||||||
|
|
||||||
|
def test_previously_enabled_is_passed_through(self, api_v3_client, raw_env):
|
||||||
|
cm, calls = raw_env
|
||||||
|
cm.get_raw_file_content.return_value = {'auto_update': {'enabled': True}}
|
||||||
|
body = {'auto_update': {'enabled': True}}
|
||||||
|
assert api_v3_client.post('/api/v3/config/raw/main', json=body).status_code == 200
|
||||||
|
assert calls == [(True, body)]
|
||||||
|
|
||||||
|
|
||||||
|
class TestSchedulesAcceptTheirGetShape:
|
||||||
|
PER_DAY = {
|
||||||
|
'enabled': True, 'mode': 'per-day', 'dim_brightness': 20,
|
||||||
|
'days': {
|
||||||
|
'monday': {'enabled': True, 'start_time': '21:15', 'end_time': '06:45'},
|
||||||
|
'tuesday': {'enabled': False},
|
||||||
|
'wednesday': {'enabled': True, 'start_time': '22:00', 'end_time': '05:30'},
|
||||||
|
'thursday': {'enabled': True, 'start_time': '20:00', 'end_time': '07:00'},
|
||||||
|
'friday': {'enabled': True, 'start_time': '23:00', 'end_time': '08:00'},
|
||||||
|
'saturday': {'enabled': True, 'start_time': '23:30', 'end_time': '09:00'},
|
||||||
|
'sunday': {'enabled': True, 'start_time': '21:00', 'end_time': '07:00'},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def store(self, api_v3_module, monkeypatch):
|
||||||
|
state = {'config': {}}
|
||||||
|
api_v3_module.api_v3.config_manager.load_config.side_effect = \
|
||||||
|
lambda *a, **k: copy.deepcopy(state['config'])
|
||||||
|
|
||||||
|
def fake_save(_manager, config, **_kwargs):
|
||||||
|
state['config'] = copy.deepcopy(config)
|
||||||
|
return True, ''
|
||||||
|
|
||||||
|
monkeypatch.setattr(api_v3_module, '_save_config_atomic', fake_save)
|
||||||
|
return state
|
||||||
|
|
||||||
|
@pytest.mark.parametrize('route,section,extra', [
|
||||||
|
('/api/v3/config/dim-schedule', 'dim_schedule', {'dim_brightness': 20}),
|
||||||
|
('/api/v3/config/schedule', 'schedule', {}),
|
||||||
|
])
|
||||||
|
def test_get_output_posts_back_unchanged(self, api_v3_client, store, route, section, extra):
|
||||||
|
body = {k: v for k, v in self.PER_DAY.items() if k != 'dim_brightness'}
|
||||||
|
body.update(extra)
|
||||||
|
store['config'] = {section: copy.deepcopy(body)}
|
||||||
|
read = api_v3_client.get(route).get_json()['data']
|
||||||
|
resp = api_v3_client.post(route, json=read)
|
||||||
|
assert resp.status_code == 200, resp.get_json()
|
||||||
|
assert store['config'][section]['days'] == body['days']
|
||||||
|
|
||||||
|
def test_flat_form_keys_still_work(self, api_v3_client, store):
|
||||||
|
body = {'enabled': True, 'mode': 'per-day', 'dim_brightness': 25,
|
||||||
|
'monday_enabled': 'on', 'monday_start': '19:00', 'monday_end': '06:00'}
|
||||||
|
resp = api_v3_client.post('/api/v3/config/dim-schedule', json=body)
|
||||||
|
assert resp.status_code == 200, resp.get_json()
|
||||||
|
assert store['config']['dim_schedule']['days']['monday'] == {
|
||||||
|
'enabled': True, 'start_time': '19:00', 'end_time': '06:00'}
|
||||||
@@ -668,7 +668,9 @@ class TestSettingsSave:
|
|||||||
|
|
||||||
def test_unchecked_toggle_on_general_save_disables(self, api_client):
|
def test_unchecked_toggle_on_general_save_disables(self, api_client):
|
||||||
client, cm, setup_calls = api_client
|
client, cm, setup_calls = api_client
|
||||||
resp = client.post('/api/v3/config/main', json={'timezone': 'UTC'})
|
# The General form marks its posts; an unchecked box is then absent.
|
||||||
|
resp = client.post('/api/v3/config/main',
|
||||||
|
json={'__form_section': 'general', 'timezone': 'UTC'})
|
||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
assert self._saved(cm)['auto_update'] == {'enabled': False}
|
assert self._saved(cm)['auto_update'] == {'enabled': False}
|
||||||
assert setup_calls == [True]
|
assert setup_calls == [True]
|
||||||
|
|||||||
@@ -14,11 +14,33 @@ from web_interface.blueprints.api_v3 import (
|
|||||||
from src.common.path_safety import resolve_under
|
from src.common.path_safety import resolve_under
|
||||||
from src.pi5_matrix_support import is_raspberry_pi_5, pi5_unsupported_settings
|
from src.pi5_matrix_support import is_raspberry_pi_5, pi5_unsupported_settings
|
||||||
import web_interface.blueprints.api_v3 as _pkg
|
import web_interface.blueprints.api_v3 as _pkg
|
||||||
|
|
||||||
# Read through the module rather than bound by value: tests patch these
|
# Read through the module rather than bound by value: tests patch these
|
||||||
# as module attributes, and a value binding would not see the patch.
|
# as module attributes, and a value binding would not see the patch.
|
||||||
# Several are also called from helpers that live in __init__, so the
|
# Several are also called from helpers that live in __init__, so the
|
||||||
# package is the only patch point that covers every caller.
|
# package is the only patch point that covers every caller.
|
||||||
|
|
||||||
|
#: Hidden input the v3 settings forms (general.html, display.html,
|
||||||
|
#: durations.html) post to /config/main. Its presence tells save_main_config
|
||||||
|
#: that a missing checkbox was unchecked, not merely left out of an API call.
|
||||||
|
FORM_SECTION_FIELD = '__form_section'
|
||||||
|
|
||||||
|
|
||||||
|
def _day_setting(data, day, flat_key, nested_key):
|
||||||
|
"""(present, value) of one per-day schedule setting in a POST body.
|
||||||
|
|
||||||
|
The schedule forms post flat keys (``monday_start``), while GET returns
|
||||||
|
the stored shape, ``days.monday.start_time``. Accept both, so a client can
|
||||||
|
post back what it read; a flat key wins when a body carries both.
|
||||||
|
"""
|
||||||
|
if flat_key in data:
|
||||||
|
return True, data[flat_key]
|
||||||
|
days = data.get('days')
|
||||||
|
day_config = days.get(day) if isinstance(days, dict) else None
|
||||||
|
if isinstance(day_config, dict) and nested_key in day_config:
|
||||||
|
return True, day_config[nested_key]
|
||||||
|
return False, None
|
||||||
|
|
||||||
|
|
||||||
@api_v3.route('/config/main', methods=['GET'])
|
@api_v3.route('/config/main', methods=['GET'])
|
||||||
def get_main_config():
|
def get_main_config():
|
||||||
@@ -123,8 +145,8 @@ def save_schedule_config():
|
|||||||
end_key = f'{day}_end'
|
end_key = f'{day}_end'
|
||||||
|
|
||||||
# Check if day is enabled
|
# Check if day is enabled
|
||||||
if enabled_key in data:
|
has_enabled, enabled_val = _day_setting(data, day, enabled_key, 'enabled')
|
||||||
enabled_val = data[enabled_key]
|
if has_enabled:
|
||||||
# Handle checkbox values that may come as 'on', True, or False
|
# Handle checkbox values that may come as 'on', True, or False
|
||||||
if isinstance(enabled_val, str):
|
if isinstance(enabled_val, str):
|
||||||
day_config['enabled'] = enabled_val.lower() in ('true', 'on', '1')
|
day_config['enabled'] = enabled_val.lower() in ('true', 'on', '1')
|
||||||
@@ -140,15 +162,8 @@ def save_schedule_config():
|
|||||||
start_time = None
|
start_time = None
|
||||||
end_time = None
|
end_time = None
|
||||||
|
|
||||||
if start_key in data and data[start_key]:
|
start_time = _day_setting(data, day, start_key, 'start_time')[1] or '07:00'
|
||||||
start_time = data[start_key]
|
end_time = _day_setting(data, day, end_key, 'end_time')[1] or '23:00'
|
||||||
else:
|
|
||||||
start_time = '07:00'
|
|
||||||
|
|
||||||
if end_key in data and data[end_key]:
|
|
||||||
end_time = data[end_key]
|
|
||||||
else:
|
|
||||||
end_time = '23:00'
|
|
||||||
|
|
||||||
# Validate time formats
|
# Validate time formats
|
||||||
is_valid, error_msg = _validate_time_format(start_time)
|
is_valid, error_msg = _validate_time_format(start_time)
|
||||||
@@ -352,8 +367,8 @@ def save_dim_schedule_config():
|
|||||||
end_key = f'{day}_end'
|
end_key = f'{day}_end'
|
||||||
|
|
||||||
# Check if day is enabled
|
# Check if day is enabled
|
||||||
if enabled_key in data:
|
has_enabled, enabled_val = _day_setting(data, day, enabled_key, 'enabled')
|
||||||
enabled_val = data[enabled_key]
|
if has_enabled:
|
||||||
if isinstance(enabled_val, str):
|
if isinstance(enabled_val, str):
|
||||||
day_config['enabled'] = enabled_val.lower() in ('true', 'on', '1')
|
day_config['enabled'] = enabled_val.lower() in ('true', 'on', '1')
|
||||||
else:
|
else:
|
||||||
@@ -364,8 +379,8 @@ def save_dim_schedule_config():
|
|||||||
# Only add times if day is enabled
|
# Only add times if day is enabled
|
||||||
if day_config.get('enabled', True):
|
if day_config.get('enabled', True):
|
||||||
enabled_days_count += 1
|
enabled_days_count += 1
|
||||||
start_time = data.get(start_key) or '20:00'
|
start_time = _day_setting(data, day, start_key, 'start_time')[1] or '20:00'
|
||||||
end_time = data.get(end_key) or '07:00'
|
end_time = _day_setting(data, day, end_key, 'end_time')[1] or '07:00'
|
||||||
|
|
||||||
# Validate time formats
|
# Validate time formats
|
||||||
is_valid, error_msg = _validate_time_format(start_time)
|
is_valid, error_msg = _validate_time_format(start_time)
|
||||||
@@ -433,8 +448,10 @@ def save_main_config():
|
|||||||
|
|
||||||
# Try to get JSON data first, fallback to form data
|
# Try to get JSON data first, fallback to form data
|
||||||
data = None
|
data = None
|
||||||
if request.content_type == 'application/json':
|
if request.is_json:
|
||||||
data = request.get_json()
|
data = request.get_json()
|
||||||
|
if data is not None and not isinstance(data, dict):
|
||||||
|
return jsonify({'status': 'error', 'message': 'Request body must be a JSON object'}), 400
|
||||||
else:
|
else:
|
||||||
# Handle form data
|
# Handle form data
|
||||||
data = request.form.to_dict()
|
data = request.form.to_dict()
|
||||||
@@ -446,6 +463,24 @@ def save_main_config():
|
|||||||
if not data:
|
if not data:
|
||||||
return jsonify({'status': 'error', 'message': 'No data provided'}), 400
|
return jsonify({'status': 'error', 'message': 'No data provided'}), 400
|
||||||
|
|
||||||
|
# A missing checkbox means different things to the two kinds of caller.
|
||||||
|
# The settings forms post every field, and a browser leaves an
|
||||||
|
# unchecked box out entirely, so for them absent means False. A JSON
|
||||||
|
# API client (the MQTT bridge's brightness slider, a curl call from the
|
||||||
|
# REST docs) sends only what it is changing, and there absent means
|
||||||
|
# "leave it alone": treating it as unchecked turned off
|
||||||
|
# disable_hardware_pulsing and three other settings on every
|
||||||
|
# brightness change, and weekly auto-updates on every timezone change.
|
||||||
|
# The v3 forms post JSON too (htmx json-enc), so they identify
|
||||||
|
# themselves with a hidden FORM_SECTION_FIELD input. A form-encoded
|
||||||
|
# post is a form by definition.
|
||||||
|
is_form_submission = bool(data.pop(FORM_SECTION_FIELD, None)) or not request.is_json
|
||||||
|
|
||||||
|
def _set_checkbox(section, key, field):
|
||||||
|
"""Store checkbox ``field`` as ``section[key]``, if this request sets it."""
|
||||||
|
if is_form_submission or field in data:
|
||||||
|
section[key] = _coerce_to_bool(data.get(field))
|
||||||
|
|
||||||
# What arrives here is the config itself, and the headers carry the
|
# What arrives here is the config itself, and the headers carry the
|
||||||
# session cookie -- neither belongs in the journal, least of all at
|
# session cookie -- neither belongs in the journal, least of all at
|
||||||
# ERROR on every save. The shape of the request is the part with
|
# ERROR on every save. The shape of the request is the part with
|
||||||
@@ -465,11 +500,13 @@ def save_main_config():
|
|||||||
'auto_update_enabled'])
|
'auto_update_enabled'])
|
||||||
|
|
||||||
if is_general_update:
|
if is_general_update:
|
||||||
# For checkbox: if not present in data during general update, it means unchecked
|
# For checkbox: if not present in data during a general *form*
|
||||||
current_config['web_display_autostart'] = _coerce_to_bool(data.get('web_display_autostart'))
|
# update, it means unchecked (see _set_checkbox)
|
||||||
|
_set_checkbox(current_config, 'web_display_autostart', 'web_display_autostart')
|
||||||
|
if is_form_submission or 'auto_update_enabled' in data:
|
||||||
if not isinstance(current_config.get('auto_update'), dict):
|
if not isinstance(current_config.get('auto_update'), dict):
|
||||||
current_config['auto_update'] = {}
|
current_config['auto_update'] = {}
|
||||||
current_config['auto_update']['enabled'] = _coerce_to_bool(data.get('auto_update_enabled'))
|
_set_checkbox(current_config['auto_update'], 'enabled', 'auto_update_enabled')
|
||||||
|
|
||||||
if 'timezone' in data:
|
if 'timezone' in data:
|
||||||
current_config['timezone'] = data['timezone']
|
current_config['timezone'] = data['timezone']
|
||||||
@@ -523,7 +560,7 @@ def save_main_config():
|
|||||||
# Handle plugin system checkboxes - always set to handle unchecked state
|
# Handle plugin system checkboxes - always set to handle unchecked state
|
||||||
# HTML checkboxes omit the key when unchecked, so missing key = unchecked = False
|
# HTML checkboxes omit the key when unchecked, so missing key = unchecked = False
|
||||||
for checkbox in ['auto_discover', 'auto_load_enabled', 'development_mode']:
|
for checkbox in ['auto_discover', 'auto_load_enabled', 'development_mode']:
|
||||||
current_config['plugin_system'][checkbox] = _coerce_to_bool(data.get(checkbox))
|
_set_checkbox(current_config['plugin_system'], checkbox, checkbox)
|
||||||
|
|
||||||
# Handle plugins_directory
|
# Handle plugins_directory
|
||||||
if 'plugins_directory' in data:
|
if 'plugins_directory' in data:
|
||||||
@@ -646,10 +683,10 @@ def save_main_config():
|
|||||||
|
|
||||||
# Handle checkboxes - coerce to bool to ensure proper JSON types
|
# Handle checkboxes - coerce to bool to ensure proper JSON types
|
||||||
for checkbox in ['disable_hardware_pulsing', 'inverse_colors', 'show_refresh_rate']:
|
for checkbox in ['disable_hardware_pulsing', 'inverse_colors', 'show_refresh_rate']:
|
||||||
current_config['display']['hardware'][checkbox] = _coerce_to_bool(data.get(checkbox))
|
_set_checkbox(current_config['display']['hardware'], checkbox, checkbox)
|
||||||
|
|
||||||
# Handle display-level checkboxes (always set to handle unchecked state)
|
# Handle display-level checkboxes (unchecked state on form saves)
|
||||||
current_config['display']['use_short_date_format'] = _coerce_to_bool(data.get('use_short_date_format'))
|
_set_checkbox(current_config['display'], 'use_short_date_format', 'use_short_date_format')
|
||||||
|
|
||||||
# Handle dynamic duration settings
|
# Handle dynamic duration settings
|
||||||
if 'max_dynamic_duration_seconds' in data:
|
if 'max_dynamic_duration_seconds' in data:
|
||||||
@@ -671,8 +708,11 @@ def save_main_config():
|
|||||||
# checkbox, so when the feature is off we accept the values without
|
# checkbox, so when the feature is off we accept the values without
|
||||||
# rejecting the whole save — otherwise a stale copies/chain_length
|
# rejecting the whole save — otherwise a stale copies/chain_length
|
||||||
# mismatch locks the user out of every other display setting.
|
# mismatch locks the user out of every other display setting.
|
||||||
|
if is_form_submission or 'double_sided_enabled' in data:
|
||||||
enabled = _coerce_to_bool(data.get('double_sided_enabled'))
|
enabled = _coerce_to_bool(data.get('double_sided_enabled'))
|
||||||
ds_config['enabled'] = enabled
|
ds_config['enabled'] = enabled
|
||||||
|
else:
|
||||||
|
enabled = _coerce_to_bool(ds_config.get('enabled'))
|
||||||
|
|
||||||
def _copies_fits_hardware(copies: int) -> Optional[str]:
|
def _copies_fits_hardware(copies: int) -> Optional[str]:
|
||||||
"""Error message if copies doesn't divide the panel evenly, else None."""
|
"""Error message if copies doesn't divide the panel evenly, else None."""
|
||||||
@@ -742,15 +782,13 @@ def save_main_config():
|
|||||||
# Handle enabled checkbox
|
# Handle enabled checkbox
|
||||||
# HTML checkboxes omit the key entirely when unchecked, so if the form
|
# HTML checkboxes omit the key entirely when unchecked, so if the form
|
||||||
# was submitted (any vegas field present) but enabled key is missing,
|
# was submitted (any vegas field present) but enabled key is missing,
|
||||||
# the checkbox was unchecked and we should set enabled=False
|
# the checkbox was unchecked and we should set enabled=False.
|
||||||
vegas_config['enabled'] = _coerce_to_bool(data.get('vegas_scroll_enabled'))
|
# A JSON API call only changes the checkboxes it sends.
|
||||||
vegas_config['auto_trim'] = _coerce_to_bool(data.get('vegas_auto_trim'))
|
_set_checkbox(vegas_config, 'enabled', 'vegas_scroll_enabled')
|
||||||
vegas_config['dynamic_duration_enabled'] = _coerce_to_bool(
|
_set_checkbox(vegas_config, 'auto_trim', 'vegas_auto_trim')
|
||||||
data.get('vegas_dynamic_duration_enabled'))
|
_set_checkbox(vegas_config, 'dynamic_duration_enabled', 'vegas_dynamic_duration_enabled')
|
||||||
vegas_config['continuous_scroll'] = _coerce_to_bool(
|
_set_checkbox(vegas_config, 'continuous_scroll', 'vegas_continuous_scroll')
|
||||||
data.get('vegas_continuous_scroll'))
|
_set_checkbox(vegas_config, 'smooth_scroll', 'vegas_smooth_scroll')
|
||||||
vegas_config['smooth_scroll'] = _coerce_to_bool(
|
|
||||||
data.get('vegas_smooth_scroll'))
|
|
||||||
|
|
||||||
# max_plugin_width_ratio is the one fractional setting, so it is
|
# max_plugin_width_ratio is the one fractional setting, so it is
|
||||||
# handled outside the integer loop below.
|
# handled outside the integer loop below.
|
||||||
@@ -916,8 +954,12 @@ def save_main_config():
|
|||||||
# them AGAIN as bogus top-level config keys (e.g. "clock_duration": 30
|
# them AGAIN as bogus top-level config keys (e.g. "clock_duration": 30
|
||||||
# sitting at config root alongside the correct
|
# sitting at config root alongside the correct
|
||||||
# display.display_durations.clock_duration).
|
# display.display_durations.clock_duration).
|
||||||
|
# The Vegas cycle-time fields (vegas_min_cycle_duration, ...) share the
|
||||||
|
# suffix but are Vegas settings, already handled above: counting them
|
||||||
|
# here wrote junk mode durations, and a blank one 400'd the save.
|
||||||
duration_fields = [k for k in list(data.keys())
|
duration_fields = [k for k in list(data.keys())
|
||||||
if k.endswith('_duration') or k in ('default_duration', 'transition_duration')]
|
if (k.endswith('_duration') and k not in vegas_fields)
|
||||||
|
or k in ('default_duration', 'transition_duration')]
|
||||||
if duration_fields:
|
if duration_fields:
|
||||||
if 'display' not in current_config:
|
if 'display' not in current_config:
|
||||||
current_config['display'] = {}
|
current_config['display'] = {}
|
||||||
@@ -1162,10 +1204,27 @@ def save_raw_main_config():
|
|||||||
if not data:
|
if not data:
|
||||||
return jsonify({'status': 'error', 'message': 'No data provided'}), 400
|
return jsonify({'status': 'error', 'message': 'No data provided'}), 400
|
||||||
|
|
||||||
|
was_auto_update_enabled = False
|
||||||
|
try:
|
||||||
|
previous = api_v3.config_manager.get_raw_file_content('main') or {}
|
||||||
|
was_auto_update_enabled = bool((previous.get('auto_update') or {}).get('enabled'))
|
||||||
|
except Exception:
|
||||||
|
logger.debug("Could not read the previous auto_update setting", exc_info=True)
|
||||||
|
|
||||||
# Save the raw config file
|
# Save the raw config file
|
||||||
api_v3.config_manager.save_raw_file_content('main', data)
|
api_v3.config_manager.save_raw_file_content('main', data)
|
||||||
|
|
||||||
return jsonify({'status': 'success', 'message': 'Main configuration saved successfully'})
|
message = 'Main configuration saved successfully'
|
||||||
|
# Same hook as save_main_config: switching automatic updates on here
|
||||||
|
# must finish their setup too, not wait for the next service restart.
|
||||||
|
try:
|
||||||
|
from web_interface import auto_update
|
||||||
|
note = auto_update.start_setup_if_needed(was_auto_update_enabled, data)
|
||||||
|
if note:
|
||||||
|
message = f'{message}. {note}'
|
||||||
|
except Exception:
|
||||||
|
logger.warning("Automatic update setup could not be started", exc_info=True)
|
||||||
|
return jsonify({'status': 'success', 'message': message})
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
from src.exceptions import ConfigError
|
from src.exceptions import ConfigError
|
||||||
logger.error("Error saving raw main config", exc_info=True)
|
logger.error("Error saving raw main config", exc_info=True)
|
||||||
|
|||||||
@@ -34,6 +34,10 @@
|
|||||||
class="space-y-6"
|
class="space-y-6"
|
||||||
novalidate
|
novalidate
|
||||||
onsubmit="fixInvalidNumberInputs(this); return true;">
|
onsubmit="fixInvalidNumberInputs(this); return true;">
|
||||||
|
{# Marks this post as the whole form, so an unchecked box saves as
|
||||||
|
false. Without it the save endpoint treats absent keys as unchanged
|
||||||
|
(FORM_SECTION_FIELD in api_v3/config.py). #}
|
||||||
|
<input type="hidden" name="__form_section" value="display">
|
||||||
|
|
||||||
<!-- Hardware Settings -->
|
<!-- Hardware Settings -->
|
||||||
<div class="bg-gray-50 rounded-lg p-4">
|
<div class="bg-gray-50 rounded-lg p-4">
|
||||||
|
|||||||
@@ -15,6 +15,8 @@
|
|||||||
class="space-y-6"
|
class="space-y-6"
|
||||||
novalidate
|
novalidate
|
||||||
onsubmit="fixInvalidNumberInputs(this); return true;">
|
onsubmit="fixInvalidNumberInputs(this); return true;">
|
||||||
|
{# See general.html: identifies a whole-form post to /config/main. #}
|
||||||
|
<input type="hidden" name="__form_section" value="durations">
|
||||||
|
|
||||||
<!-- Primary rotation order: drag to reorder which plugin shows first,
|
<!-- Primary rotation order: drag to reorder which plugin shows first,
|
||||||
second, ... in the normal display rotation. Saved as
|
second, ... in the normal display rotation. Saved as
|
||||||
|
|||||||
@@ -30,6 +30,10 @@
|
|||||||
showNotification(message, status);
|
showNotification(message, status);
|
||||||
"
|
"
|
||||||
class="space-y-6">
|
class="space-y-6">
|
||||||
|
{# Marks this post as the whole form, so an unchecked box saves as
|
||||||
|
false. Without it the save endpoint treats absent keys as unchanged
|
||||||
|
(FORM_SECTION_FIELD in api_v3/config.py). #}
|
||||||
|
<input type="hidden" name="__form_section" value="general">
|
||||||
|
|
||||||
<!-- Web Display Autostart -->
|
<!-- Web Display Autostart -->
|
||||||
<div class="form-group" id="setting-general-web_display_autostart" data-setting-key="web_display_autostart">
|
<div class="form-group" id="setting-general-web_display_autostart" data-setting-key="web_display_autostart">
|
||||||
|
|||||||
Reference in New Issue
Block a user