mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-10-04 06:15:09 +00:00
* fix(sports): rebuild un-shared faces through the pinned layout engine unshare_element_fonts re-instantiates a duplicate font face so two elements can be told apart by id(). It did so through bare ImageFont.truetype, which takes PIL's default layout engine rather than the one src/common/font_layout.py pins. Raqm and Basic disagree on fractional advances -- that disagreement is the reason the pin exists, having broken golden images across machines -- so a rebuilt face could measure differently from the shared face it replaced, on any host where Raqm is installed. These were the only two call sites in src/ bypassing the pin. The guard asserts that the rebuild goes through the pinned loader rather than comparing engine values: where Raqm is absent, bare truetype returns BASIC anyway, so an engine comparison passes whether or not the pin is honoured. The first draft of this test did exactly that and passed with the bug reintroduced. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * refactor(web): drop the two dead client-side config-form renderers generateConfigForm and generateSimpleConfigForm (580 lines) were defined on the Alpine component and never called: server-side Jinja replaced them, as pages_v3.py:641 records. Nothing in any template invokes them -- there is no x-html in the templates and no bracket access on the component. They carried their own x-widget dispatch, which made them an active trap: the next person adding a widget would reasonably think both renderers needed updating. plugins/config_manager.js (PluginConfigManager, 133 lines) goes for the same reason -- loaded on every page from base.html, referenced only by itself and by an archived doc. Kept, having checked them: widgets/example-color-picker.js is the worked example docs/widget-guide.md points plugin authors at, and widgets/plugin-loader.js is the client half of a documented feature (manifest-declared plugin widgets) whose server route is missing -- soccer-scoreboard already ships a widgets/custom-leagues.js that this loader is meant to fetch. That is an unfinished feature to complete, not dead code to delete. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(web): serve plugin-declared widgets, and actually ask for them LEDMatrixWidgets.loadPluginWidget has always fetched /static/plugin-widgets/<plugin>/<widget>.js, and docs/widget-guide.md has always documented that path, but nothing served it. soccer-scoreboard has shipped a 17KB widgets/custom-leagues.js since August that could never load. Both halves were missing, not just the route: - serve_plugin_widget serves the script from the plugin's widgets/ directory as text/javascript. The manifest is the allowlist -- only a widget the plugin declares is reachable -- so installing a plugin does not publish everything it ships. Path handling mirrors the sibling serve_plugin_web_ui: allowlist regexes, os.path.basename, resolve() + relative_to() containment, and the ledmatrix- prefix fallback. The declared script name is guarded too, since it comes from the plugin rather than the request. - The config form never requested one. Its x-widget dispatch is a hardcoded list of core widget names, so a plugin's own widget fell through to a plain text input. An unrecognised x-widget on a string field now asks ensureWidget() for it. The text input stays as the fallback and is removed only once the widget has actually rendered, so a missing or broken widget costs the user an editor rather than their configured value on the next save. - manifest_schema.json gains "widgets", so the declaration is validated rather than merely tolerated by additionalProperties. Verified in a browser against the real partial: a declared widget loads, registers and renders, and its field posts exactly one value; a field whose widget 404s keeps its text input and still posts its value. Not addressed: loadPluginWidgetsFromManifest still has no caller. The per-field ensureWidget path is lazier and is what the form now uses, so that bulk helper is dead weight -- worth removing, but left alone here rather than inventing a call site for it. Known limitation, documented: only string-typed fields take this path. object/array/boolean/number fields and enums are dispatched by the template's own branches, which still only know core widgets. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(element-style): a wrong-size BDF now keeps its font, not its size BDF fonts are fixed-size bitmap strikes: FreeType accepts only the pixel size baked into the file and raises for anything else. 32 of the 35 shipped fonts are BDF, so a size picked in the web UI usually is not a valid strike -- and load_font caught that failure with its generic "unloadable font" handler, which substitutes PressStart2P. Asking for 5x7.bdf at size 10 therefore rendered a completely different typeface, silently. It now falls back to the file's own native size instead, which is what SportsCore._load_custom_font_from_element_config has always done. The native size is read via FontManager._read_bdf_native_size rather than a fourth copy of that parser, matching how core.py already delegates. Also here, because they are the same code path: - native_bdf_size() is exposed for the web UI, which needs to know when a size field can take effect at all. None means "free choice". - ElementStyle.font_size now reports the size actually realised rather than the one requested. Callers lay out from it, and reserving space for a size nothing was drawn at is how this surfaces. - The module font cache is a bounded LRU (256) instead of an unbounded dict. The display process runs for weeks and every config save can add a (font, size) pair; every other hot cache in the codebase is bounded this way. Untouched configs are unaffected: the shipped classic fonts are the three TTFs, so nothing was hitting the substitution path by default. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(element-style): per-mode style and offset overrides Lets one element be styled differently per situation -- a scoreboard's live / upcoming / recent cards, weather's current / hourly / daily screens -- under customization.modes.<mode>. The mode is bound at construction rather than passed per call. That is what makes this cheap to adopt: SportsUpcoming and SportsRecent are already separate instances with distinct SKIN_MODE values, so binding once makes every existing style()/offset_value() call site mode-aware without editing any of them. A per-call mode argument exists for the rare host that renders more than one mode. The two layers answer different questions, deliberately: - The base layer keeps the existing "differs from the schema default" rule, because the save flow writes the full default object into config.json whether or not the user touched it. - A mode layer is pure override -- its fields default to None, so presence is intent. Nothing writes into it unasked, so there is nothing for the stricter rule to protect against. None therefore means inherit, and has to stay distinct from 0: a mode y_offset of 0 means "sit at the base position", not "no preference". This is the same distinction scroll_card.switch_* draws with "inherit". A malformed mode value falls back to the resolved base value rather than to the caller's default -- caught by the degradation tests, which is what they are for: resolving the mode first let one bad string in a mode block silently discard a good base offset. With no modes block, and for every existing caller, resolution is unchanged. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(element-style): declare per-mode overrides in config_schema.json A plugin adds "x-style-modes": ["live", "upcoming", "recent"] alongside its x-style-elements declaration and gets a customization.modes.<mode> group per mode, with every field of every declared element repeated as an override. Those override fields are typed nullable and default to null, which is the whole trick. The save flow writes schema defaults into config.json wholesale, so giving a mode field the base element's default would make every mode a frozen copy of the base the first time a user pressed Save, and the base would stop reaching them. Null means inherit. The mutation test for this is explicit: with concrete defaults, a base font_size of 14 resolves as 10 with user_forced set. min/max from the declaration carry into the mode blocks, so an out-of-range override is rejected by validation rather than clamped silently at render time. Also: the emitted font field now carries "x-widget": "font-selector". The widget already shipped and the config form already allowlisted it -- the hint was simply never emitted, so the field rendered as a bare text box that the user had to type a font filename into. Verified through the real SchemaManager path -- load_schema, defaults extraction, merge_with_defaults, validation, then resolution -- rather than against a hand-built dict, since the thing at risk is what that pipeline does to a null. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): render the config form from the schema the save route validates The form read config_schema.json with a raw json.load while api_v3.save_plugin_config went through SchemaManager. Those are not the same schema: SchemaManager applies expand_style_elements, which turns a compact customization.x-style-elements declaration into the per-element blocks the form knows how to render. Without it, that customization object has an x-style-elements key and no "properties", so the template's object branch matched nothing and the section rendered as empty space -- while saving still validated against the expanded shape. of-the-day ships the compact form, so its customization section has been invisible in the web UI. pages_v3 gains a schema_manager the way it already has config_manager and plugin_manager. use_cache=False matches the save route, so an edited schema is not served stale during plugin development. The raw read stays as a fallback for callers that register this blueprint without one. Checked before making the change: load_schema does nothing here except read, validate and expand -- inject_skin_selector is a separate method it does not call -- so this is not a behaviour change for schemas without the declaration. The test pair renders the same compact schema with and without a SchemaManager, so it documents exactly what was broken as well as what is fixed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(web): style-editor widget -- a row per element instead of 65 accordions Rendered element by element, a realistic scoreboard's customization block is 65 nested sections, and reaching one per-mode font size takes five levels of expanding. The widget collapses that to one compact row per element -- font, size, colour, X, Y -- with a tab per declared mode. It emits ordinary inputs under the same dotted names the generic renderer would produce, so the save/validate/merge pipeline is untouched: no hidden JSON blob and no new server-side parsing. It is driven entirely by the schema block it is handed, so fields added to the schema later appear without editing the widget. If it fails to load or throws, the generic nested rendering it replaces is left in place. Fixing two things the save path got wrong for nullable fields, found by posting what the widget actually emits: - The indexed-array recombiner (text_color.0/.1/.2 -> one list) compared the declared type to the string 'array', so a per-mode colour, typed ["array", "null"], was never reassembled and failed validation on save. _parse_form_value_with_schema had the same comparison. - A blank nullable field became [] rather than None, which then failed the minItems the colour array declares. Null is the inherit sentinel, so it has to survive. And two things the widget itself got wrong, found by looking at it: - An unset base control fell back to the select's first option, so an untouched scoreboard claimed every element used 10x20.bdf -- and the size box then locked itself to that bitmap font's fixed size. Base controls now show the schema default; mode controls stay blank, because blank there means inherit. - Elements arrived alphabetised (Detail and Odds above Score). Flask's JSON provider sorts keys, so declaration order has to be stated explicitly; expand_style_elements now emits x-propertyOrder, which the generic renderer already honoured too. Size is disabled and shown as fixed for a bitmap font, using the scalable/native_size the font catalog now reports. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(element-style): visibility, alignment and scale per element Completes the customization vocabulary: hide an element, align it, and resize a logo, alongside the font/size/colour/offset that already existed. All three per mode. They resolve to "change nothing" until the user asks for something -- True, None and 1.0 -- rather than to whatever the schema declares. That is the same invariant the font fields keep: a caller that honours them still renders an untouched config exactly as it did before they existed. A schema default therefore does not count as a choice, which matters because the save flow writes that default into config either way. scale sits in the layout block with the offsets rather than in the element block, because it is geometry: a logo has a scale and no font. The widget's columns come from the schema, so a logo row shows visibility, offsets and scale and no empty font cell. Two bugs found by the tests rather than by reading: - A nullable enum needs null in its enum list, not just in its type. The mode copy of `align` defaulted to null and then failed its own schema, so a plugin declaring any enum field with modes could not save at all. Six tests failed on this before any of them reached what they were testing. - defaults_from_schema only ever extracted font/font_size/text_color, so the schema defaults for the new fields were invisible to the resolver and a declared default read as a user choice. Widget: the table scrolls horizontally and pins the element-name column. Nine columns do not fit the config panel, and clipping them hid the offsets entirely while scrolling them made every row anonymous. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(element-style): resolve elements under the names plugins actually use Two naming conventions collided as the scoreboards grew. Counted across the published schemas: the style block names elements with a _text suffix (score_text, status_text, detail_text), while the layout block mostly uses the bare noun (score, date, time, odds) -- except status_text, which kept the suffix in seven plugins and lost it in two. records vs record splits seven to two the same way. A lookup now tries the exact name first and then the spellings that mean the same thing. Exact-first is what makes this inert for any config that already matches; the aliases only decide cases that resolved to nothing before. This is also what makes migrating to the compact declaration form safe. That form uses one key for both blocks, so a scoreboard adopting it asks for layout.score_text while its users have layout.score saved -- without the aliases, every offset they had dialled in would silently become 0. Applies to the style block, the layout block, the schema defaults and the per-mode overrides, since the drift shows up in all four. Not attempting to canonicalise on write: renaming keys in config.json would break the plugins still reading the old spelling from their own bundled code, and the drift costs a dict miss rather than correctness. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(plugins): BasePlugin.styles -- per-element styling every plugin inherits Adopting the element-style system meant repeating three things in every plugin: a guarded import, finding its own config_schema.json, and rebuilding the resolver when on_config_change swapped the config dict. This is those three things once, on the class all 45 plugins already inherit from. title = self.styles.style('title_text', classic_font='PressStart2P-Regular.ttf', classic_size=8, classic_color=(255, 255, 255)) The classic_* arguments are the adoption contract: with nothing configured they come back verbatim, so a plugin that switches to this renders exactly as before until a user changes something. A plugin with one instance per display mode sets STYLE_MODE on the class and every existing lookup becomes mode-aware without a call site changing -- which is the point of binding the mode to the resolver rather than passing it per call. styles_for() covers a plugin that renders several modes from one instance. Schema discovery reads the concrete class's own module rather than this file, because this file lives in src/plugin_system where no plugin schema exists -- the same trap SportsCore._config_schema_path documents. The first mutation test for that passed anyway: an installed plugin's module directory and its entry under plugins_dir are the same path, so the test could not tell the two apart. The case where they diverge is a plugin symlinked in for development, and the test now forces that shape. Getting discovery wrong is silent rather than loud: with no schema the resolver has no defaults to compare against, so every configured value reads as a deliberate override and the plugin quietly stops honouring its own shipped styling. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(element-style): adopt hand-written customization blocks, and widen the font list Nineteen plugins spell their style elements out longhand instead of declaring them -- football's block is 701 lines for seven elements -- and predate this system entirely. Core now recognises that shape, so they pick up the row-per-element editor and the real font picker on a core update rather than on a plugin release. Checked against every published schema: 21 plugins adopt, and the defaults of each still validate against the schema generated for it. Detection requires *every* field in a block to be one this system understands. A looser "has at least one style field" rule sweeps in baseball's `count`, which carries a text_color beside geometry that means nothing here. That distinction took three attempts to test: the first two assertions passed under both rules, because an over-eager rule leaves a fontless block looking untouched and only surfaces as an extra row in the editor. The hardcoded font enum is replaced rather than extended. Football lists five of the thirty-five installed fonts, which is why a font a user uploads can never appear in one. It is not a curated safe set -- it omits some twenty other faces that fit the declared size cap just as well -- it is the fonts that happened to exist when it was written. Widening it does need a guard, though, and not the one the schema already has: a bitmap font ignores font_size and renders at its size baked into the file, so `maximum: 16` cannot stop a 27px face. The picker now filters out fixed-size fonts taller than the element's own declared ceiling, which drops exactly the four that would overflow a 32px panel and keeps the other thirty. Per-mode overrides stay opt-in: core cannot invent a plugin's display modes, so `x-style-modes` remains the one line that unlocks them. Their layout half covers every positionable element rather than only those with a style block -- the two namespaces do not line up in a hand-written schema, and football positions six things (logos, timeouts, possession) that have no style block at all. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * refactor(web): remove the two Fonts-tab panels that reported invented data "Element Font Overrides" let a user configure an override, showed a success toast, and changed nothing. All three endpoints behind it were stubs -- GET returned a hardcoded {}, POST and DELETE returned success without calling anything -- each marked "This would integrate with the actual font system". Wiring them to FontManager would not have fixed it. The machinery there is real (_load_overrides/_save_overrides persist config/font_overrides.json, resolve_font applies them, and the countdown plugin genuinely consumes it), but the panel's element dropdown offered eleven invented keys -- nfl.live.score, clock.time, weather.current -- that no plugin has ever read. An override saved against one of those would have persisted correctly and still done nothing. "Detected Manager Fonts" goes for the same reason. It claimed to show "fonts currently in use by managers (auto-detected)"; its own comment said "we'll simulate this", and it listed every font in the catalog with a hardcoded usage_count of 1 -- the panel beside it, with fabricated numbers attached. Per-element font choice now lives in each plugin's own config editor, against the elements that plugin actually has, and covers size, colour, offsets, visibility, alignment and scale rather than family and size. Kept: the font library (upload, preview, delete), which works, and /fonts/tokens, which is a stub but genuinely feeds the preview's size dropdown. FontManager's override methods are untouched -- countdown uses them. Verified in a browser with the tab's JS running: no console errors, 35 fonts listed, upload and preview intact. Removing the panel meant unwiring it from populateFontSelects too, which would otherwise have bailed out early on the missing select and left the preview dropdown empty. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * refactor(sports): one reader for element colours and layout offsets There were two copies of the per-element colour read and three of the layout-offset read. They had already drifted -- the scroll-card renderer carries a comment about having ignored offsets its own schema advertised -- and each new capability had to be added to all of them or silently work in some places and not others. All of them now go through src.element_style, which is what carries the alias handling and the per-mode lookup. That lands immediately for the nine plugins importing these modules: a scoreboard asking for `score_text` offsets finds the `layout.score` its users configured, and a Live instance resolves its own colours through SKIN_MODE without any call site passing a mode. _normalize_color learned "#RRGGBB" in the process. The scoreboards' own readers have always accepted it, so the shared one had to, or consolidating would have quietly dropped a form users' configs may hold. _coerce_offset picked up the non-finite guard the scroll-card reader had and the other two did not. _get_layout_offset is promoted onto SportsCoreSharedMixin. Each plugin still carries its own copy in its bundled sports.py, which wins by MRO -- so adopting this is a deletion in the plugin, and until that deletion nothing changes for it. Note for whoever runs the suite next: test_display_dirty_tracking.py is order-dependent. Fifteen of its tests failed in one full run and passed in the next with no change in between, and pass in isolation. Pre-existing, unrelated to this, but it makes a full-run diff untrustworthy until it is fixed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(changelog): record the element-style work under Unreleased This file's own preamble asks for it: a plugin may delete its bundled fallback copy of a core module only when its manifest floors on the first release that shipped that module, which requires the additions to be recorded here against a version. Names a plugin can now import and floor on -- the stateless layout_offset and element_color readers, alias_keys, native_bdf_size, the resolver's mode binding, BasePlugin.styles, and the promoted SportsCoreSharedMixin._get_layout_offset -- plus the schema and web-UI changes, the four fixes and the three removals. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(fonts): log the BDF native-size read failure instead of swallowing it The bdf-native-size lookup in get_fonts_catalog() caught any exception and silently discarded it. Every other guarded read added in this PR (the manifest parse in _declared_widget_script, the SchemaManager fallback in _load_plugin_config_partial) logs before falling through to the same degraded behavior. This one didn't, which is the shape a silent-exception-swallow lint rule flags. Behavior is unchanged -- native_size still comes back None -- but a corrupt or unreadable BDF file now leaves a trace. Verified: font-related tests (140) and the full suite still pass, with only the 2 pre-existing Europe/Kiev/Asia/Calcutta tzdata-alias failures already present on origin/main. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix: address CodeRabbit findings on the style-editor/font-selector PR - Fix _load_font_sized double-wrapping the (font, size) tuple on the missing-font path, which handed callers a tuple instead of a font. - Fix _set_nested_value skipping an explicit None when the key already existed, which silently kept stale overrides when a user cleared a nullable per-mode field or blanked all channels of an indexed color. - Preserve BDF scalable/native_size metadata through fetchFontCatalog's catalog-format mapping so maxFixedSize filtering actually applies. - Stop caching an empty array on a failed font-catalog fetch so a later call can retry instead of being stuck with the failed result. - Keep a saved font selected in the style editor even when it no longer fits a newly declared maxFixedSize, instead of silently deselecting it. - Don't drop in-progress user edits to fallback fields when a plugin widget finishes loading asynchronously and takes over the form. - Tighten the removed font-override endpoint test to assert 405, not just != 200. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): a partial save no longer switches off checkboxes it never showed An HTML checkbox posts nothing when unchecked, so the save route walked the schema and forced every boolean missing from the form to False. That is right for the rendered form and wrong for every other caller: a script, the MQTT bridge or a curl against the documented endpoint never rendered a checkbox, and reading its silence as "all off" turns a one-field save into a mass disable. Found on hardware. Posting four customization.* keys to a live device switched off nfl.enabled, ncaa_fb.enabled and every display-mode toggle in one request. The form now reports the top-level sections it drew (__rendered_section), and inside those an absent checkbox still means unchecked -- including a section whose only fields are checkboxes that are all off, which no heuristic could recover. A post with no marker only touches objects it actually posted a field from. Meta fields are dropped before form keys are treated as config paths, because unknown keys are otherwise written straight into config.json. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * feat(sports): resolve element colour by name, and honour visible/align/scale Two of the three gaps this framework shipped with. Colour by name. A draw resolved its colour by comparing the *identity* of the font object it was handed, which cannot tell two elements apart when they share a face -- so those draws went out white. Every bitmap font is in that case, because a freetype.Face cannot be re-instantiated to un-share it, which is how an element rendered in any of the 32 shipped BDF fonts silently lost a colour its picker had offered all along. _draw_text_with_outline now takes element="score_text" and reads the colour by name; the identity path remains for un-annotated callers, but narrows before giving up -- one configured colour among the sharers is the only thing the user can have meant. Visible, align and scale. The resolver has understood these since the framework landed and nothing consumed them: an element could be marked hidden in the web UI and still render. Adds the stateless readers, the mixin accessors, and a scale parameter on the one shared logo-sizing seam (keyed into the cache, so two elements scaled differently cannot be served each other's image). Naming an element in a draw also honours its visibility. Untouched configs are unaffected: every new parameter defaults to today's behaviour, and all ten affected plugins render pixel-identically to main across every harness size. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * docs(plugins): how to declare styleable elements; harden the widget's lookups The plugin-author guide for the compact x-style-elements declaration -- what each key does, how to read values back without breaking the "user-forced only when it differs from the default" rule, and why a hand-written block needs no changes to be adopted. Also clears the static-analysis findings on style-editor.js. Every lookup in that file is keyed by something out of a schema or a saved config, so a key of __proto__ or constructor would walk the prototype chain and hand back a function instead of a schema; reads now go through an own-property helper. The panel registry became a list, and the flagged vars moved to their function roots. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): clear the remaining static-analysis findings Five, all on lines this branch touched. The Python one is not a new defect: _set_missing_booleans_to_false's first parameter was always named `config`, which shadows the `config` submodule imported for its side effects at the bottom of this module. Editing the signature simply put the existing warning on a changed line. The parameter is the plugin's config dict, so `plugin_config` is what it should have been called anyway; callers pass it positionally and are unaffected. The JavaScript ones are the object-injection rule firing on reads keyed by data. own() now goes through a property descriptor, so the one unavoidable data-keyed read is no longer a computed member access; at() consumes its path instead of indexing it; and the column set is a Map, which has no prototype to pollute and needs no guarded reads at all. Verified the widget still renders identically against football's real schema: 29 element rows, all four mode tabs, values populated, no console errors. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(web): drop the hasOwnProperty alias the descriptor read made redundant own() now reads through Object.getOwnPropertyDescriptor, so the alias it used to call has no remaining reference. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
999 lines
44 KiB
Python
999 lines
44 KiB
Python
from flask import Blueprint, render_template, flash, jsonify
|
|
from jinja2 import TemplateNotFound
|
|
from markupsafe import escape
|
|
from html.parser import HTMLParser
|
|
import json
|
|
import logging
|
|
import re
|
|
from pathlib import Path
|
|
|
|
# Strict allowlists for URL-derived values used in path and script operations.
|
|
_SAFE_PLUGIN_ID_RE = re.compile(r'^[a-zA-Z0-9_-]{1,64}$')
|
|
_SAFE_WEB_UI_FILE_RE = re.compile(r'^[a-zA-Z0-9_-]{1,64}\.html$')
|
|
_SAFE_WIDGET_NAME_RE = re.compile(r'^[a-zA-Z0-9_-]{1,64}$')
|
|
_SAFE_WIDGET_SCRIPT_RE = re.compile(r'^[a-zA-Z0-9_-]{1,64}\.js$')
|
|
from src.web_interface.secret_helpers import mask_secret_fields
|
|
from src.common.path_safety import resolve_under, safe_path_component
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Will be initialized when blueprint is registered
|
|
config_manager = None
|
|
plugin_manager = None
|
|
plugin_store_manager = None
|
|
schema_manager = None
|
|
|
|
pages_v3 = Blueprint('pages_v3', __name__)
|
|
|
|
|
|
class _SettingsIndexParser(HTMLParser):
|
|
"""Extract searchable settings fields from a rendered partial's HTML.
|
|
|
|
Captures one entry per ``<div class="form-group" id="setting-…">``: the
|
|
anchor id, ``data-setting-key``, the field's ``<label>`` text, the
|
|
``.help-tip`` tooltip text (``data-tooltip``), and the nearest preceding
|
|
``<h3>``/``<h4>`` section heading. Parsing the *rendered* HTML (rather than
|
|
the schema) guarantees the anchor ids match the live DOM exactly, so the
|
|
search index cannot drift from what users actually see.
|
|
"""
|
|
|
|
def __init__(self, tab, tab_label):
|
|
super().__init__(convert_charrefs=True)
|
|
self.tab = tab
|
|
self.tab_label = tab_label
|
|
self.fields = []
|
|
self._section = ''
|
|
self._field = None
|
|
self._depth = 0 # open-div depth within the current field
|
|
self._in_label = False
|
|
self._label_parts = []
|
|
self._in_heading = False
|
|
self._heading_parts = []
|
|
|
|
def handle_starttag(self, tag, attrs):
|
|
a = {k: (v or '') for k, v in attrs}
|
|
classes = a.get('class', '').split()
|
|
# Section headings (only when not already inside a field)
|
|
if tag in ('h3', 'h4') and self._field is None:
|
|
self._in_heading = True
|
|
self._heading_parts = []
|
|
if tag == 'div':
|
|
fid = a.get('id', '')
|
|
if self._field is None and 'form-group' in classes and fid.startswith('setting-'):
|
|
self._field = {
|
|
'anchorId': fid,
|
|
'key': a.get('data-setting-key', '') or fid[len('setting-'):],
|
|
'label': '',
|
|
'help': '',
|
|
'section': self._section,
|
|
'tab': self.tab,
|
|
'tabLabel': self.tab_label,
|
|
}
|
|
self._depth = 1
|
|
return
|
|
if self._field is not None:
|
|
self._depth += 1
|
|
if self._field is not None:
|
|
if tag == 'label' and not self._field['label']:
|
|
self._in_label = True
|
|
self._label_parts = []
|
|
if tag == 'button' and 'help-tip' in classes and not self._field['help']:
|
|
self._field['help'] = a.get('data-tooltip', '')
|
|
|
|
def handle_data(self, data):
|
|
if self._in_label:
|
|
self._label_parts.append(data)
|
|
elif self._in_heading:
|
|
self._heading_parts.append(data)
|
|
|
|
def handle_endtag(self, tag):
|
|
if tag in ('h3', 'h4') and self._in_heading:
|
|
self._in_heading = False
|
|
self._section = ' '.join(''.join(self._heading_parts).split()).strip()
|
|
return
|
|
if self._field is None:
|
|
return
|
|
if tag == 'label' and self._in_label:
|
|
self._in_label = False
|
|
self._field['label'] = ' '.join(''.join(self._label_parts).split()).strip()
|
|
elif tag == 'div':
|
|
self._depth -= 1
|
|
if self._depth <= 0:
|
|
if self._field['label']:
|
|
self.fields.append(self._field)
|
|
self._field = None
|
|
self._depth = 0
|
|
|
|
|
|
def _partial_html(loader):
|
|
"""Run a partial loader and return its HTML string ('' on error)."""
|
|
try:
|
|
result = loader()
|
|
except Exception:
|
|
logger.warning("search-index: partial render failed", exc_info=True)
|
|
return ''
|
|
if isinstance(result, str):
|
|
return result
|
|
if isinstance(result, tuple): # loaders return (msg, status) on error
|
|
return ''
|
|
try:
|
|
return result.get_data(as_text=True)
|
|
except Exception:
|
|
return ''
|
|
|
|
|
|
def _extract_settings_fields(html, tab, tab_label):
|
|
parser = _SettingsIndexParser(tab, tab_label)
|
|
parser.feed(html)
|
|
return parser.fields
|
|
|
|
|
|
# Cache the built index keyed on the installed-plugin set. Core labels/tooltips
|
|
# are static template text, so only a change in installed plugins invalidates it.
|
|
_SEARCH_INDEX_CACHE = {'sig': None, 'fields': None}
|
|
|
|
|
|
@pages_v3.route('/')
|
|
def index():
|
|
"""Main v3 interface page"""
|
|
try:
|
|
if pages_v3.config_manager:
|
|
# Load configuration data
|
|
main_config = pages_v3.config_manager.load_config()
|
|
schedule_config = main_config.get('schedule', {})
|
|
|
|
# Get raw config files for JSON editor
|
|
main_config_data = pages_v3.config_manager.get_raw_file_content('main')
|
|
secrets_config_data = pages_v3.config_manager.get_raw_file_content('secrets')
|
|
main_config_json = json.dumps(main_config_data, indent=4)
|
|
secrets_config_json = json.dumps(secrets_config_data, indent=4)
|
|
else:
|
|
raise Exception("Config manager not initialized")
|
|
|
|
except Exception as e:
|
|
flash(f"Error loading configuration: {e}", "error")
|
|
schedule_config = {}
|
|
main_config_json = "{}"
|
|
secrets_config_json = "{}"
|
|
main_config_data = {}
|
|
secrets_config_data = {}
|
|
|
|
return render_template('v3/index.html',
|
|
schedule_config=schedule_config,
|
|
main_config_json=main_config_json,
|
|
secrets_config_json=secrets_config_json,
|
|
main_config_path=pages_v3.config_manager.get_config_path() if pages_v3.config_manager else "",
|
|
secrets_config_path=pages_v3.config_manager.get_secrets_path() if pages_v3.config_manager else "",
|
|
main_config=main_config_data,
|
|
secrets_config=secrets_config_data)
|
|
|
|
@pages_v3.route('/partials/<partial_name>')
|
|
def load_partial(partial_name):
|
|
"""Load HTMX partials dynamically"""
|
|
try:
|
|
# Map partial names to specific data loading
|
|
if partial_name == 'overview':
|
|
return _load_overview_partial()
|
|
elif partial_name == 'general':
|
|
return _load_general_partial()
|
|
elif partial_name == 'display':
|
|
return _load_display_partial()
|
|
elif partial_name == 'durations':
|
|
return _load_durations_partial()
|
|
elif partial_name == 'schedule':
|
|
return _load_schedule_partial()
|
|
elif partial_name == 'plugins':
|
|
return _load_plugins_partial()
|
|
elif partial_name == 'fonts':
|
|
return _load_fonts_partial()
|
|
elif partial_name == 'logs':
|
|
return _load_logs_partial()
|
|
elif partial_name == 'raw-json':
|
|
return _load_raw_json_partial()
|
|
elif partial_name == 'backup-restore':
|
|
return _load_backup_restore_partial()
|
|
elif partial_name == 'wifi':
|
|
return _load_wifi_partial()
|
|
elif partial_name == 'cache':
|
|
return _load_cache_partial()
|
|
elif partial_name == 'operation-history':
|
|
return _load_operation_history_partial()
|
|
elif partial_name == 'tools':
|
|
return _load_tools_partial()
|
|
else:
|
|
return "Partial not found", 404
|
|
|
|
except Exception as e:
|
|
logger.error("Error loading partial %s", partial_name, exc_info=True)
|
|
return "Error loading partial", 500
|
|
|
|
|
|
@pages_v3.route('/partials/plugin-config/<plugin_id>')
|
|
def load_plugin_config_partial(plugin_id):
|
|
"""Load plugin configuration partial via HTMX - server-side rendered form"""
|
|
try:
|
|
return _load_plugin_config_partial(plugin_id)
|
|
except Exception:
|
|
logger.error("Error loading plugin config partial for %s", plugin_id, exc_info=True)
|
|
return '<div class="text-red-500 p-4">Error loading plugin config; see logs for details</div>', 500
|
|
|
|
|
|
@pages_v3.route('/settings/search-index')
|
|
def settings_search_index():
|
|
"""Return a flat JSON index of every searchable setting (core + plugin).
|
|
|
|
Powers the web UI's global settings search. Built by rendering the settings
|
|
partials server-side and extracting field metadata, then cached per
|
|
installed-plugin set so it is off the display's hot path.
|
|
"""
|
|
# Core settings tabs: (activeTab value, human label, loader).
|
|
core_tabs = [
|
|
('general', 'General', _load_general_partial),
|
|
('display', 'Display', _load_display_partial),
|
|
('durations', 'Durations', _load_durations_partial),
|
|
('schedule', 'Schedule', _load_schedule_partial),
|
|
('wifi', 'WiFi', _load_wifi_partial),
|
|
]
|
|
try:
|
|
plugin_ids = []
|
|
if pages_v3.plugin_manager:
|
|
try:
|
|
pages_v3.plugin_manager.discover_plugins()
|
|
plugin_ids = sorted(
|
|
pi.get('id') for pi in pages_v3.plugin_manager.get_all_plugin_info()
|
|
if pi.get('id')
|
|
)
|
|
except Exception:
|
|
logger.warning("search-index: could not enumerate plugins", exc_info=True)
|
|
|
|
sig = tuple(plugin_ids)
|
|
if _SEARCH_INDEX_CACHE['sig'] == sig and _SEARCH_INDEX_CACHE['fields'] is not None:
|
|
return jsonify({'fields': _SEARCH_INDEX_CACHE['fields']})
|
|
|
|
fields = []
|
|
for tab, label, loader in core_tabs:
|
|
fields.extend(_extract_settings_fields(_partial_html(loader), tab, label))
|
|
|
|
for pid in plugin_ids:
|
|
info = pages_v3.plugin_manager.get_plugin_info(pid) or {}
|
|
label = info.get('name', pid)
|
|
html = _partial_html(lambda pid=pid: _load_plugin_config_partial(pid))
|
|
fields.extend(_extract_settings_fields(html, pid, label))
|
|
|
|
_SEARCH_INDEX_CACHE['sig'] = sig
|
|
_SEARCH_INDEX_CACHE['fields'] = fields
|
|
return jsonify({'fields': fields})
|
|
except Exception:
|
|
logger.error("Error building settings search index", exc_info=True)
|
|
return jsonify({'fields': []}), 500
|
|
|
|
|
|
@pages_v3.route('/plugin-ui/<plugin_id>/web-ui/<path:filename>')
|
|
def serve_plugin_web_ui(plugin_id, filename):
|
|
"""Serve a plugin's web_ui/ HTML fragment as a standalone page.
|
|
|
|
Wraps the fragment with a minimal HTML page that injects window.PLUGIN_ID
|
|
and loads Tailwind CSS so the fragment runs correctly inside the iframe
|
|
that plugin_config.html embeds it in.
|
|
|
|
That iframe carries no ``sandbox`` attribute, so the fragment runs with
|
|
the interface's own origin. That is deliberate rather than an oversight:
|
|
the fragment is a file from an installed plugin, and an installed plugin
|
|
already runs Python on the device. The trust boundary is plugin install,
|
|
not this route. It is worth knowing when reading the code, which is why
|
|
it says so here instead of claiming a sandbox that is not there.
|
|
"""
|
|
# Validate URL-derived values against strict allowlists before any path or
|
|
# script operations.
|
|
if not _SAFE_PLUGIN_ID_RE.match(plugin_id):
|
|
return 'Invalid plugin ID', 400, {'Content-Type': 'text/plain'}
|
|
if not _SAFE_WEB_UI_FILE_RE.match(filename):
|
|
return 'Invalid filename', 400, {'Content-Type': 'text/plain'}
|
|
|
|
# The allowlists above already forbid a separator, but the value that gets
|
|
# joined has to be the checked one, not the argument -- see
|
|
# src/common/path_safety.py. safe_path_component rejects rather than
|
|
# truncates, so these cannot disagree.
|
|
safe_id = safe_path_component(plugin_id)
|
|
safe_fn = safe_path_component(filename)
|
|
if not safe_id or not safe_fn:
|
|
return 'Invalid path component', 400, {'Content-Type': 'text/plain'}
|
|
|
|
if not pages_v3.plugin_manager:
|
|
return 'Plugin manager not available', 503, {'Content-Type': 'text/plain'}
|
|
|
|
try:
|
|
_plugins_base = Path(pages_v3.plugin_manager.plugins_dir).resolve()
|
|
|
|
_plugin_dir = resolve_under(_plugins_base, safe_id)
|
|
if _plugin_dir is None:
|
|
return 'Forbidden', 403, {'Content-Type': 'text/plain'}
|
|
|
|
# Mirror PluginManager's ledmatrix- prefix fallback.
|
|
if not _plugin_dir.exists():
|
|
_alt = resolve_under(_plugins_base, f'ledmatrix-{safe_id}')
|
|
if _alt is not None:
|
|
_plugin_dir = _alt
|
|
|
|
web_ui_path = resolve_under(_plugin_dir / 'web_ui', safe_fn)
|
|
if web_ui_path is None:
|
|
return 'Forbidden', 403, {'Content-Type': 'text/plain'}
|
|
|
|
if not web_ui_path.exists():
|
|
return 'Not found', 404, {'Content-Type': 'text/plain'}
|
|
|
|
fragment = web_ui_path.read_text(encoding='utf-8')
|
|
|
|
# json.dumps wraps the value in quotes. Replace HTML meta-chars with
|
|
# their JS Unicode escape sequences so the value cannot close or escape
|
|
# the enclosing <script> tag.
|
|
# r'<' is the 6-char literal string <, which JavaScript
|
|
# interprets as <. This is the standard JSON-in-HTML hardening pattern.
|
|
safe_plugin_id_js = (
|
|
json.dumps(safe_id)
|
|
.replace('<', '\\u003c')
|
|
.replace('>', '\\u003e')
|
|
.replace('&', '\\u0026')
|
|
)
|
|
|
|
page = (
|
|
'<!DOCTYPE html>\n'
|
|
'<html lang="en">\n'
|
|
'<head>\n'
|
|
'<meta charset="UTF-8">\n'
|
|
'<meta name="viewport" content="width=device-width,initial-scale=1">\n'
|
|
'<script>\n'
|
|
# Inject plugin context before the fragment runs.
|
|
# plugin_id is validated to [a-zA-Z0-9_-] above, so this is safe,
|
|
# but we also Unicode-escape HTML meta-chars as defence in depth.
|
|
f' window.PLUGIN_ID = {safe_plugin_id_js};\n'
|
|
'</script>\n'
|
|
# Tailwind v2 CDN — same version used by the parent LEDMatrix UI
|
|
'<link rel="stylesheet" '
|
|
'href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" '
|
|
'crossorigin="anonymous">\n'
|
|
'<style>body{margin:0;padding:0;background:#fff;}</style>\n'
|
|
'</head>\n'
|
|
'<body>\n'
|
|
+ fragment +
|
|
'\n</body>\n</html>'
|
|
)
|
|
return page, 200, {'Content-Type': 'text/html; charset=utf-8'}
|
|
|
|
except ValueError:
|
|
return 'Forbidden', 403, {'Content-Type': 'text/plain'}
|
|
except Exception:
|
|
logger.error('Error serving plugin web_ui %s/%s', plugin_id, filename, exc_info=True)
|
|
return 'Error serving file', 500, {'Content-Type': 'text/plain'}
|
|
|
|
|
|
def _plugin_dir_for(safe_id):
|
|
"""Resolve a sanitised plugin id to its directory, or None.
|
|
|
|
Mirrors serve_plugin_web_ui: containment-guarded against the configured
|
|
plugins directory, with PluginManager's ``ledmatrix-`` prefix fallback.
|
|
"""
|
|
plugins_base = Path(pages_v3.plugin_manager.plugins_dir).resolve()
|
|
plugin_dir = resolve_under(plugins_base, safe_id)
|
|
if plugin_dir is None:
|
|
raise ValueError('plugin id escapes the plugins directory')
|
|
|
|
if not plugin_dir.exists():
|
|
alt = resolve_under(plugins_base, f'ledmatrix-{safe_id}')
|
|
if alt is not None:
|
|
plugin_dir = alt
|
|
return plugin_dir
|
|
|
|
|
|
def _declared_widget_script(plugin_dir, widget_name):
|
|
"""The script filename a plugin's manifest declares for ``widget_name``.
|
|
|
|
The manifest is the allowlist: only a widget the plugin actually declares
|
|
can be served, so this route never exposes arbitrary files under the
|
|
plugin directory even though the directory itself is attacker-influenced
|
|
(plugins are user-installed). Returns None when the widget is not
|
|
declared, the manifest is unreadable, or the declared script name is not
|
|
a plain ``<name>.js`` basename.
|
|
"""
|
|
manifest_path = plugin_dir / 'manifest.json'
|
|
try:
|
|
with open(manifest_path, 'r', encoding='utf-8') as f:
|
|
manifest = json.load(f)
|
|
except (OSError, ValueError):
|
|
return None
|
|
if not isinstance(manifest, dict):
|
|
return None
|
|
|
|
for entry in manifest.get('widgets') or ():
|
|
if not isinstance(entry, dict):
|
|
continue
|
|
if entry.get('name') != widget_name:
|
|
continue
|
|
script = entry.get('script') or f'{widget_name}.js'
|
|
if not isinstance(script, str) or not _SAFE_WIDGET_SCRIPT_RE.match(script):
|
|
return None
|
|
return script
|
|
return None
|
|
|
|
|
|
@pages_v3.route('/static/plugin-widgets/<plugin_id>/<widget_name>.js')
|
|
def serve_plugin_widget(plugin_id, widget_name):
|
|
"""Serve a plugin-declared widget script from its ``widgets/`` directory.
|
|
|
|
This is the server half of ``LEDMatrixWidgets.loadPluginWidget`` (see
|
|
static/v3/js/widgets/plugin-loader.js), which fetches exactly this path.
|
|
The loader uses a dynamic ``import()``, so the response must carry a
|
|
JavaScript MIME type or the browser refuses the module.
|
|
|
|
The route is deliberately narrower than the plugin directory: a script is
|
|
served only when the plugin's own manifest declares a widget by that name,
|
|
so installing a plugin does not publish everything it ships.
|
|
"""
|
|
if not _SAFE_PLUGIN_ID_RE.match(plugin_id):
|
|
return 'Invalid plugin ID', 400, {'Content-Type': 'text/plain'}
|
|
if not _SAFE_WIDGET_NAME_RE.match(widget_name):
|
|
return 'Invalid widget name', 400, {'Content-Type': 'text/plain'}
|
|
|
|
# safe_path_component is this codebase's sanitiser (src/common/
|
|
# path_safety.py): it rejects rather than mangles, so a name that is not
|
|
# a plain path component never reaches the filesystem.
|
|
safe_id = safe_path_component(plugin_id)
|
|
safe_widget = safe_path_component(widget_name)
|
|
if not safe_id or not safe_widget:
|
|
return 'Invalid path component', 400, {'Content-Type': 'text/plain'}
|
|
|
|
if not pages_v3.plugin_manager:
|
|
return 'Plugin manager not available', 503, {'Content-Type': 'text/plain'}
|
|
|
|
try:
|
|
plugin_dir = _plugin_dir_for(safe_id)
|
|
if not plugin_dir.exists():
|
|
return 'Not found', 404, {'Content-Type': 'text/plain'}
|
|
|
|
script = _declared_widget_script(plugin_dir, safe_widget)
|
|
if script is None:
|
|
# Undeclared is a 404 rather than a 403: whether a plugin happens
|
|
# to ship an undeclared file is not something to confirm.
|
|
return 'Not found', 404, {'Content-Type': 'text/plain'}
|
|
|
|
widgets_dir = (plugin_dir / 'widgets').resolve()
|
|
# The script name comes from the plugin's manifest, not the request,
|
|
# so it gets the same containment treatment the URL parts got.
|
|
script_path = resolve_under(widgets_dir, script)
|
|
if script_path is None or not script_path.is_file():
|
|
return 'Not found', 404, {'Content-Type': 'text/plain'}
|
|
|
|
body = script_path.read_text(encoding='utf-8')
|
|
return body, 200, {
|
|
'Content-Type': 'text/javascript; charset=utf-8',
|
|
# Plugin updates replace this file in place; revalidate so a
|
|
# stale widget cannot outlive the plugin version that shipped it.
|
|
'Cache-Control': 'no-cache',
|
|
}
|
|
|
|
except ValueError:
|
|
return 'Forbidden', 403, {'Content-Type': 'text/plain'}
|
|
except Exception:
|
|
logger.error('Error serving plugin widget %s/%s', plugin_id, widget_name,
|
|
exc_info=True)
|
|
return 'Error serving file', 500, {'Content-Type': 'text/plain'}
|
|
|
|
|
|
def _load_overview_partial():
|
|
"""Load overview partial with system stats"""
|
|
try:
|
|
if pages_v3.config_manager:
|
|
main_config = pages_v3.config_manager.load_config()
|
|
# This would be populated with real system stats via SSE
|
|
return render_template('v3/partials/overview.html',
|
|
main_config=main_config)
|
|
except Exception as e:
|
|
logger.error("Error loading partial", exc_info=True)
|
|
return "Error loading partial", 500
|
|
|
|
def _load_general_partial():
|
|
"""Load general settings partial"""
|
|
try:
|
|
if pages_v3.config_manager:
|
|
main_config = pages_v3.config_manager.load_config()
|
|
return render_template('v3/partials/general.html',
|
|
main_config=main_config)
|
|
except Exception as e:
|
|
logger.error("Error loading partial", exc_info=True)
|
|
return "Error loading partial", 500
|
|
|
|
def _load_display_partial():
|
|
"""Load display settings partial"""
|
|
try:
|
|
if pages_v3.config_manager:
|
|
main_config = pages_v3.config_manager.load_config()
|
|
return render_template('v3/partials/display.html',
|
|
main_config=main_config)
|
|
except Exception as e:
|
|
logger.error("Error loading partial", exc_info=True)
|
|
return "Error loading partial", 500
|
|
|
|
def _load_durations_partial():
|
|
"""Load rotation & durations partial.
|
|
|
|
Builds one duration entry per display mode of every enabled plugin
|
|
(falling back to the display controller's 30s default), overlaid with any
|
|
values saved in display.display_durations. Historically the template only
|
|
looped over saved keys, and nothing ever populated them, so the page
|
|
rendered empty.
|
|
"""
|
|
try:
|
|
if pages_v3.config_manager:
|
|
main_config = pages_v3.config_manager.load_config()
|
|
duration_groups = []
|
|
covered_keys = set()
|
|
if pages_v3.plugin_manager:
|
|
try:
|
|
pages_v3.plugin_manager.discover_plugins()
|
|
saved = (main_config.get('display', {}) or {}).get('display_durations', {}) or {}
|
|
infos = sorted(pages_v3.plugin_manager.get_all_plugin_info(),
|
|
key=lambda i: (i.get('name') or i.get('id') or '').lower())
|
|
for info in infos:
|
|
pid = info.get('id')
|
|
if not pid or not (main_config.get(pid, {}) or {}).get('enabled', False):
|
|
continue
|
|
modes = pages_v3.plugin_manager.get_plugin_display_modes(pid) or [pid]
|
|
covered_keys.update(modes)
|
|
duration_groups.append({
|
|
'plugin_id': pid,
|
|
'plugin_name': info.get('name') or pid,
|
|
'modes': [{'key': m, 'value': saved.get(m, 30)} for m in modes],
|
|
})
|
|
# Saved keys not owned by any enabled plugin (disabled or
|
|
# uninstalled plugins) stay visible rather than vanishing.
|
|
leftovers = [{'key': k, 'value': v} for k, v in saved.items()
|
|
if k not in covered_keys]
|
|
if leftovers:
|
|
duration_groups.append({
|
|
'plugin_id': '',
|
|
'plugin_name': 'Other saved entries',
|
|
'modes': leftovers,
|
|
})
|
|
except Exception:
|
|
logger.warning("durations: could not enumerate plugin modes", exc_info=True)
|
|
return render_template('v3/partials/durations.html',
|
|
main_config=main_config,
|
|
duration_groups=duration_groups)
|
|
except Exception as e:
|
|
logger.error("Error loading partial", exc_info=True)
|
|
return "Error loading partial", 500
|
|
|
|
def _load_schedule_partial():
|
|
"""Load schedule settings partial"""
|
|
try:
|
|
if pages_v3.config_manager:
|
|
main_config = pages_v3.config_manager.load_config()
|
|
schedule_config = main_config.get('schedule', {})
|
|
dim_schedule_config = main_config.get('dim_schedule', {})
|
|
# Get normal brightness for display in dim schedule UI
|
|
normal_brightness = main_config.get('display', {}).get('hardware', {}).get('brightness', 90)
|
|
return render_template('v3/partials/schedule.html',
|
|
schedule_config=schedule_config,
|
|
dim_schedule_config=dim_schedule_config,
|
|
normal_brightness=normal_brightness)
|
|
except Exception as e:
|
|
logger.error("Error loading partial", exc_info=True)
|
|
return "Error loading partial", 500
|
|
|
|
|
|
def _load_plugins_partial():
|
|
"""Load plugins management partial"""
|
|
try:
|
|
import json
|
|
from pathlib import Path
|
|
|
|
# Load plugin data from the plugin system
|
|
plugins_data = []
|
|
|
|
# Get installed plugins if managers are available
|
|
if pages_v3.plugin_manager and pages_v3.plugin_store_manager:
|
|
try:
|
|
# Get all installed plugin info
|
|
all_plugin_info = pages_v3.plugin_manager.get_all_plugin_info()
|
|
|
|
# Load config once before the loop (not per-plugin)
|
|
full_config = pages_v3.config_manager.load_config() if pages_v3.config_manager else {}
|
|
|
|
# Format for the web interface
|
|
for plugin_info in all_plugin_info:
|
|
plugin_id = plugin_info.get('id')
|
|
|
|
# Re-read manifest from disk to ensure we have the latest metadata
|
|
manifest_path = Path(pages_v3.plugin_manager.plugins_dir) / plugin_id / "manifest.json"
|
|
if manifest_path.exists():
|
|
try:
|
|
with open(manifest_path, 'r', encoding='utf-8') as f:
|
|
fresh_manifest = json.load(f)
|
|
# Update plugin_info with fresh manifest data
|
|
plugin_info.update(fresh_manifest)
|
|
except Exception as e:
|
|
# If we can't read the fresh manifest, use the cached one
|
|
logger.warning("Could not read fresh manifest for plugin: %s", plugin_id)
|
|
|
|
# Get enabled status from config (source of truth)
|
|
# Read from config file first, fall back to plugin instance if config doesn't have the key
|
|
enabled = None
|
|
if pages_v3.config_manager:
|
|
plugin_config = full_config.get(plugin_id, {})
|
|
# Check if 'enabled' key exists in config (even if False)
|
|
if 'enabled' in plugin_config:
|
|
enabled = bool(plugin_config['enabled'])
|
|
|
|
# Fallback to plugin instance if config doesn't have enabled key
|
|
if enabled is None:
|
|
plugin_instance = pages_v3.plugin_manager.get_plugin(plugin_id)
|
|
if plugin_instance:
|
|
enabled = plugin_instance.enabled
|
|
else:
|
|
# Default to True if no config key and plugin not loaded (matches BasePlugin default)
|
|
enabled = True
|
|
|
|
# Get verified status from store registry (no GitHub API calls needed)
|
|
store_info = pages_v3.plugin_store_manager.get_registry_info(plugin_id)
|
|
verified = store_info.get('verified', False) if store_info else False
|
|
|
|
last_updated = plugin_info.get('last_updated')
|
|
last_commit = plugin_info.get('last_commit') or plugin_info.get('last_commit_sha')
|
|
branch = plugin_info.get('branch')
|
|
|
|
if store_info:
|
|
last_updated = last_updated or store_info.get('last_updated') or store_info.get('last_updated_iso')
|
|
last_commit = last_commit or store_info.get('last_commit') or store_info.get('last_commit_sha')
|
|
branch = branch or store_info.get('branch') or store_info.get('default_branch')
|
|
|
|
plugins_data.append({
|
|
'id': plugin_id,
|
|
'name': plugin_info.get('name', plugin_id),
|
|
'author': plugin_info.get('author', 'Unknown'),
|
|
'category': plugin_info.get('category', 'General'),
|
|
'description': plugin_info.get('description', 'No description available'),
|
|
'tags': plugin_info.get('tags', []),
|
|
'enabled': enabled,
|
|
'verified': verified,
|
|
'loaded': plugin_info.get('loaded', False),
|
|
'last_updated': last_updated,
|
|
'last_commit': last_commit,
|
|
'branch': branch
|
|
})
|
|
except Exception as e:
|
|
logger.error("Error loading plugin data", exc_info=True)
|
|
|
|
return render_template('v3/partials/plugins.html',
|
|
plugins=plugins_data)
|
|
except Exception as e:
|
|
logger.error("Error loading partial", exc_info=True)
|
|
return "Error loading partial", 500
|
|
|
|
def _load_fonts_partial():
|
|
"""Load fonts management partial"""
|
|
try:
|
|
# This would load font data from the font system
|
|
fonts_data = {} # Placeholder for font data
|
|
return render_template('v3/partials/fonts.html',
|
|
fonts=fonts_data)
|
|
except Exception as e:
|
|
logger.error("Error loading partial", exc_info=True)
|
|
return "Error loading partial", 500
|
|
|
|
def _load_logs_partial():
|
|
"""Load logs viewer partial"""
|
|
try:
|
|
return render_template('v3/partials/logs.html')
|
|
except Exception as e:
|
|
logger.error("Error loading partial", exc_info=True)
|
|
return "Error loading partial", 500
|
|
|
|
def _load_raw_json_partial():
|
|
"""Load raw JSON editor partial"""
|
|
try:
|
|
if pages_v3.config_manager:
|
|
main_config_data = pages_v3.config_manager.get_raw_file_content('main')
|
|
secrets_config_data = pages_v3.config_manager.get_raw_file_content('secrets')
|
|
main_config_json = json.dumps(main_config_data, indent=4)
|
|
secrets_config_json = json.dumps(secrets_config_data, indent=4)
|
|
|
|
return render_template('v3/partials/raw_json.html',
|
|
main_config_json=main_config_json,
|
|
secrets_config_json=secrets_config_json,
|
|
main_config_path=pages_v3.config_manager.get_config_path(),
|
|
secrets_config_path=pages_v3.config_manager.get_secrets_path())
|
|
except Exception as e:
|
|
logger.error("Error loading partial", exc_info=True)
|
|
return "Error loading partial", 500
|
|
|
|
def _load_backup_restore_partial():
|
|
"""Load backup & restore partial."""
|
|
try:
|
|
return render_template('v3/partials/backup_restore.html')
|
|
except Exception as e:
|
|
logger.error("Error loading partial", exc_info=True)
|
|
return "Error loading partial", 500
|
|
|
|
@pages_v3.route('/setup')
|
|
def captive_setup():
|
|
"""Lightweight captive portal setup page — self-contained, no frameworks."""
|
|
return render_template('v3/captive_setup.html')
|
|
|
|
def _load_wifi_partial():
|
|
"""Load WiFi setup partial"""
|
|
try:
|
|
return render_template('v3/partials/wifi.html')
|
|
except Exception as e:
|
|
logger.error("Error loading partial", exc_info=True)
|
|
return "Error loading partial", 500
|
|
|
|
def _load_cache_partial():
|
|
"""Load cache management partial"""
|
|
try:
|
|
return render_template('v3/partials/cache.html')
|
|
except Exception as e:
|
|
logger.error("Error loading partial", exc_info=True)
|
|
return "Error loading partial", 500
|
|
|
|
def _load_operation_history_partial():
|
|
"""Load operation history partial"""
|
|
try:
|
|
return render_template('v3/partials/operation_history.html')
|
|
except Exception as e:
|
|
logger.error("Error loading partial", exc_info=True)
|
|
return "Error loading partial", 500
|
|
|
|
|
|
def _load_tools_partial():
|
|
"""Load tools/utilities partial."""
|
|
try:
|
|
return render_template('v3/partials/tools.html')
|
|
except TemplateNotFound:
|
|
logger.error("[Pages V3][Tools] Template not found: v3/partials/tools.html", exc_info=True)
|
|
return "[Pages V3][Tools] Template is missing.", 500
|
|
except OSError as exc:
|
|
logger.error("[Pages V3][Tools] I/O error loading tools partial: %s", exc, exc_info=True)
|
|
return "[Pages V3][Tools] Failed to load due to a file system error. Check logs.", 500
|
|
|
|
|
|
def _load_plugin_config_partial(plugin_id):
|
|
"""
|
|
Load plugin configuration partial - server-side rendered form.
|
|
This replaces the client-side generateConfigForm() JavaScript.
|
|
"""
|
|
# Refuse an id that is not a plain directory name, rather than quietly
|
|
# basename-ing it down to one: "../weather" used to become "weather" and
|
|
# render a partial the caller never asked for.
|
|
plugin_id = safe_path_component(plugin_id)
|
|
if not plugin_id or not re.match(r'^[a-zA-Z0-9][a-zA-Z0-9._\-:]*$', plugin_id):
|
|
return '<div class="text-red-500 p-4">Invalid plugin ID</div>', 400
|
|
|
|
try:
|
|
if not pages_v3.plugin_manager:
|
|
return '<div class="text-red-500 p-4">Plugin manager not available</div>', 500
|
|
|
|
# Handle starlark app config (starlark:<app_id>)
|
|
if plugin_id.startswith('starlark:'):
|
|
return _load_starlark_config_partial(plugin_id[len('starlark:'):])
|
|
|
|
# Resolve and validate all plugin paths against the plugins base directory
|
|
_plugins_base = Path(pages_v3.plugin_manager.plugins_dir).resolve()
|
|
_plugin_dir = resolve_under(_plugins_base, plugin_id)
|
|
if _plugin_dir is None:
|
|
return '<div class="text-red-500 p-4">Invalid plugin ID</div>', 400
|
|
|
|
# Try to get plugin info first
|
|
plugin_info = pages_v3.plugin_manager.get_plugin_info(plugin_id)
|
|
|
|
# If not found, re-discover plugins (handles plugins added after startup)
|
|
if not plugin_info:
|
|
pages_v3.plugin_manager.discover_plugins()
|
|
plugin_info = pages_v3.plugin_manager.get_plugin_info(plugin_id)
|
|
|
|
if not plugin_info:
|
|
return '<div class="text-red-500 p-4">Plugin not found</div>', 404
|
|
|
|
# Get plugin instance (may be None if not loaded)
|
|
plugin_instance = pages_v3.plugin_manager.get_plugin(plugin_id)
|
|
|
|
# Get plugin configuration from config file
|
|
config = {}
|
|
if pages_v3.config_manager:
|
|
full_config = pages_v3.config_manager.load_config()
|
|
config = full_config.get(plugin_id, {})
|
|
|
|
# Load uploaded images from metadata file if images field exists in schema
|
|
schema_path_temp = resolve_under(_plugin_dir, "config_schema.json")
|
|
if schema_path_temp is not None and schema_path_temp.exists():
|
|
try:
|
|
with open(schema_path_temp, 'r', encoding='utf-8') as f:
|
|
temp_schema = json.load(f)
|
|
if (temp_schema.get('properties', {}).get('images', {}).get('x-widget') == 'file-upload' or
|
|
temp_schema.get('properties', {}).get('images', {}).get('x_widget') == 'file-upload'):
|
|
_assets_base = (Path(__file__).parent.parent.parent / 'assets' / 'plugins').resolve()
|
|
metadata_file = resolve_under(
|
|
_assets_base, plugin_id, 'uploads', '.metadata.json'
|
|
)
|
|
if metadata_file and metadata_file.exists():
|
|
try:
|
|
with open(metadata_file, 'r', encoding='utf-8') as mf:
|
|
metadata = json.load(mf)
|
|
images_from_metadata = list(metadata.values())
|
|
if not config.get('images') or len(config.get('images', [])) == 0:
|
|
config['images'] = images_from_metadata
|
|
else:
|
|
config_image_ids = {img.get('id') for img in config.get('images', []) if img.get('id')}
|
|
new_images = [img for img in images_from_metadata if img.get('id') not in config_image_ids]
|
|
if new_images:
|
|
config['images'] = config.get('images', []) + new_images
|
|
except Exception as e:
|
|
logger.warning("Could not load plugin upload metadata: %s", e)
|
|
except Exception as e: # nosec B110 - metadata pre-load is optional; schema loads fully below
|
|
logger.debug("Metadata pre-load skipped for plugin %s: %s", plugin_id, e)
|
|
|
|
# Get plugin schema.
|
|
#
|
|
# Through SchemaManager, not a raw json.load, because that is what
|
|
# the save route uses (api_v3.save_plugin_config) -- and the two
|
|
# disagreeing is not academic. SchemaManager applies
|
|
# expand_style_elements, which turns a compact
|
|
# customization.x-style-elements declaration into the per-element
|
|
# blocks this form renders. Reading the file directly meant a plugin
|
|
# using that form (of-the-day ships one) had a customization section
|
|
# that rendered nothing at all, while saving still validated against
|
|
# the expanded shape.
|
|
#
|
|
# use_cache=False matches the save route: a plugin's schema changes
|
|
# on disk during development, and a cached copy would keep serving
|
|
# the old form.
|
|
#
|
|
# The raw read stays as a fallback for callers that never set a
|
|
# schema_manager (several tests, and any embedder of this blueprint).
|
|
schema = {}
|
|
schema_mgr = getattr(pages_v3, 'schema_manager', None)
|
|
if schema_mgr is not None:
|
|
try:
|
|
schema = schema_mgr.load_schema(plugin_id, use_cache=False) or {}
|
|
except Exception as e:
|
|
logger.warning("SchemaManager could not load schema for %s: %s",
|
|
plugin_id, e)
|
|
if not schema:
|
|
# resolve_under keeps the containment guard main added here; the
|
|
# SchemaManager path above does its own.
|
|
schema_path = resolve_under(_plugin_dir, "config_schema.json")
|
|
if schema_path is not None and schema_path.exists():
|
|
try:
|
|
with open(schema_path, 'r', encoding='utf-8') as f:
|
|
schema = json.load(f)
|
|
except Exception as e:
|
|
logger.warning("Could not load schema for plugin: %s", e)
|
|
|
|
# Get web UI actions from plugin manifest
|
|
web_ui_actions = []
|
|
manifest_path = resolve_under(_plugin_dir, "manifest.json")
|
|
if manifest_path is not None and manifest_path.exists():
|
|
try:
|
|
with open(manifest_path, 'r', encoding='utf-8') as f:
|
|
manifest = json.load(f)
|
|
web_ui_actions = manifest.get('web_ui_actions', [])
|
|
except Exception as e:
|
|
logger.warning("Could not load manifest for plugin: %s", e)
|
|
|
|
# Mask secret fields before rendering template (fail closed — never leak secrets)
|
|
schema_properties = schema.get('properties') if isinstance(schema, dict) else None
|
|
if not isinstance(schema_properties, dict):
|
|
return '<div class="text-red-500 p-4">Error loading plugin config securely: schema unavailable.</div>', 500
|
|
config = mask_secret_fields(config, schema_properties)
|
|
|
|
# Determine enabled status
|
|
enabled = config.get('enabled', True)
|
|
if plugin_instance:
|
|
enabled = plugin_instance.enabled
|
|
|
|
# Build plugin data for template
|
|
plugin_data = {
|
|
'id': plugin_id,
|
|
'name': plugin_info.get('name', plugin_id),
|
|
'author': plugin_info.get('author', 'Unknown'),
|
|
'version': plugin_info.get('version', ''),
|
|
'description': plugin_info.get('description', ''),
|
|
'category': plugin_info.get('category', 'General'),
|
|
'tags': plugin_info.get('tags', []),
|
|
'enabled': enabled,
|
|
'last_commit': plugin_info.get('last_commit') or plugin_info.get('last_commit_sha', ''),
|
|
'branch': plugin_info.get('branch', ''),
|
|
}
|
|
|
|
return render_template(
|
|
'v3/partials/plugin_config.html',
|
|
plugin=plugin_data,
|
|
config=config,
|
|
schema=schema,
|
|
web_ui_actions=web_ui_actions
|
|
)
|
|
|
|
except Exception as e:
|
|
logger.error("Error loading plugin config partial for %s", plugin_id, exc_info=True)
|
|
return '<div class="text-red-500 p-4">Error loading plugin config; see logs for details</div>', 500
|
|
|
|
|
|
def _load_starlark_config_partial(app_id):
|
|
"""Load configuration partial for a Starlark app."""
|
|
# Refuse an id that is not a plain directory name rather than basename-ing
|
|
# it down to one -- see _load_plugin_config_partial for why.
|
|
app_id = safe_path_component(app_id)
|
|
if not app_id or not re.match(r'^[a-zA-Z0-9][a-zA-Z0-9_\-]*$', app_id):
|
|
return '<div class="text-red-500 p-4">Invalid app ID</div>', 400
|
|
|
|
try:
|
|
starlark_plugin = pages_v3.plugin_manager.get_plugin('starlark-apps') if pages_v3.plugin_manager else None
|
|
|
|
if starlark_plugin and hasattr(starlark_plugin, 'apps'):
|
|
app = starlark_plugin.apps.get(app_id)
|
|
if not app:
|
|
return '<div class="text-red-500 p-4">Starlark app not found</div>', 404
|
|
return render_template(
|
|
'v3/partials/starlark_config.html',
|
|
app_id=app_id,
|
|
app_name=app.manifest.get('name', app_id),
|
|
app_enabled=app.is_enabled(),
|
|
render_interval=app.get_render_interval(),
|
|
display_duration=app.get_display_duration(),
|
|
config=app.config,
|
|
schema=app.schema,
|
|
has_frames=app.frames is not None,
|
|
frame_count=len(app.frames) if app.frames else 0,
|
|
last_render_time=app.last_render_time,
|
|
)
|
|
|
|
# Standalone: read from manifest file
|
|
starlark_base = (Path(__file__).resolve().parent.parent.parent / 'starlark-apps').resolve()
|
|
manifest_file = starlark_base / 'manifest.json'
|
|
if not manifest_file.exists():
|
|
return '<div class="text-red-500 p-4">Starlark app not found</div>', 404
|
|
|
|
with open(manifest_file, 'r') as f:
|
|
manifest = json.load(f)
|
|
|
|
app_data = manifest.get('apps', {}).get(app_id)
|
|
if not app_data:
|
|
return '<div class="text-red-500 p-4">Starlark app not found</div>', 404
|
|
|
|
# Load schema from schema.json if it exists — validate path stays within starlark_base
|
|
schema = None
|
|
schema_file = resolve_under(starlark_base, app_id, 'schema.json')
|
|
if schema_file and schema_file.exists():
|
|
try:
|
|
with open(schema_file, 'r') as f:
|
|
schema = json.load(f)
|
|
except (OSError, json.JSONDecodeError) as e:
|
|
logger.warning("Could not load starlark schema for app: %s", e)
|
|
|
|
# Load config from config.json if it exists — validate path stays within starlark_base
|
|
config = {}
|
|
config_file = resolve_under(starlark_base, app_id, 'config.json')
|
|
if config_file and config_file.exists():
|
|
try:
|
|
with open(config_file, 'r') as f:
|
|
config = json.load(f)
|
|
except (OSError, json.JSONDecodeError) as e:
|
|
logger.warning("Could not load starlark config for app: %s", e)
|
|
|
|
return render_template(
|
|
'v3/partials/starlark_config.html',
|
|
app_id=app_id,
|
|
app_name=app_data.get('name', app_id),
|
|
app_enabled=app_data.get('enabled', True),
|
|
render_interval=app_data.get('render_interval', 300),
|
|
display_duration=app_data.get('display_duration', 15),
|
|
config=config,
|
|
schema=schema,
|
|
has_frames=False,
|
|
frame_count=0,
|
|
last_render_time=None,
|
|
)
|
|
|
|
except Exception as e:
|
|
logger.error("[Pages V3] Error loading starlark config for app", exc_info=True)
|
|
return '<div class="text-red-500 p-4">Error loading starlark config; see logs for details</div>', 500
|