fix(providers): address CodeRabbit review feedback and strengthen Awtrix adapter

This commit is contained in:
Rob Walsh committed 2026-11-05 14:21:19 -07:00
1 parent f9920b0df0
commit 4cc6150dc8
9 files changed
+432 -101

No files matched your search

+7 -4
View File
@@ -177,7 +177,7 @@ sequenceDiagram
### Live Architecture Details
* **Target Hub**: REST API at `AWTRIX_URL` (e.g. `http://192.168.1.15:7080`).
* **Native Geometry**: 64×32 pixels (`2,048` total pixels).
* **Frame Endpoint**: `GET /api/v1/display/screen` returns a 2,048-element JSON array of 24-bit integers formatted as `0xRRGGBB` (`(r << 16) | (g << 8) | b`).
* **Frame Endpoint**: `GET /api/v1/display/screen` returns a JSON object containing `width` (64), `height` (32), and a `pixels` array of 2,048 row-major 24-bit integers formatted as `0xRRGGBB` (`(r << 16) | (g << 8) | b`).
* **Frame Performance**: Average HTTP request latency over local LAN is **~24.2 ms** (delivering up to 40 FPS).
### App Discovery & Classification
@@ -216,14 +216,17 @@ AWTRIX NG schemas use native data types that do not match Pixlet schemas. The ad
| AWTRIX NG Schema Field | Translated Pixlet Schema Control | Notes / Transformations |
| :--- | :--- | :--- |
| `bool` | `schema.Toggle` | Maps `true` / `false`. |
| `select` | `schema.Dropdown` | Maps options with values and labels. |
| `select` | `schema.Dropdown` | Maps options with values and labels (numeric options converted on `PATCH`). |
| `color` | `schema.Color` | Converts `#RRGGBB` hex string &harr; 24-bit RGB int (`16711680`). |
| `days` | `schema.Dropdown` | Prepopulates week range options (`All Days`, `Weekdays`, etc.). |
| `days` | `schema.Text` | Not translated to a dropdown. Uses the default text control. |
| `string` / `text` | `schema.Text` | Direct string entry. |
| `int` / `float` | `schema.Text` or `schema.Dropdown` | Validated and converted back to numbers on `PATCH`. |
| `number` / `slider` | `schema.Text` | Converted to a number on `PATCH`. Other types keep their submitted value type. |
The schema translator also incorporates an embedded human-readable dictionary providing user-friendly titles and field descriptions for common AWTRIX configuration parameters (e.g., `showSeconds`, `calendarIcon`, `appEffect`, `textColor`).
> [!NOTE]
> **Timezone Behavior**: AWTRIX clock apps display time based on the AWTRIX hub's configured timezone. `RenderAppChunks` does not alter the hub-wide timezone during rendering to avoid disrupting other devices sharing the hub.
---
## 6. Rendering, Caching, and Serving Pipeline
+238 -75
View File
@@ -9,6 +9,7 @@ import (
"image"
"io"
"log/slog"
"net"
"net/http"
"net/url"
"strings"
@@ -29,6 +30,7 @@ type AdapterConfig struct {
ScaleFilter string
Layout string
HTTPClient *http.Client
Semaphore chan struct{}
}
// AwtrixAdapter implements providers.ExternalAppProvider for AWTRIX NG.
@@ -41,7 +43,7 @@ type AwtrixAdapter struct {
httpClient *http.Client
}
// NewAdapter creates a new AwtrixAdapter.
// NewAdapter creates a new AwtrixAdapter with safe transport dials and redirect checks.
func NewAdapter(cfg AdapterConfig) *AwtrixAdapter {
baseURL := strings.TrimRight(cfg.BaseURL, "/")
if baseURL == "" {
@@ -59,13 +61,49 @@ func NewAdapter(cfg AdapterConfig) *AwtrixAdapter {
if layout == "" {
layout = "center"
}
safeDialContext := func(ctx context.Context, network, addr string) (net.Conn, error) {
host, _, err := net.SplitHostPort(addr)
if err != nil {
host = addr
}
if ip := net.ParseIP(host); ip != nil {
if providers.IsBlockedMetadataIP(ip) {
return nil, fmt.Errorf("connection to prohibited IP %s blocked", ip)
}
} else if ips, err := net.DefaultResolver.LookupIP(ctx, "ip", host); err == nil {
for _, ip := range ips {
if providers.IsBlockedMetadataIP(ip) {
return nil, fmt.Errorf("connection to prohibited IP %s blocked", ip)
}
}
}
d := &net.Dialer{Timeout: 5 * time.Second}
return d.DialContext(ctx, network, addr)
}
httpClient := cfg.HTTPClient
if httpClient == nil {
httpClient = &http.Client{Timeout: 10 * time.Second}
httpClient = &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
DialContext: safeDialContext,
},
}
}
if httpClient.CheckRedirect == nil {
httpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return errors.New("HTTP redirects are not permitted for external provider requests")
}
}
sem := cfg.Semaphore
if sem == nil {
sem = make(chan struct{}, 1)
}
return &AwtrixAdapter{
sem: make(chan struct{}, 1),
sem: sem,
baseURL: baseURL,
fps: fps,
scaleFilter: scaleFilter,
@@ -74,6 +112,11 @@ func NewAdapter(cfg AdapterConfig) *AwtrixAdapter {
}
}
// Semaphore returns the adapter's concurrency synchronization channel.
func (a *AwtrixAdapter) Semaphore() chan struct{} {
return a.sem
}
// Name returns the provider's unique identifier.
func (a *AwtrixAdapter) Name() string {
return "awtrix"
@@ -145,11 +188,12 @@ func (a *AwtrixAdapter) ListApps(ctx context.Context) ([]providers.ExternalAppMe
}
result = append(result, providers.ExternalAppMeta{
ID: item.Name,
Name: name,
Summary: summary,
Desc: desc,
Author: author,
ID: item.Name,
Name: name,
Summary: summary,
Desc: desc,
Author: author,
Disabled: !item.Enabled,
})
}
@@ -160,8 +204,8 @@ func (a *AwtrixAdapter) ListApps(ctx context.Context) ([]providers.ExternalAppMe
func (a *AwtrixAdapter) GetAppSchema(ctx context.Context, appID string) ([]byte, error) {
cfg, isBuiltin, err := a.fetchAppConfig(ctx, appID)
if err != nil {
slog.Warn("Failed to fetch awtrix app config, returning empty schema", "app", appID, "error", err)
return []byte(`{"version":"1","schema":[]}`), nil
slog.Warn("Failed to fetch awtrix app config, returning schema with layout defaults", "app", appID, "error", err)
return TranslateAwtrixSchema(AwtrixConfigResponse{}, false)
}
return TranslateAwtrixSchema(*cfg, isBuiltin)
@@ -218,6 +262,7 @@ type screenData struct {
}
// RenderAppChunks configures the app on AWTRIX NG, captures virtual screen frames, and encodes them into WebP chunks.
// Note: AWTRIX clock apps display time based on the AWTRIX hub's configured timezone; req.Timezone does not override the hub-wide setting.
func (a *AwtrixAdapter) RenderAppChunks(ctx context.Context, req providers.RenderRequest) ([]providers.RenderChunk, error) {
// Acquire semaphore to ensure exclusive access to the Awtrix virtual display
select {
@@ -229,27 +274,47 @@ func (a *AwtrixAdapter) RenderAppChunks(ctx context.Context, req providers.Rende
// 1. Query original settings so we can reliably restore them on exit
type awtrixSettingsResp struct {
AutoTransition *bool `json:"autoTransition,omitempty"`
TransitionDurationMs *int `json:"transitionDurationMs,omitempty"`
AutoTransition *bool `json:"autoTransition"`
TransitionDurationMs *int `json:"transitionDurationMs"`
}
var origSettings awtrixSettingsResp
settingsURL := fmt.Sprintf("%s/api/v1/settings", a.baseURL)
if sReq, err := http.NewRequestWithContext(ctx, http.MethodGet, settingsURL, nil); err == nil {
if sResp, err := a.httpClient.Do(sReq); err == nil {
_ = json.NewDecoder(sResp.Body).Decode(&origSettings)
_, _ = io.Copy(io.Discard, io.LimitReader(sResp.Body, 1024))
_ = sResp.Body.Close()
}
sReq, err := http.NewRequestWithContext(ctx, http.MethodGet, settingsURL, nil)
if err != nil {
return nil, fmt.Errorf("creating settings request: %w", err)
}
sResp, err := a.httpClient.Do(sReq)
if err != nil {
return nil, fmt.Errorf("fetching awtrix settings: %w", err)
}
if sResp.StatusCode != http.StatusOK {
_, _ = io.Copy(io.Discard, io.LimitReader(sResp.Body, 1024))
_ = sResp.Body.Close()
return nil, fmt.Errorf("fetching awtrix settings returned status %d", sResp.StatusCode)
}
decodeErr := json.NewDecoder(sResp.Body).Decode(&origSettings)
_, _ = io.Copy(io.Discard, io.LimitReader(sResp.Body, 1024))
_ = sResp.Body.Close()
if decodeErr != nil || origSettings.AutoTransition == nil {
return nil, fmt.Errorf("invalid awtrix settings response (autoTransition required): %w", decodeErr)
}
// Ensure AWTRIX auto-transition and display settings are always restored when rendering completes or aborts
var (
origFieldValues map[string]any
configPatchURL string
configPatched bool
origCurrentApp string
activated bool
)
// Ensure AWTRIX auto-transition, app configuration, and active app are restored when rendering completes or aborts
defer func() {
cleanupCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
restoreMap := map[string]any{"autoTransition": true}
if origSettings.AutoTransition != nil {
restoreMap["autoTransition"] = *origSettings.AutoTransition
// 1. Restore display settings
restoreMap := map[string]any{
"autoTransition": *origSettings.AutoTransition,
}
if origSettings.TransitionDurationMs != nil {
restoreMap["transitionDurationMs"] = *origSettings.TransitionDurationMs
@@ -257,46 +322,111 @@ func (a *AwtrixAdapter) RenderAppChunks(ctx context.Context, req providers.Rende
if b, err := json.Marshal(restoreMap); err == nil {
if rReq, err := http.NewRequestWithContext(cleanupCtx, http.MethodPatch, settingsURL, bytes.NewReader(b)); err == nil {
rReq.Header.Set("Content-Type", "application/json")
if rResp, err := a.httpClient.Do(rReq); err == nil {
if rResp, err := a.httpClient.Do(rReq); err != nil {
slog.Warn("Failed to restore awtrix display settings", "error", err)
} else {
if rResp.StatusCode < 200 || rResp.StatusCode >= 300 {
slog.Warn("Awtrix display settings restore returned non-2xx status", "status", rResp.StatusCode)
}
_, _ = io.Copy(io.Discard, io.LimitReader(rResp.Body, 1024))
_ = rResp.Body.Close()
}
}
}
// 2. Restore app configuration if modified
if configPatched && len(origFieldValues) > 0 && configPatchURL != "" {
if b, err := json.Marshal(origFieldValues); err == nil {
if rReq, err := http.NewRequestWithContext(cleanupCtx, http.MethodPatch, configPatchURL, bytes.NewReader(b)); err == nil {
rReq.Header.Set("Content-Type", "application/json")
if rResp, err := a.httpClient.Do(rReq); err != nil {
slog.Warn("Failed to restore awtrix app configuration", "error", err)
} else {
if rResp.StatusCode < 200 || rResp.StatusCode >= 300 {
slog.Warn("Awtrix app configuration restore returned non-2xx status", "status", rResp.StatusCode)
}
_, _ = io.Copy(io.Discard, io.LimitReader(rResp.Body, 1024))
_ = rResp.Body.Close()
}
}
}
}
// 3. Restore previously active app if activation succeeded and differed from target
if activated && origCurrentApp != "" && origCurrentApp != req.AppID {
activateURL := fmt.Sprintf("%s/api/v1/apps/active", a.baseURL)
if b, err := json.Marshal(map[string]string{"name": origCurrentApp}); err == nil {
if rReq, err := http.NewRequestWithContext(cleanupCtx, http.MethodPut, activateURL, bytes.NewReader(b)); err == nil {
rReq.Header.Set("Content-Type", "application/json")
if rResp, err := a.httpClient.Do(rReq); err != nil {
slog.Warn("Failed to restore previous awtrix active app", "app", origCurrentApp, "error", err)
} else {
if rResp.StatusCode < 200 || rResp.StatusCode >= 300 {
slog.Warn("Awtrix active app restore returned non-2xx status", "status", rResp.StatusCode)
}
_, _ = io.Copy(io.Discard, io.LimitReader(rResp.Body, 1024))
_ = rResp.Body.Close()
}
}
}
}
}()
// 2. If custom configuration options were provided, apply them via PATCH
if len(req.Config) > 0 {
if cfg, isBuiltin, err := a.fetchAppConfig(ctx, req.AppID); err == nil && len(cfg.Fields) > 0 {
origFieldValues = make(map[string]any)
for _, f := range cfg.Fields {
if f.Value != nil {
origFieldValues[f.Key] = f.Value
}
}
patchBody := ConvertUserConfigToAwtrix(cfg.Fields, req.Config)
if len(patchBody) > 0 {
patchURL := fmt.Sprintf("%s/api/v1/apps/builtin/%s/config", a.baseURL, url.PathEscape(req.AppID))
configPatchURL = fmt.Sprintf("%s/api/v1/apps/builtin/%s/config", a.baseURL, url.PathEscape(req.AppID))
if !isBuiltin {
patchURL = fmt.Sprintf("%s/api/v1/apps/%s/config", a.baseURL, url.PathEscape(req.AppID))
configPatchURL = fmt.Sprintf("%s/api/v1/apps/%s/config", a.baseURL, url.PathEscape(req.AppID))
}
bodyBytes, err := json.Marshal(patchBody)
if err == nil {
pReq, err := http.NewRequestWithContext(ctx, http.MethodPatch, patchURL, bytes.NewReader(bodyBytes))
if err == nil {
pReq.Header.Set("Content-Type", "application/json")
if pResp, err := a.httpClient.Do(pReq); err == nil {
_, _ = io.Copy(io.Discard, io.LimitReader(pResp.Body, 1024))
_ = pResp.Body.Close()
}
}
if err != nil {
return nil, fmt.Errorf("encoding awtrix config patch: %w", err)
}
pReq, err := http.NewRequestWithContext(ctx, http.MethodPatch, configPatchURL, bytes.NewReader(bodyBytes))
if err != nil {
return nil, fmt.Errorf("creating awtrix config patch request: %w", err)
}
pReq.Header.Set("Content-Type", "application/json")
pResp, err := a.httpClient.Do(pReq)
if err != nil {
return nil, fmt.Errorf("patching awtrix app config: %w", err)
}
pStatusCode := pResp.StatusCode
_, _ = io.Copy(io.Discard, io.LimitReader(pResp.Body, 1024))
_ = pResp.Body.Close()
if pStatusCode < 200 || pStatusCode >= 300 {
return nil, fmt.Errorf("patching awtrix app config returned status %d", pStatusCode)
}
configPatched = true
}
}
}
// 3. Freeze AWTRIX auto-rotation and disable transitions so only this single app renders
freezeBody := []byte(`{"autoTransition":false,"transitionDurationMs":0}`)
if fReq, err := http.NewRequestWithContext(ctx, http.MethodPatch, settingsURL, bytes.NewReader(freezeBody)); err == nil {
fReq.Header.Set("Content-Type", "application/json")
if fResp, err := a.httpClient.Do(fReq); err == nil {
_, _ = io.Copy(io.Discard, io.LimitReader(fResp.Body, 1024))
_ = fResp.Body.Close()
}
fReq, err := http.NewRequestWithContext(ctx, http.MethodPatch, settingsURL, bytes.NewReader(freezeBody))
if err != nil {
return nil, fmt.Errorf("creating freeze request: %w", err)
}
fReq.Header.Set("Content-Type", "application/json")
fResp, err := a.httpClient.Do(fReq)
if err != nil {
return nil, fmt.Errorf("freezing awtrix display: %w", err)
}
fStatusCode := fResp.StatusCode
_, _ = io.Copy(io.Discard, io.LimitReader(fResp.Body, 1024))
_ = fResp.Body.Close()
if fStatusCode != http.StatusOK {
return nil, fmt.Errorf("freezing awtrix display returned status %d", fStatusCode)
}
// 4. Activate the app on the AWTRIX display
@@ -311,12 +441,15 @@ func (a *AwtrixAdapter) RenderAppChunks(ctx context.Context, req providers.Rende
var devInfo struct {
CurrentApp string `json:"currentApp"`
}
if json.NewDecoder(dResp.Body).Decode(&devInfo) == nil && devInfo.CurrentApp == req.AppID {
nextURL := fmt.Sprintf("%s/api/v1/apps/next", a.baseURL)
if nReq, err := http.NewRequestWithContext(ctx, http.MethodPost, nextURL, nil); err == nil {
if nResp, err := a.httpClient.Do(nReq); err == nil {
_, _ = io.Copy(io.Discard, io.LimitReader(nResp.Body, 1024))
_ = nResp.Body.Close()
if json.NewDecoder(dResp.Body).Decode(&devInfo) == nil {
origCurrentApp = devInfo.CurrentApp
if devInfo.CurrentApp == req.AppID {
nextURL := fmt.Sprintf("%s/api/v1/apps/next", a.baseURL)
if nReq, err := http.NewRequestWithContext(ctx, http.MethodPost, nextURL, nil); err == nil {
if nResp, err := a.httpClient.Do(nReq); err == nil {
_, _ = io.Copy(io.Discard, io.LimitReader(nResp.Body, 1024))
_ = nResp.Body.Close()
}
}
}
}
@@ -336,11 +469,13 @@ func (a *AwtrixAdapter) RenderAppChunks(ctx context.Context, req providers.Rende
if err != nil {
return nil, fmt.Errorf("activating awtrix app: %w", err)
}
actStatusCode := actResp.StatusCode
_, _ = io.Copy(io.Discard, io.LimitReader(actResp.Body, 1024))
_ = actResp.Body.Close()
if actResp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("activating awtrix app returned status %d", actResp.StatusCode)
if actStatusCode != http.StatusOK {
return nil, fmt.Errorf("activating awtrix app returned status %d", actStatusCode)
}
activated = true
// Wait 150ms for initial layout rendering
select {
@@ -349,7 +484,7 @@ func (a *AwtrixAdapter) RenderAppChunks(ctx context.Context, req providers.Rende
return nil, ctx.Err()
}
// 4. Determine capture parameters
// 5. Determine capture parameters
fps := req.FPS
if fps <= 0 {
fps = a.fps
@@ -380,11 +515,9 @@ func (a *AwtrixAdapter) RenderAppChunks(ctx context.Context, req providers.Rende
layoutMode = "center"
}
var frames []*image.RGBA
var layoutDetermined bool
var detectedLayout layoutInfo
var rawFrames []*image.RGBA
// 5. Capture frames
// 6. Capture frames
ticker := time.NewTicker(frameInterval)
defer ticker.Stop()
@@ -418,18 +551,22 @@ func (a *AwtrixAdapter) RenderAppChunks(ctx context.Context, req providers.Rende
}
continue
}
consecutiveErrors = 0
var sd screenData
decodeErr := json.NewDecoder(sResp.Body).Decode(&sd)
decodeErr := json.NewDecoder(io.LimitReader(sResp.Body, 1024*1024)).Decode(&sd)
_, _ = io.Copy(io.Discard, io.LimitReader(sResp.Body, 4096))
_ = sResp.Body.Close()
if decodeErr != nil || sd.Width <= 0 || sd.Height <= 0 || len(sd.Pixels) != sd.Width*sd.Height {
if decodeErr != nil || sd.Width <= 0 || sd.Width > 256 || sd.Height <= 0 || sd.Height > 256 || len(sd.Pixels) != sd.Width*sd.Height {
consecutiveErrors++
if consecutiveErrors >= 5 {
return nil, errors.New("awtrix screen frame decoding failed repeatedly or returned invalid dimensions")
}
continue
}
consecutiveErrors = 0
// Convert pixel array to image.RGBA (row-major 64x32)
// Convert pixel array to image.RGBA (row-major)
img := image.NewRGBA(image.Rect(0, 0, sd.Width, sd.Height))
for idx, pix := range sd.Pixels {
offset := idx * 4
@@ -439,31 +576,57 @@ func (a *AwtrixAdapter) RenderAppChunks(ctx context.Context, req providers.Rende
img.Pix[offset+3] = 0xFF
}
// Determine layout mode on the first frame with visible content
if !layoutDetermined && layoutMode != "native" && sd.Width == 64 && sd.Height == 32 {
if info, ok := detectLayoutInfo(img); ok {
layoutDetermined = true
detectedLayout = info
}
}
if sd.Width == 64 && sd.Height == 32 {
img = applyAwtrixLayout(img, detectedLayout, layoutMode)
}
img = fitToTargetCanvas(img, req.Width, req.Height, layoutMode, detectedLayout, a.scaleFilter)
frames = append(frames, img)
rawFrames = append(rawFrames, img)
}
if len(frames) == 0 {
if len(rawFrames) == 0 {
return nil, errors.New("no frames captured from awtrix screen")
}
// 5. Partition frames into WebP chunk(s)
// Determine layout mode across all captured frames to avoid partial-frame misclassification
var detectedLayout layoutInfo
if layoutMode != "native" {
detectedLayout = detectLayoutAcrossFrames(rawFrames)
}
frames := make([]*image.RGBA, 0, len(rawFrames))
for _, raw := range rawFrames {
img := raw
if raw.Bounds().Dx() == 64 && raw.Bounds().Dy() == 32 {
img = applyAwtrixLayout(img, detectedLayout, layoutMode)
}
img = fitToTargetCanvas(img, req.Width, req.Height, layoutMode, detectedLayout, a.scaleFilter)
frames = append(frames, img)
}
// 7. Partition frames into WebP chunk(s)
return chunker.SplitFramesIntoChunksWithDuration(frames, fps, req.MaxChunkSize, req.MaxChunkDurationMs, durationMs)
}
// detectLayoutAcrossFrames scans all captured frames to determine the most accurate layout,
// prioritizing full 32-row content over 16-row or 8-row modes.
func detectLayoutAcrossFrames(frames []*image.RGBA) layoutInfo {
var best layoutInfo
found := false
for _, frame := range frames {
if info, ok := detectLayoutInfo(frame); ok {
if !found {
best = info
found = true
}
// 32row always takes highest precedence over 16row and 8row
if info.mode == "32row" {
return info
}
// 16row takes precedence over 8row
if (info.mode == "16row-full" || info.mode == "16row-narrow") && best.mode == "8row" {
best = info
}
}
}
return best
}
type layoutInfo struct {
mode string // "8row", "16row-narrow", "16row-full", "32row"
bgColor [4]byte // R, G, B, A
+121
View File
@@ -6,6 +6,7 @@ import (
"image"
"net/http"
"net/http/httptest"
"sync"
"testing"
"tronbyt-server/internal/providers"
@@ -108,8 +109,31 @@ func TestAwtrixAdapter_GetAppSchema(t *testing.T) {
func TestAwtrixAdapter_RenderAppChunks(t *testing.T) {
activated := false
var settingsPatches []map[string]any
var mu sync.Mutex
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v1/settings":
if r.Method == http.MethodGet {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"autoTransition":true,"transitionDurationMs":5000}`))
return
}
if r.Method == http.MethodPatch {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
mu.Lock()
settingsPatches = append(settingsPatches, body)
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"ok":true}`))
return
}
http.Error(w, "bad method", http.StatusMethodNotAllowed)
case "/api/v1/device":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"currentApp":"OtherApp"}`))
case "/api/v1/apps/active":
assert.Equal(t, http.MethodPut, r.Method)
activated = true
@@ -153,6 +177,15 @@ func TestAwtrixAdapter_RenderAppChunks(t *testing.T) {
assert.True(t, activated, "App should have been activated via PUT")
require.NotEmpty(t, chunks)
assert.NotEmpty(t, chunks[0].WebPBytes)
// Verify freeze and restore PATCHes
mu.Lock()
defer mu.Unlock()
require.Len(t, settingsPatches, 2, "Expected freeze PATCH followed by restore PATCH")
assert.Equal(t, false, settingsPatches[0]["autoTransition"])
assert.Equal(t, float64(0), settingsPatches[0]["transitionDurationMs"])
assert.Equal(t, true, settingsPatches[1]["autoTransition"])
assert.Equal(t, float64(5000), settingsPatches[1]["transitionDurationMs"])
}
func TestConvertUserConfigToAwtrix(t *testing.T) {
@@ -433,3 +466,91 @@ func TestFitToTargetCanvas_ZeroDimensions(t *testing.T) {
detectLayoutInfo(emptyImg)
})
}
func TestAwtrixAdapter_GetAppSchema_FallbackOnFetchError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "server down", http.StatusInternalServerError)
}))
defer server.Close()
adapter := NewAdapter(AdapterConfig{
BaseURL: server.URL,
})
schemaBytes, err := adapter.GetAppSchema(context.Background(), "BrokenApp")
require.NoError(t, err)
var schema PixletSchema
require.NoError(t, json.Unmarshal(schemaBytes, &schema))
assert.Equal(t, "1", schema.Version)
require.NotEmpty(t, schema.Schema)
hasLayout := false
for _, f := range schema.Schema {
if f.ID == "_layout" {
hasLayout = true
break
}
}
assert.True(t, hasLayout, "Fallback schema must include _layout field")
}
func TestAwtrixAdapter_ListApps_DisabledField(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode([]awtrixAppItem{
{Name: "ActiveApp", Enabled: true, Present: true},
{Name: "InactiveApp", Enabled: false, Present: true},
})
}))
defer server.Close()
adapter := NewAdapter(AdapterConfig{
BaseURL: server.URL,
})
apps, err := adapter.ListApps(context.Background())
require.NoError(t, err)
require.Len(t, apps, 2)
assert.Equal(t, "ActiveApp", apps[0].ID)
assert.False(t, apps[0].Disabled)
assert.Equal(t, "InactiveApp", apps[1].ID)
assert.True(t, apps[1].Disabled)
}
func TestTranslateAwtrixSchema_BoolValuePrecedence(t *testing.T) {
resp := AwtrixConfigResponse{
Name: "TestApp",
Fields: []AwtrixField{
{
Key: "flag",
Type: "bool",
Default: false,
Value: true,
},
},
}
b, err := TranslateAwtrixSchema(resp, false)
require.NoError(t, err)
var schema PixletSchema
require.NoError(t, json.Unmarshal(b, &schema))
require.NotEmpty(t, schema.Schema)
assert.Equal(t, "true", schema.Schema[0].Default, "f.Value must take precedence over f.Default for bool fields")
}
func TestConvertUserConfigToAwtrix_SelectFloat(t *testing.T) {
fields := []AwtrixField{
{
Key: "speed",
Type: "select",
Options: []any{0.5, 1.0, 1.5, 2.0},
},
}
userConfig := map[string]any{
"speed": "1.5",
}
converted := ConvertUserConfigToAwtrix(fields, userConfig)
assert.Equal(t, 1.5, converted["speed"])
}
+7 -3
View File
@@ -173,6 +173,7 @@ type PixletSchema struct {
Schema []PixletSchemaField `json:"schema"`
}
// PixletSchemaField represents an individual parameter control in a Pixlet schema.
type PixletSchemaField struct {
ID string `json:"id"`
Name string `json:"name"`
@@ -183,6 +184,7 @@ type PixletSchemaField struct {
Options []PixletOption `json:"options,omitempty"`
}
// PixletOption represents a selectable option in a dropdown control.
type PixletOption struct {
Display string `json:"display"`
Value string `json:"value"`
@@ -229,10 +231,10 @@ func TranslateAwtrixSchema(resp AwtrixConfigResponse, isBuiltin bool) ([]byte, e
switch f.Type {
case "bool":
field.Type = "onoff"
if d, ok := f.Default.(bool); ok {
field.Default = fmt.Sprintf("%t", d)
} else if v, ok := f.Value.(bool); ok {
if v, ok := f.Value.(bool); ok {
field.Default = fmt.Sprintf("%t", v)
} else if d, ok := f.Default.(bool); ok {
field.Default = fmt.Sprintf("%t", d)
} else {
field.Default = "false"
}
@@ -365,6 +367,8 @@ func ConvertUserConfigToAwtrix(fields []AwtrixField, userConfig map[string]any)
if s, ok := v.(string); ok {
if n, err := strconv.Atoi(s); err == nil {
converted = n
} else if fl, err := strconv.ParseFloat(s, 64); err == nil {
converted = fl
}
}
}
+1
View File
@@ -39,6 +39,7 @@ type ExternalAppMeta struct {
Supports2x bool `json:"supports2x"`
Tags []string `json:"tags"`
PreviewURL string `json:"preview_url"`
Disabled bool `json:"disabled,omitempty"`
}
// ExternalAppProvider defines the pluggable interface for third-party app stores / renderers.
@@ -19,6 +19,17 @@ func TestAwtrixIntegration(t *testing.T) {
// Mock Awtrix NG server
awtrixServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/v1/settings":
if r.Method == http.MethodGet {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"autoTransition":true,"transitionDurationMs":5000}`))
return
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"ok":true}`))
case "/api/v1/device":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"currentApp":"OtherApp"}`))
case "/api/v1/apps":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`[
+13 -2
View File
@@ -93,6 +93,9 @@ func (s *Server) handleAddAppGet(w http.ResponseWriter, r *http.Request) {
s.warmExternalAppThumbnails(provider, extApps)
}
for _, ext := range extApps {
if ext.Disabled {
continue
}
category := "Visuals"
if strings.HasPrefix(ext.ID, "clocks") {
category = "Clocks"
@@ -551,6 +554,9 @@ func (s *Server) warmExternalAppThumbnails(provider providers.ExternalAppProvide
cacheDir := s.ensureCleanPreviewCache(provider.Name())
s.backgroundRenders.Go(func() {
for _, app := range apps {
if app.Disabled {
continue
}
safeAppID, err := sanitizeAppID(app.ID)
if err != nil {
continue
@@ -1204,8 +1210,10 @@ func (s *Server) handleRenderConfigPreview(w http.ResponseWriter, r *http.Reques
Timezone: device.GetTimezone(),
Config: configData,
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
renderTimeout := max(30*time.Second, time.Duration(previewDurationMs)*time.Millisecond+15*time.Second)
ctx, cancel := context.WithTimeout(r.Context(), renderTimeout)
defer cancel()
_ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(renderTimeout))
chunks, err := provider.RenderAppChunks(ctx, req)
if err != nil || len(chunks) == 0 {
@@ -1297,8 +1305,11 @@ func (s *Server) handleRenderConfigPreview(w http.ResponseWriter, r *http.Reques
Timezone: device.GetTimezone(),
Config: app.Config,
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
renderTimeout := max(30*time.Second, time.Duration(previewDurationMs)*time.Millisecond+15*time.Second)
ctx, cancel := context.WithTimeout(r.Context(), renderTimeout)
defer cancel()
_ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(renderTimeout))
chunks, err := provider.RenderAppChunks(ctx, req)
if err == nil && len(chunks) > 0 {
previewBytes := chunks[0].WebPBytes
+6 -2
View File
@@ -115,8 +115,12 @@ func (s *Server) possiblyRender(ctx context.Context, app *data.App, device *data
appBasename := fmt.Sprintf("%s-%s", app.Name, app.Iname)
// External Provider App (e.g. Screeny, Awtrix)
if _, _, ok := s.parseExternalAppPath(*app.Path); ok {
return s.renderExternalApp(ctx, app, device, user, false)
if s.isExternalAppPath(*app.Path) {
if _, _, ok := s.parseExternalAppPath(*app.Path); ok {
return s.renderExternalApp(ctx, app, device, user, false)
}
slog.Warn("External app provider unavailable for path", "path", *app.Path)
return false
}
appPath, err := securejoin.SecureJoin(s.DataDir, *app.Path)
+28 -15
View File
@@ -200,7 +200,7 @@ func NewServer(db *gorm.DB, cfg *config.Settings) *Server {
slog.Info("Registered Screeny external app provider", "url", cfg.ScreenyStudioURL, "scaleFilter", cfg.ScreenyScaleFilter)
}
// Awtrix Settings from DB or env
if val, err := s.getSetting("awtrix_url"); err == nil && val != "" {
if val, err := s.getSetting("awtrix_url"); err == nil {
cfg.AwtrixURL = val
}
if val, err := s.getSetting("awtrix_scale_filter"); err == nil && val != "" {
@@ -632,33 +632,49 @@ func (s *Server) updateAwtrixConfig(awtrixURL, scaleFilter, layout string) error
if err := validateExternalProviderURL(cleanURL); err != nil {
return fmt.Errorf("invalid Awtrix URL: %w", err)
}
s.Config.AwtrixURL = cleanURL
filter := s.Config.AwtrixScaleFilter
if scaleFilter != "" {
s.Config.AwtrixScaleFilter = scaleFilter
filter = scaleFilter
}
awtrixLayout := s.Config.AwtrixLayout
if layout != "" {
s.Config.AwtrixLayout = layout
awtrixLayout = layout
}
if err := s.setSetting("awtrix_url", s.Config.AwtrixURL); err != nil {
if err := s.setSettings(map[string]string{
"awtrix_url": cleanURL,
"awtrix_scale_filter": filter,
"awtrix_layout": awtrixLayout,
}); err != nil {
return err
}
if err := s.setSetting("awtrix_scale_filter", s.Config.AwtrixScaleFilter); err != nil {
return err
}
if err := s.setSetting("awtrix_layout", s.Config.AwtrixLayout); err != nil {
return err
oldURL := s.Config.AwtrixURL
s.Config.AwtrixURL = cleanURL
s.Config.AwtrixScaleFilter = filter
s.Config.AwtrixLayout = awtrixLayout
if oldURL != cleanURL {
markerFile := filepath.Join(s.DataDir, "cache", "previews", "awtrix", ".previews_v9")
_ = os.Remove(markerFile)
}
if s.Config.AwtrixURL != "" {
var sem chan struct{}
s.externalProvidersMu.RLock()
if existing, ok := s.externalProviders["awtrix"].(*awtrix.AwtrixAdapter); ok {
sem = existing.Semaphore()
}
s.externalProvidersMu.RUnlock()
adapter := awtrix.NewAdapter(awtrix.AdapterConfig{
BaseURL: s.Config.AwtrixURL,
FPS: s.Config.AwtrixFPS,
ScaleFilter: s.Config.AwtrixScaleFilter,
Layout: s.Config.AwtrixLayout,
Semaphore: sem,
})
s.RegisterExternalProvider(adapter)
slog.Info("Updated Awtrix external app provider", "url", s.Config.AwtrixURL, "scaleFilter", s.Config.AwtrixScaleFilter, "layout", s.Config.AwtrixLayout)
go s.preheatExternalAppThumbnails()
s.backgroundRenders.Go(func() { s.preheatExternalAppThumbnails() })
} else {
s.externalProvidersMu.Lock()
delete(s.externalProviders, "awtrix")
@@ -668,11 +684,8 @@ func (s *Server) updateAwtrixConfig(awtrixURL, scaleFilter, layout string) error
return nil
}
// isExternalAppPath returns true if the path refers to an external provider (e.g. "screeny:clock").
// isExternalAppPath returns true if the path follows the external provider naming convention ("<provider>:<appID>").
func (s *Server) isExternalAppPath(path string) bool {
if _, _, ok := s.parseExternalAppPath(path); ok {
return true
}
parts := strings.SplitN(path, ":", 2)
return len(parts) == 2 && len(parts[0]) > 1 && parts[1] != "" &&
!strings.Contains(parts[0], "/") && !strings.Contains(parts[0], "\\")