25 Commits
Author SHA1 Message Date
behrinml dd1d40b0d4 implemented pr (worth fixing) feedback
update commit
2026-08-06 20:27:25 +02:00
maziggy a74dc7932f Cover nested data structures in the HA notify pass-through (#1441)
The three tests around it use flat scalars, which is also all the field's
placeholder and the wiki showed, so nothing recorded that the value is
forwarded verbatim rather than treated as a key/value list. A reporter asked
whether action buttons work; they always have, and now that is pinned.

The changelog entry said "nested options work" and left it there. It now names
actions and the two things that decide whether the buttons do anything - the
mobile_app_notification_action automation, and iOS needing a registered
category - since neither is set from Bambuddy and both are what a reader would
otherwise have to discover the way the reporter did.
2026-08-05 11:51:30 +02:00
maziggy 88dc56d6e1 Security hardening (maziggy/bambuddy-security #7)
fix(settings): accept JSON booleans on the Spoolman settings endpoint
2026-07-30 13:52:56 +02:00
maziggy 62ba751278 feat(notifications): Bark notification provider (#1495)
Bark is the open-source, account-free iOS push app (self-hostable
via bark-server). Configure with just the device key from the app;
the server URL defaults to the official api.day.app relay and
accepts a self-hosted instance. Optional settings: notification
Group, Sound, and iOS Interruption Level - Time Sensitive breaks
through scheduled summaries, Critical bypasses Silent mode and
Focus, Passive delivers silently.

bark-server can wrap failures in an HTTP 200 body ({"code": 400}),
so the sender checks the body code as well as the HTTP status.
Unknown interruption levels are dropped rather than forwarded.
2026-07-28 10:58:08 +02:00
maziggy 49f9d7120d feat(notifications): custom data fields for Home Assistant notify services (#1441)
When an HA notification provider targets a notify service (e.g.
notify.mobile_app_myphone), a new optional Data (JSON) field is
forwarded as the service call's nested "data" object - the same
place HA automations put mobile push options like priority, ttl,
channel, and group. ttl: 0 + priority: high make Android pushes
arrive immediately; channel gives printer alerts their own sound.

JSON rather than key=value lines so numbers stay numbers and nested
options work. Validated on both ends: the UI rejects malformed JSON
before saving, and the sender fails loudly instead of posting a
half-built payload. Only included when configured - the default
persistent_notification.create path is unchanged, as its schema
rejects unknown keys.
2026-07-28 10:44:40 +02:00
maziggy cc75a24371 fix(db): stop holding pooled connections across FTP/camera/SMTP work (#2572)
The remaining routes of the idle-in-transaction class: the file-manager,
storage, camera-snapshot and timelapse routes each took their printer row
via Depends(get_db) and then talked FTP/camera on the same held session, so
a farm dashboard polling cover/snapshot tiles (offline printers included)
crept the pool to exhaustion over ~23h. They now read in a short session and
release before the I/O; timelapse re-opens a fresh session only for the write.

Also caps the four bare-executor FTP helpers with asyncio.wait_for so a
saturated 48-worker pool can't pin a caller (and its DB connection)
indefinitely, and runs the synchronous smtplib send off the event loop with
an explicit timeout so a wedged relay can't freeze the loop.
2026-07-18 09:10:08 +02:00
maziggy 7e6b390d74 feat(notifications): template-driven finish-photo email embed + user_print_* rename (#1792)
Reporter (email provider, "Reason: unknown" failures) wanted a camera snapshot
  in failure emails. The finish-photo capture path shipped in 0.2.5b1 (#1397)
  already loads JPEG bytes into archive_data["image_data"] for terminal print
  events, and pushover/telegram/discord/ntfy users have been getting them.
  Email was the one provider that dropped the bytes on the floor. Reporter
  separately flagged that the Message Templates list shows "Print Completed"
  and "User Print Completed" with no visual cue they're different dispatches.

  Both fixes in one commit because they touch the same UI surface (Message
  Templates) and both stem from the same reporter conversation.

  1) Inline finish-photo embed in email — template-driven, opt-in.

     _send_email now accepts finish_photo_url alongside image_data. Inline
     embed fires only when bytes are present AND URL is set AND the rendered
     body contains that URL — i.e. the user's template referenced the existing
     {finish_photo_url} variable. The multipart/related shape wraps a
     multipart/alternative (plain + HTML) plus an inline MIMEImage with
     Content-ID: <bambuddy-finish-photo>. The HTML part replaces the escaped
     URL in-place with the cid <img>, so the image appears WHERE the user put
     the variable in the template, not stapled to the bottom. Plain-text part
     keeps the URL as a clickable link for non-HTML clients.

     First draft of this fix unconditionally inlined the photo whenever
     image_data was present, which bypassed the template system. Reverted to
     the template-driven contract: default templates unchanged, opt-in by
     editing the template body to include {finish_photo_url}.

  2) user_print_* template name disambiguation.

     The four user_print_* templates are the per-user SMTP emails sent to the
     print's submitter (advanced-auth-only path). They shared the "Print
     Completed" / "Print Failed" / etc. short names with the broadcast
     provider templates, so the Message Templates list was indistinguishable.
     The EVENT_NAMES display map in routes/notification_templates.py already
     used the disambiguated "… Email" labels, but the seed wrote the short
     name to the DB.

     DEFAULT_TEMPLATES now seeds the four user_print_* rows with " Email"
     suffix so fresh installs are correctly labelled. New
     _migrate_rename_user_print_template_names runs on startup and updates
     existing rows where the name still matches the old default. Admin-edited
     names are preserved. Standard SQL UPDATE works on both SQLite and
     Postgres without dialect branching.
2026-06-22 11:15:39 +02:00
maziggy 4206d675eb feat(notifications): dedicate AI Failure Detection notification event (#1794)
Split Obico failure-detection dispatch out of the multiplexed
  on_printer_error event onto its own on_ai_failure_detection event so
  users can subscribe to AI alerts without also enabling HMS hardware-
  error pages, and so the discoverable label "AI Failure Detection" is
  what subscribes them rather than the unrelated "Printer Error" toggle.

  New column on notification_providers (default False, branched
  SQLite/Postgres migration), new notification_service.on_ai_failure_detection
  method, new ai_failure_detection template, obico_actions._notify swap.
  Frontend gets a summary badge, a toggle row with description, and ntfy
  priority surfacing. 14 new tests pin the routing + the regression guard
  ("Printer Error" alone must NOT receive AI notifications now). 11 locales
  covered.

  Existing providers keep working: HMS hardware errors continue to ride
  on_printer_error unchanged; users who want spaghetti alerts opt in via
  the new toggle.
2026-06-22 08:15:29 +02:00
maziggy 4343bd60b1 fix(notifications): honest UA + Cloudflare-challenge detection on ntfy (#1534)
The notification service's httpx client was the only outbound client in
  the codebase still leaking python-httpx/<version> as User-Agent; all
  other clients identify as Bambuddy/1.0 since the May 2026 compliance
  pass. Bring it in line.

  The reporter's ntfy server was behind a Cloudflare Tunnel and CF returned
  its JS challenge page (Just a moment...) to every API request — confirmed
  by reproducing the same 403 with curl. Cloudflare can't be solved from a
  backend, so add detection for the challenge shape (Server: cloudflare or
  cf-mitigated header, or <!DOCTYPE html>...Just a moment... body) and
  return an actionable error message that points at the real fix on the
  user's CF side instead of dumping the raw HTML.

  Normal 403s (auth failures with plain text bodies) still surface the
  original body so genuine errors stay debuggable.
2026-05-26 11:21:03 +02:00
maziggy 5e88ce13f0 fix(notifications): accept discordapp.com webhook URLs (#1363)
Discord's "Copy Webhook URL" button emits discordapp.com URLs; both
  hostnames serve the same webhooks. The validation now accepts either
  prefix while keeping the check itself in place to catch the
  paste-the-wrong-thing error.
2026-05-16 08:00:39 +02:00
maziggy a6c53798d4 fix(notifications): print-complete duration uses actual elapsed, not slicer estimate (#1198)
Pre-fix, _background_notifications in main.py:3434 built archive_data
  with print_time_seconds (the slicer's pre-print estimate parsed from
  the 3MF at archive creation), and notification_service.py:909 formatted
  that field straight into the {{duration}} template variable. A print
  cancelled 2 minutes into a 3-hour estimate notified "duration: 3h".

  Compute actual_time_seconds from started_at/completed_at in main.py and
  add it to archive_data. notification_service.py prefers it, falls back
  to print_time_seconds when the actual can't be derived.

  Also add "cancelled" to the list of statuses that get completed_at set
  in update_archive_status — pre-fix only completed/failed/aborted got a
  timestamp, so queue-UI cancellations had no actual elapsed to compute
  from. Audited every completed_at consumer; none depend on NULL to mean
  "cancelled" (status field already carries that signal), and the
  statistics-totals aggregation gets more accurate too as a side effect.

  3 new regression tests in TestNotificationVariableFallbacks pin the
  {{duration}} variable contract (actual wins over estimate; estimate
  falls in when actual is missing; "Unknown" when both absent).
2026-05-03 08:33:00 +02:00
maziggy 35edc036bd feat(notifications): per-event ntfy priority headers (#990)
ntfy supports a Priority header (1=min, 2=low, 3=default, 4=high, 5=urgent)
  that controls escalation on the receiving device, but every event was being
  sent at the server default — so a "50% complete" ping looked identical to
  "print failed" or "printer offline". Add a per-event priority dropdown
  section in the Add/Edit Notification modal (visible only for ntfy, listing
  only enabled events); the backend reads config.event_priorities and emits
  the matching Priority header on POST and PUT (image-attachment) paths.
  Unmapped events fall through to the ntfy server default. Out-of-range
  and non-numeric values are dropped, not clamped, so a misconfigured value
  never silently sends at the wrong urgency. Test sends omit the header by
  design so the test path can't accidentally page someone at urgent priority.

  Backward compatible: existing providers without event_priorities behave
  exactly as before. NtfyConfig.event_priorities is optional; the route
  stores config as a JSON blob so no migration is needed.

  i18n: full translations across all 8 locales (en/de/fr/it/ja/pt-BR/zh-CN/
  zh-TW). README, CHANGELOG, and the wiki notifications page updated.

  Tests: 6 backend (Priority set on mapped, omitted on unmapped/missing/
  no-priorities, ignored for bad values, propagated through attachment
  path), 6 frontend (section visible only for ntfy, lists only enabled
  events, save round-trip, edit pre-fill, toggle drops row, non-ntfy
  never writes the key).
2026-04-25 12:33:58 +02:00
maziggy 446da087a0 Fix webhook notifications missing camera snapshot (#679)
Webhook providers did not include image data (e.g. camera snapshots
  from first layer complete notifications) even though other providers
  like Telegram, Pushover, and Discord already attached them. The webhook
  payload now includes a base64-encoded "image" field when a snapshot is
  available (generic format only, excluded from Slack format).
2026-03-16 15:10:39 +01:00
maziggy 0b6facc91c Add first layer complete notification with camera snapshot (#679)
Notify users when the first layer finishes printing so they can check
  adhesion remotely. Triggers once per print when layer 2 begins
  (layer_num >= 2, capped at <= 5 to handle reconnects). Includes a
  camera snapshot attachment. Adds the on_first_layer_complete toggle
  to all notification providers, with backend/frontend/i18n support
  across all 7 locales.
2026-03-13 10:53:21 +01:00
maziggy f28421d1ae Add Home Assistant as notification provider (#656)
Sends persistent notifications to the HA dashboard using the existing
  HA connection from Settings. Zero config — just select "Home Assistant"
  as provider type. Users can forward notifications to mobile via HA
  automations.
2026-03-10 10:10:14 +01:00
maziggy 09c3c24111 Add ETA variable to print notification templates (#638)
Add {eta} template variable showing wall-clock completion time
  (e.g. "15:53" or "3:53 PM") to print_start, print_progress, and
  queue_job_started notifications. Respects the user's time_format
  setting (12h/24h). The existing {estimated_time} variable continues
  to show duration ("1h 23m").
2026-03-07 09:34:01 +01:00
maziggy 53a4933c36 feat: add bed cooled notification after print completes (#378)
Notify users when the print bed cools below a configurable threshold
(default 35°C) after a print finishes, so they know when to remove parts.

- Backend: DB migration, model, schemas, notification template, service
  method, background cooldown monitor (polls every 15s, 30min timeout)
- Frontend: event toggle in provider card/modal, threshold setting in
  Settings > Notifications, i18n keys for all 5 locales
- Tests: 4 backend + 4 frontend tests
- Docs: README, website, wiki updated
2026-02-15 10:59:07 +01:00
maziggy b99536cc33 Remove unused imports, variables, and fix minor CodeQL findings
- Remove 28 unused imports across 22 test files
- Prefix 4 unused local variables with _ in app code
  (archives, bambu_mqtt, main) and remove 1 dead store
- Consolidate import/import-from in test_plate_detection.py
- Fix unreachable statement in test_archive_service.py
- Simplify redundant comparison in timelapse_processor.py

Resolves ~50 CodeQL py/unused-import, py/unused-local-variable,
py/import-and-import-from, py/unreachable-statement, and
py/redundant-comparison findings.
2026-02-06 12:19:17 +01:00
maziggy b9495877fc Add HMS error notifications with translations and plate detection fixes
New Features:
- HMS error notifications with human-readable messages (853 error codes)
- Plate not empty notification category (separate toggle in settings)
- Module-friendly names: Print/Task, AMS/Filament, Nozzle/Extruder, etc.
- Backup/restore now includes plate calibration reference images

Fixes:
- Plate calibration images now persist after restart in Docker
- Telegram notifications no longer fail on error codes with underscores
- Plate detection combo button: main toggles detection, chevron opens modal

Tests:
- Added HMS error code tests (10 tests)
- Implemented Dashboard, FileManagerModal, UploadModal tests (previously skipped)
- Added notification service tests for HMS errors and plate detection
- Fixed AuthContext unmount memory leak in tests
2026-01-27 08:48:57 +01:00
maziggy 6c5aad1b73 Fix: Mattermost/Slack Webhook Support
Root Cause: The generic webhook sent a JSON payload with custom field names plus timestamp and source fields. Mattermost/Slack webhooks only accept {"text": "..."}
format and reject unknown fields with HTTP 400.

Users just need to select "Slack / Mattermost" from the Payload Format dropdown when configuring their Mattermost webhook.

Closes #133
2026-01-23 07:13:46 +01:00
maziggy 0354218657 Add finish photo URL to notification templates (Issue #126)
- Add {finish_photo_url} template variable for print_complete, print_failed,
  print_stopped events
- Photo capture now completes before notification is sent (ensures image exists)
- Add External URL setting in Settings → Network (auto-detects from browser)
- Full URL constructed using external_url setting for external services
- Fix Telegram Markdown parsing error when messages contain URLs
- Add backend schema for external_url setting
- Add unit test for finish_photo_url variable passing
2026-01-22 10:42:20 +01:00
maziggy 83cbac04b7 - Add interactive API Browser to Settings > API Keys
- New APIBrowser component with full OpenAPI schema integration
    - Fetches and parses /openapi.json automatically
    - Groups endpoints by API tags (printers, archives, settings, etc.)
    - Expandable endpoint sections with color-coded method badges
    - Path parameter, query parameter, and JSON body editors
    - Auto-populates request body with schema examples
    - Live API request execution with response display
    - Response shows status code, timing, and formatted JSON
    - Copy response button with clipboard fallback
    - Search to filter endpoints across all categories
    - Expand All / Collapse All buttons
    - Link to Swagger UI (/docs)

  - Two-column layout for API Keys tab
    - Left: API key management + webhook documentation
    - Right: API Browser with dedicated test key input

  - Parameter validation
    - Shows warning for missing required parameters
    - Validates before sending requests to avoid 422 errors

  - UX improvements
    - "Use in API Browser" button on newly created keys
    - Responsive layout (stacked on mobile, side-by-side on xl+)
2026-01-02 15:00:21 +01:00
maziggy a14dcbc034 Frontend WebSocket Tests Summary
Expanded the useWebSocket.test.ts from minimal coverage to 20 comprehensive tests covering:

  WebSocket Mock Tests (6 tests)

  - Creates WebSocket with correct URL
  - Starts in CONNECTING state
  - Transitions to OPEN state
  - Can receive messages
  - Can close connection
  - Tracks all instances

  Hook Connection Tests (2 tests)

  - Connects to WebSocket on mount
  - Reports connected state when WebSocket opens

  Message Handling Tests (9 tests)

  - Updates printer status in query cache on printer_status message
  - Preserves wifi_signal when new value is null
  - Invalidates archives on print_complete message
  - Invalidates archives on archive_created message
  - Invalidates archives on archive_updated message (new handler for timelapse auto-assignment)
  - Ignores pong messages without error
  - Handles malformed JSON gracefully
  - Handles unknown message types gracefully

  sendMessage Tests (2 tests)

  - Sends JSON message when connected
  - Does not send when disconnected

  Reconnection Tests (2 tests)

  - Reconnects after connection closes
  - Cleans up on unmount

  Key Fixes

  - Fixed MSW (Mock Service Worker) conflict by:
    a. Adding addEventListener/removeEventListener to MockWebSocket class
    b. Updating MSW setup to bypass WebSocket requests
    c. Properly managing WebSocket mock lifecycle in each test

  Test Results:
  - Frontend: 137 tests passed (9 test files)
  - Backend: 346 tests passed
2025-12-12 15:52:35 +01:00
maziggy f7cde95bbb Tests Added Summary:
Backend Tests (New Files)

  1. backend/tests/integration/test_camera_api.py - 13 tests
    - Camera stop endpoint (GET and POST methods)
    - Active stream termination
    - Printer-specific stream stopping
    - Camera test endpoint
    - Camera snapshot endpoint
    - Camera stream validation
  2. backend/tests/integration/test_system_api.py - 16 tests
    - System info endpoint structure
    - App, database, storage, memory, CPU sections
    - Helper functions (format_bytes, format_uptime)
    - Archive statistics
    - Printer connection info
  3. backend/tests/unit/services/test_telemetry.py - 16 tests
    - Installation ID creation/retrieval
    - Telemetry enabled/disabled checks
    - Telemetry URL configuration
    - Heartbeat sending and rate limiting
    - Exception handling
  4. backend/tests/unit/services/test_notification_service.py (updated) - Added TestNotificationVariableFallbacks class with 9 tests
    - Duration formatting with None values
    - Print complete fallback values
    - Estimated time and remaining time fallbacks
    - Filename fallback to "Unknown"

  Frontend Tests (New Files)

  5. frontend/src/__tests__/pages/SystemInfoPage.test.tsx - 14 tests
    - Loading and error states
    - Application, database, storage, memory, CPU sections
    - Connected printers display
    - Disk usage warning/danger colors
    - Refresh button
  6. frontend/src/__tests__/components/AMSHistoryModal.test.tsx - 21 tests
    - Modal open/close behavior
    - Humidity/temperature mode switching
    - Time range selection
    - Statistics cards (current, avg, min, max)
    - Loading and error states
    - Trend calculation
  7. frontend/src/__tests__/components/NotificationProviderCard.test.tsx (updated) - Added NotificationProviderCard AMS toggles describe block with 11 tests
    - AMS humidity/temperature notification toggles
    - AMS-HT humidity/temperature notification toggles
    - Independence of AMS and AMS-HT toggles
    - Default values

  Total New Tests: ~100 tests covering:
  - Camera API endpoints
  - System info API
  - Anonymous telemetry service
  - Notification variable fallbacks
  - System Info page UI
  - AMS History modal UI
  - AMS/AMS-HT notification toggle settings

  Tests Added - Complete Summary:

  Backend Tests (4 new files, 1 updated)

  | File                                                       | Tests | Description                                                     |
  |------------------------------------------------------------|-------|-----------------------------------------------------------------|
  | tests/integration/test_camera_api.py                       | 13    | Camera stop (GET/POST), snapshot, stream, test endpoints        |
  | tests/integration/test_system_api.py                       | 16    | System info API, helper functions (format_bytes, format_uptime) |
  | tests/unit/services/test_telemetry.py                      | 16    | Installation ID, telemetry toggle, heartbeat sending            |
  | tests/unit/services/test_notification_service.py (updated) | +10   | Variable fallbacks for duration, filename, estimated_time       |

  Frontend Tests (2 new files, 1 updated)

  | File                                                                 | Tests | Description                                           |
  |----------------------------------------------------------------------|-------|-------------------------------------------------------|
  | src/__tests__/pages/SystemInfoPage.test.tsx                          | 14    | System info page UI, sections, loading/error states   |
  | src/__tests__/components/AMSHistoryModal.test.tsx                    | 21    | AMS history modal, mode switching, time ranges, stats |
  | src/__tests__/components/NotificationProviderCard.test.tsx (updated) | +11   | AMS/AMS-HT notification toggle independence           |

  Total: 101 new tests
  - Backend: 335 tests total (all passing)
  - Frontend: 124 tests total (all passing)
2025-12-12 11:15:59 +01:00
maziggy ff53e62ef8 Add comprehensive automated testing infrastructure
Backend:
  - pytest configuration with async support and coverage
  - Unit tests for notification service (23 tests)
  - Unit tests for smart plug manager (12 tests)
  - Unit tests for archive service (16 tests)
  - Integration tests for API endpoints
  - Fix: notifications now send immediately (digest is summary only)

  Frontend:
  - Vitest configuration with jsdom and coverage
  - MSW for API mocking
  - Component tests for Toggle, Button, Card, ConfirmModal (77 tests)
  - Test utilities with custom render wrapper

  CI/CD:
  - GitHub Actions workflow for automated testing
  - Backend lint, unit tests, integration tests
  - Frontend lint, type-check, unit tests, build
2025-12-11 10:03:40 +01:00