Sfoglia il codice sorgente

Notifications: choose which events get the camera photo (#2877)

- New provider column photo_skip_events: events sent without the
  snapshot although Attach Photo is on. Empty keeps every photo.
- _send_to_provider checks it for uploaded photos and for the photo
  URL of Home Assistant, Bark, Gotify, Notify! and Slack webhooks.
- Add/Edit dialog lists the provider's photo events under Attach
  Photo; the card names the events sent without a photo.
- Translated in all locales; tests for sender, routes and dialog.
maziggy 1 settimana fa
parent
commit
9a6089400c
62 ha cambiato i file con 472 aggiunte e 22 eliminazioni
  1. 1 0
      CHANGELOG.md
  2. 2 0
      backend/app/api/routes/notifications.py
  3. 5 0
      backend/app/core/database.py
  4. 6 1
      backend/app/models/notification.py
  5. 21 0
      backend/app/schemas/notification.py
  6. 12 10
      backend/app/services/notification_service.py
  7. 58 0
      backend/tests/integration/test_notifications_api.py
  8. 116 1
      backend/tests/unit/services/test_notification_photo_attachments.py
  9. 109 6
      frontend/src/__tests__/components/AddNotificationModal.test.tsx
  10. 16 0
      frontend/src/api/client.ts
  11. 42 1
      frontend/src/components/AddNotificationModal.tsx
  12. 13 0
      frontend/src/components/NotificationProviderCard.tsx
  13. 2 0
      frontend/src/i18n/locales/de.ts
  14. 2 0
      frontend/src/i18n/locales/en.ts
  15. 2 0
      frontend/src/i18n/locales/es.ts
  16. 2 0
      frontend/src/i18n/locales/fr.ts
  17. 2 0
      frontend/src/i18n/locales/it.ts
  18. 2 0
      frontend/src/i18n/locales/ja.ts
  19. 2 0
      frontend/src/i18n/locales/ko.ts
  20. 2 0
      frontend/src/i18n/locales/nl.ts
  21. 2 0
      frontend/src/i18n/locales/pl.ts
  22. 2 0
      frontend/src/i18n/locales/pt-BR.ts
  23. 2 0
      frontend/src/i18n/locales/ru.ts
  24. 2 0
      frontend/src/i18n/locales/sv.ts
  25. 2 0
      frontend/src/i18n/locales/tr.ts
  26. 2 0
      frontend/src/i18n/locales/uk.ts
  27. 2 0
      frontend/src/i18n/locales/zh-CN.ts
  28. 2 0
      frontend/src/i18n/locales/zh-TW.ts
  29. 36 0
      frontend/src/utils/notificationPhotoEvents.ts
  30. 0 0
      static/assets/ArchivesPage-SaxFULhm.js
  31. 0 0
      static/assets/CamWallPage-BULJvhVm.js
  32. 0 0
      static/assets/CameraPage-9Zmssl6v.js
  33. 0 0
      static/assets/FileManagerPage-Vy3pn8Fu.js
  34. 0 0
      static/assets/InventoryPage-Cn4wibBS.js
  35. 0 0
      static/assets/Layout-DU75Yw6s.js
  36. 0 0
      static/assets/ModelSourcesPage-DFHEUBvY.js
  37. 0 0
      static/assets/PrintersPage-BR3tAzcM.js
  38. 0 0
      static/assets/SettingsPage-7a7wSe23.js
  39. 0 0
      static/assets/SliceModal-DfMkMLa_.js
  40. 0 0
      static/assets/SpoolBuddyInventoryPage-BQTA8vhi.js
  41. 1 1
      static/assets/SpoolBuddySettingsPage-DvwkS9CZ.js
  42. 0 0
      static/assets/SpoolBuddyWriteTagPage-CTZnKR0m.js
  43. 0 0
      static/assets/de-Cbnj1m80.js
  44. 0 0
      static/assets/es-By7MKag1.js
  45. 0 0
      static/assets/fr-CXsYiYRW.js
  46. 0 0
      static/assets/index-DiZoeKH_.js
  47. 0 0
      static/assets/it-DY0-4sMP.js
  48. 0 0
      static/assets/ja-26fblY7-.js
  49. 0 0
      static/assets/ko-DPWne3AC.js
  50. 0 0
      static/assets/locationSensorDefaults-gowXD_hZ.js
  51. 0 0
      static/assets/nl-CCiNvmGh.js
  52. 0 0
      static/assets/pl-DkuENbjS.js
  53. 0 0
      static/assets/pt-BR-Dus71v3l.js
  54. 0 0
      static/assets/ru-DCvToIFe.js
  55. 0 0
      static/assets/spoolCost-LDvVStel.js
  56. 0 0
      static/assets/sv-WOoUanVA.js
  57. 0 0
      static/assets/tr-DiaFyaEr.js
  58. 0 0
      static/assets/uk-CliAC6eU.js
  59. 0 0
      static/assets/usePageFileDrop-4ICkhsFX.js
  60. 0 0
      static/assets/zh-CN-B6l2Dwta.js
  61. 0 0
      static/assets/zh-TW-CgrTzJjX.js
  62. 2 2
      static/index.html

+ 1 - 0
CHANGELOG.md

@@ -18,6 +18,7 @@ All notable changes to Bambuddy will be documented in this file.
 
 - **The profile editor offers the material types of the preferred slicer (#2928, requested by @doncaruana, contributed by @Keybored02 in #3544)** — The **Filament Type** dropdown of a filament profile was one list kept in Bambuddy, with types a slicer does not know (and without ones it does), so a profile could be valid here and not in the slicer. It now offers the types of the slicer chosen under Settings → Slicer: Bambu Studio's or OrcaSlicer's, which differ (Orca has SBS and the PA11/PA12 families, Bambu Studio has TPU-AMS). A profile keeps the type it has, imported or cloud-synced, even if the list does not have it, and changing the preferred slicer changes no existing profile.
 - **The slicer sidecars can be published on one address only (suggested by @pleasantone)** — The sidecar compose file published the slicer ports on every network interface, and the sidecars have no login. The new `SIDECAR_BIND` setting in `slicer-api/.env` limits them to one address: `127.0.0.1` when Bambuddy runs on the same host with its default `network_mode: host`. Left unset, nothing changes, so Bambuddy in bridge mode or on another host still reaches the sidecars
+- **Choose which notifications get the camera photo (#2877, requested by @HappyPuppy21)** — **Attach Photo** on a notification provider sent the snapshot with every event that has one, so a channel that should show the finished print also got a photo at the start and at 25, 50 and 75 percent. With Attach Photo on, the provider's settings now list the photo events it sends, and unticking one sends that event without the photo. Every event keeps its photo until it is unticked, and the provider card names the events that go without one.
 ### Changed
 - **A slice sent again from the slicer adds a print to its archive (#1634, requested by @d3nn3s08, contributed by @Keybored02 in #3508)** — A print from the File Manager or the queue already joined the archive of its file, but a print sent from Bambu Studio or OrcaSlicer, or started on the printer, always got a new archive: the slicer writes a new 3MF each time it sends, so the file never matched, and the archive's print count stayed at one. Bambuddy now also keeps the hash of each archive's G-code, and a print whose G-code matches an archive nobody owns, in no project and not from a File Manager file adds a run to that archive. The archive takes the new 3MF in place of its old one and keeps its photos, timelapses, notes, tags and earlier runs; a name set by hand stays, and a name taken from the file follows the new file. While another print of it is running, the archive keeps its file and only gets the run. A model sliced again with other settings gets an archive of its own. OrcaSlicer writes the slicing time into the G-code, so with it only the same slice sent again matches. Archives made before are read once in the background after the update. Wiki updated.
 - **SpoolBuddy writes OpenTag3D 2.004 on NTAG215 and NTAG216 tags (#3500, suggested by @pleasantone)** — SpoolBuddy wrote the first version of the OpenTag3D layout. The current version moved every field, so a reader that only knows it read the brand, colour, weight and temperatures from the wrong places. Tags with room for it now get version 2.004, with material, brand, colour name, up to four colours, minimum and maximum print temperature, net weight and empty spool weight. Version 2 no longer fits on an NTAG213, so those keep the first version. SpoolBuddy picks by the size the tag reports, and falls back to the first version if it can't read it; a SpoolBuddy that hasn't been updated keeps writing the first version. Bambuddy does not track density or bed temperature, so a version 2 tag leaves them unset. Wiki updated.

+ 2 - 0
backend/app/api/routes/notifications.py

@@ -118,6 +118,7 @@ def _provider_to_dict(provider: NotificationProvider) -> dict:
         "enabled": provider.enabled,
         "config": mask_config(_stored_config(provider)),
         "attach_photo": provider.attach_photo,
+        "photo_skip_events": provider.photo_skip_events or [],
         # Print lifecycle events
         "on_print_start": provider.on_print_start,
         "on_print_complete": provider.on_print_complete,
@@ -277,6 +278,7 @@ async def create_notification_provider(
         enabled=provider_data.enabled,
         config=json.dumps(provider_data.config),
         attach_photo=provider_data.attach_photo,
+        photo_skip_events=provider_data.photo_skip_events,
         # Print lifecycle events
         on_print_start=provider_data.on_print_start,
         on_print_complete=provider_data.on_print_complete,

+ 5 - 0
backend/app/core/database.py

@@ -6174,6 +6174,11 @@ async def _run_migrations(conn):
     )
     await _safe_execute(conn, "ALTER TABLE smart_plugs ADD COLUMN off_bed_temp_threshold INTEGER NOT NULL DEFAULT 35")
 
+    # Migration: the events a provider sends without its camera snapshot
+    # (#2877). Nullable, no backfill: NULL means no event is skipped, so every
+    # provider keeps attaching photos exactly as before.
+    await _safe_execute(conn, "ALTER TABLE notification_providers ADD COLUMN photo_skip_events JSON")
+
     await _backfill_archive_run_photos(conn)
     await _migrate_h3c_queue_tray_ids(conn)
 

+ 6 - 1
backend/app/models/notification.py

@@ -3,7 +3,7 @@
 from datetime import datetime
 from typing import TYPE_CHECKING
 
-from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String, Text, false, true
+from sqlalchemy import JSON, Boolean, DateTime, ForeignKey, Integer, String, Text, false, true
 from sqlalchemy.orm import Mapped, mapped_column, relationship
 
 from backend.app.core.database import Base
@@ -77,6 +77,11 @@ class NotificationProvider(Base):
     # True so ntfy/Pushover/Telegram/Discord keep behaving as they always
     # did; this is the opt-out for whoever doesn't want it.
     attach_photo: Mapped[bool | None] = mapped_column(Boolean, default=True, server_default=true())
+    # Events that go out without the snapshot although attach_photo is on
+    # (#2877), as event types ("print_progress", ...). An opt-out list, so
+    # NULL/empty keeps every event's photo, and an event that starts carrying
+    # one later gets it here too.
+    photo_skip_events: Mapped[list | None] = mapped_column(JSON, nullable=True)
 
     # Event triggers - print lifecycle
     on_print_start: Mapped[bool | None] = mapped_column(Boolean, default=False)

+ 21 - 0
backend/app/schemas/notification.py

@@ -25,6 +25,22 @@ class ProviderType(StrEnum):
     NOTIFY = "notify"
 
 
+# The events that can carry a camera snapshot, i.e. those the sender passes
+# image_data for. A provider can skip the photo on any of them (#2877).
+PhotoEvent = Literal[
+    "print_start",
+    "print_complete",
+    "print_failed",
+    "print_stopped",
+    "print_progress",
+    "first_layer_complete",
+    "printer_error",
+    "ai_failure_detection",
+    "plate_not_empty",
+    "print_confirm_request",
+]
+
+
 class NotificationProviderBase(BaseModel):
     """Base schema for notification providers."""
 
@@ -35,6 +51,10 @@ class NotificationProviderBase(BaseModel):
     attach_photo: bool = Field(
         default=True, description="Attach a camera snapshot to this provider's notifications when one is available"
     )
+    photo_skip_events: list[PhotoEvent] = Field(
+        default_factory=list,
+        description="Events sent without the camera snapshot although attach_photo is on",
+    )
 
     # Event triggers - print lifecycle
     on_print_start: bool = Field(default=False, description="Notify on print start")
@@ -178,6 +198,7 @@ class NotificationProviderUpdate(IgnoresNullForRequiredColumns):
     enabled: bool | None = None
     config: dict[str, Any] | None = None
     attach_photo: bool | None = None
+    photo_skip_events: list[PhotoEvent] | None = None
 
     # Event triggers - print lifecycle
     on_print_start: bool | None = None

+ 12 - 10
backend/app/services/notification_service.py

@@ -1414,11 +1414,13 @@ class NotificationService:
 
         config = json.loads(provider.config) if isinstance(provider.config, str) else provider.config
 
-        # attach_photo is a per-provider opt-out. Clearing image_data covers
-        # the byte-upload providers below; HA/Bark/Slack get their own check
-        # further down too, since they could otherwise get the URL an earlier
-        # provider in the same send left in photo_cache.
-        if not provider.attach_photo:
+        # attach_photo is a per-provider opt-out, photo_skip_events narrows it
+        # to some events (#2877). Clearing image_data covers the byte-upload
+        # providers below; HA/Bark/Slack/Gotify/Notify! check attach_photo
+        # again further down, since they could otherwise get the URL an
+        # earlier provider in the same send left in photo_cache.
+        attach_photo = bool(provider.attach_photo) and event_type not in (provider.photo_skip_events or ())
+        if not attach_photo:
             image_data = None
 
         try:
@@ -1519,7 +1521,7 @@ class NotificationService:
                 # Only Slack format needs a URL — generic format gets the
                 # base64 image field instead.
                 photo_url = None
-                if provider.attach_photo and (config.get("payload_format") or "generic").strip() == "slack":
+                if attach_photo and (config.get("payload_format") or "generic").strip() == "slack":
                     photo_url = await self._get_or_build_photo_url(db, image_data, event_type, photo_cache)
                 return await self._send_webhook(
                     config,
@@ -1533,7 +1535,7 @@ class NotificationService:
             elif provider.provider_type == "homeassistant":
                 photo_url = (
                     await self._get_or_build_photo_url(db, image_data, event_type, photo_cache)
-                    if provider.attach_photo
+                    if attach_photo
                     else None
                 )
                 return await self._send_homeassistant(config, title, message, db=db, image_url=photo_url)
@@ -1546,14 +1548,14 @@ class NotificationService:
                     bark_url = _bark_confirm
                 photo_url = (
                     await self._get_or_build_photo_url(db, image_data, event_type, photo_cache)
-                    if provider.attach_photo
+                    if attach_photo
                     else None
                 )
                 return await self._send_bark(config, title, message, url=bark_url, image_url=photo_url)
             elif provider.provider_type == "notify":
                 photo_url = (
                     await self._get_or_build_photo_url(db, image_data, event_type, photo_cache)
-                    if provider.attach_photo and notify_supports_photos(config.get("device_id"))
+                    if attach_photo and notify_supports_photos(config.get("device_id"))
                     else None
                 )
                 return await self._send_notify(
@@ -1568,7 +1570,7 @@ class NotificationService:
                     gotify_url = _gotify_confirm
                 photo_url = (
                     await self._get_or_build_photo_url(db, image_data, event_type, photo_cache)
-                    if provider.attach_photo
+                    if attach_photo
                     else None
                 )
                 return await self._send_gotify(

+ 58 - 0
backend/tests/integration/test_notifications_api.py

@@ -447,6 +447,64 @@ class TestNotificationsAPI:
         assert result["on_bed_cooled"] is False
         assert result["on_first_layer_complete"] is True
 
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_photo_skip_events_round_trip(self, async_client: AsyncClient):
+        """#2877: the events sent without a photo persist on create and PATCH."""
+        data = {
+            "name": "Photo Skip",
+            "provider_type": "ntfy",
+            "config": {"server": "https://ntfy.sh", "topic": "test"},
+            "photo_skip_events": ["print_progress", "print_start"],
+        }
+        response = await async_client.post("/api/v1/notifications/", json=data)
+        assert response.status_code == 200
+        provider_id = response.json()["id"]
+        assert response.json()["photo_skip_events"] == ["print_progress", "print_start"]
+
+        response = await async_client.patch(
+            f"/api/v1/notifications/{provider_id}", json={"photo_skip_events": ["first_layer_complete"]}
+        )
+        assert response.status_code == 200
+
+        response = await async_client.get(f"/api/v1/notifications/{provider_id}")
+        assert response.json()["photo_skip_events"] == ["first_layer_complete"]
+
+        response = await async_client.patch(f"/api/v1/notifications/{provider_id}", json={"photo_skip_events": []})
+        assert response.status_code == 200
+        response = await async_client.get(f"/api/v1/notifications/{provider_id}")
+        assert response.json()["photo_skip_events"] == []
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_photo_skip_events_rejects_unknown_event(
+        self, async_client: AsyncClient, notification_provider_factory
+    ):
+        provider = await notification_provider_factory()
+
+        response = await async_client.patch(
+            f"/api/v1/notifications/{provider.id}", json={"photo_skip_events": ["print_progres"]}
+        )
+
+        assert response.status_code == 422
+
+    @pytest.mark.asyncio
+    @pytest.mark.integration
+    async def test_null_photo_skip_events_reads_as_empty(
+        self, async_client: AsyncClient, notification_provider_factory, db_session
+    ):
+        """A provider from before #2877 holds NULL, which means nothing skipped."""
+        provider = await notification_provider_factory(name="Pre-2877")
+        await db_session.execute(
+            text("UPDATE notification_providers SET photo_skip_events = NULL WHERE id = :id"), {"id": provider.id}
+        )
+        await db_session.commit()
+
+        response = await async_client.get(f"/api/v1/notifications/{provider.id}")
+
+        assert response.status_code == 200
+        assert response.json()["photo_skip_events"] == []
+
     @pytest.mark.asyncio
     @pytest.mark.integration
     async def test_create_provider_with_missing_spool_assignment_toggle(self, async_client: AsyncClient):

+ 116 - 1
backend/tests/unit/services/test_notification_photo_attachments.py

@@ -12,7 +12,9 @@ from types import SimpleNamespace
 from unittest.mock import AsyncMock, MagicMock, patch
 
 import pytest
+from pydantic import ValidationError
 
+from backend.app.schemas.notification import NotificationProviderCreate, PhotoEvent
 from backend.app.schemas.notification_template import EVENT_VARIABLES, PHOTO_CAPABLE_EVENTS
 from backend.app.services.email_service import send_email
 from backend.app.services.notification_service import NotificationService
@@ -29,12 +31,13 @@ def _client_returning(status_code=200, json_body=None):
     return mock_client
 
 
-def _provider(provider_type: str, config: dict, attach_photo: bool = True):
+def _provider(provider_type: str, config: dict, attach_photo: bool = True, photo_skip_events=None):
     provider = MagicMock()
     provider.provider_type = provider_type
     provider.config = json.dumps(config)
     provider.quiet_hours_enabled = False
     provider.attach_photo = attach_photo
+    provider.photo_skip_events = photo_skip_events
     return provider
 
 
@@ -138,6 +141,118 @@ class TestPhotoCapableEvents:
         assert set(EVENT_VARIABLES) >= PHOTO_CAPABLE_EVENTS
 
 
+class TestPhotoSkipEvents:
+    """photo_skip_events turns the snapshot off for single events (#2877)."""
+
+    def test_skippable_events_are_the_provider_photo_events(self):
+        """The skippable events are exactly the photo events a provider sends:
+        the template editor's set minus the per-user emails, which go to users
+        rather than through a provider, and the test send."""
+        provider_events = {e for e in PHOTO_CAPABLE_EVENTS if not e.startswith("user_")} - {"test"}
+        assert set(PhotoEvent.__args__) == provider_events
+
+    def test_unknown_event_is_rejected(self):
+        with pytest.raises(ValidationError):
+            NotificationProviderCreate(
+                name="n", provider_type="ntfy", config={"topic": "t"}, photo_skip_events=["print_progres"]
+            )
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize("skip", [None, []])
+    async def test_nothing_skipped_keeps_the_photo(self, service, skip):
+        provider = _provider("ntfy", {"topic": "t"}, photo_skip_events=skip)
+
+        with patch.object(service, "_send_ntfy", new_callable=AsyncMock, return_value=(True, "OK")) as mock_send:
+            await service._send_to_provider(
+                provider, "T", "B", db=AsyncMock(), image_data=b"jpeg", event_type="print_progress"
+            )
+
+        assert mock_send.call_args.kwargs.get("image_data") == b"jpeg"
+
+    @pytest.mark.asyncio
+    async def test_skipped_event_goes_out_without_image(self, service):
+        provider = _provider("ntfy", {"topic": "t"}, photo_skip_events=["print_progress", "print_start"])
+
+        with patch.object(service, "_send_ntfy", new_callable=AsyncMock, return_value=(True, "OK")) as mock_send:
+            await service._send_to_provider(
+                provider, "T", "B", db=AsyncMock(), image_data=b"jpeg", event_type="print_progress"
+            )
+
+        mock_send.assert_awaited_once()
+        assert mock_send.call_args.kwargs.get("image_data") is None
+
+    @pytest.mark.asyncio
+    async def test_event_not_skipped_keeps_its_photo(self, service):
+        provider = _provider("ntfy", {"topic": "t"}, photo_skip_events=["print_progress"])
+
+        with patch.object(service, "_send_ntfy", new_callable=AsyncMock, return_value=(True, "OK")) as mock_send:
+            await service._send_to_provider(
+                provider, "T", "B", db=AsyncMock(), image_data=b"jpeg", event_type="print_complete"
+            )
+
+        assert mock_send.call_args.kwargs.get("image_data") == b"jpeg"
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize(
+        ("provider_type", "config", "sender"),
+        [
+            ("bark", {"device_key": "abc"}, "_send_bark"),
+            ("gotify", {"server": "https://g.example", "app_token": "t"}, "_send_gotify"),
+            ("homeassistant", {"service": "notify.mobile_app_x"}, "_send_homeassistant"),
+            ("webhook", {"webhook_url": "http://hook.local", "payload_format": "slack"}, "_send_webhook"),
+            ("notify", {"device_id": "IOS-1", "token": "t"}, "_send_notify"),
+        ],
+    )
+    async def test_fetched_url_providers_skip_the_cached_url(self, service, provider_type, config, sender):
+        """An earlier provider in the same send may have left a photo URL in
+        the shared cache; a provider skipping this event must not pick it up."""
+        provider = _provider(provider_type, config, photo_skip_events=["print_progress"])
+        photo_cache = {"url": "https://bambuddy.example/api/v1/notifications/photos/a.jpg"}
+
+        with patch.object(service, sender, new_callable=AsyncMock, return_value=(True, "OK")) as mock_send:
+            await service._send_to_provider(
+                provider,
+                "T",
+                "B",
+                db=AsyncMock(),
+                image_data=b"jpeg",
+                event_type="print_progress",
+                photo_cache=photo_cache,
+            )
+
+        assert mock_send.call_args.kwargs.get("image_url") is None
+
+    @pytest.mark.asyncio
+    async def test_one_send_photo_only_where_not_skipped(self, service):
+        """Two providers in one send: the one that skips the event gets no
+        photo, the other still gets the URL the send persisted."""
+        keeps = _provider("bark", {"device_key": "abc"})
+        skips = _provider("homeassistant", {"service": "notify.mobile_app_x"}, photo_skip_events=["print_progress"])
+        for i, provider in enumerate((keeps, skips)):
+            provider.id = i
+            provider.name = f"p{i}"
+            provider.daily_digest_enabled = False
+
+        with (
+            patch.object(service, "_send_bark", new_callable=AsyncMock, return_value=(True, "OK")) as bark,
+            patch.object(service, "_send_homeassistant", new_callable=AsyncMock, return_value=(True, "OK")) as ha,
+            patch.object(service, "_update_provider_status", new_callable=AsyncMock),
+            patch.object(service, "_log_notification", new_callable=AsyncMock),
+            patch(
+                "backend.app.api.routes.settings.get_setting",
+                new_callable=AsyncMock,
+                return_value="https://bambuddy.example",
+            ),
+            patch("backend.app.services.notification_service.save_notification_photo", return_value="p.jpg"),
+        ):
+            await service._send_to_providers(
+                [keeps, skips], "T", "B", AsyncMock(), event_type="print_progress", image_data=b"jpeg"
+            )
+
+        assert bark.call_args.kwargs["image_url"] == "https://bambuddy.example/api/v1/notifications/photos/p.jpg"
+        assert ha.call_args.kwargs["image_url"] is None
+
+
 class TestAttachPhotoOptOut:
     """provider.attach_photo=False must keep the photo off every provider type."""
 

+ 109 - 6
frontend/src/__tests__/components/AddNotificationModal.test.tsx

@@ -181,11 +181,12 @@ describe('AddNotificationModal — ntfy Priority (#990)', () => {
     // Find the Stopped toggle in the events grid (a separate area). Its label
     // appears in the priority section AND the toggle grid; we need the toggle
     // one. The toggle is a sibling of the label inside an event-row div.
-    const allStoppedNodes = screen.getAllByText('Stopped');
-    // The first occurrence is in the Print Events grid; the second is in the
-    // Priority section. Click the toggle next to the first one.
-    const togglesGridStopped = allStoppedNodes[0];
-    const toggleRow = togglesGridStopped.closest('div')!;
+    // It also appears in the Attach Photo event list (#2877); the grid one is
+    // the only one with a switch beside it.
+    const toggleRow = screen
+      .getAllByText('Stopped')
+      .map((node) => node.closest('div')!)
+      .find((row) => within(row).queryByRole('switch'))!;
     const toggle = within(toggleRow).getByRole('switch');
     await user.click(toggle);
 
@@ -1017,7 +1018,8 @@ describe('AddNotificationModal — Notify!', () => {
     render(<AddNotificationModal provider={notifyProvider({ live_activities: true })} onClose={() => undefined} />);
     await user.click(screen.getByText('Live Activity appearance'));
     expect(screen.getByText(/The timer is shown by default/)).toBeInTheDocument();
-    for (const checkbox of screen.getAllByRole('checkbox')) expect(checkbox).not.toBeChecked();
+    const metrics = screen.getByRole('group', { name: 'Metrics' });
+    for (const checkbox of within(metrics).getAllByRole('checkbox')) expect(checkbox).not.toBeChecked();
   });
 
   it('enables Lock Screen widgets independently of Live Activities and push events', async () => {
@@ -1088,3 +1090,104 @@ describe('AddNotificationModal — Notify!', () => {
     expect(screen.queryByText('Live Activities (iOS)')).not.toBeInTheDocument();
   });
 });
+
+describe('AddNotificationModal — photo per event (#2877)', () => {
+  function photoEventsGroup() {
+    return screen.getByRole('group', { name: 'Attach the photo to' });
+  }
+
+  it('lists only the photo events the provider sends, ticked by default', async () => {
+    render(
+      <AddNotificationModal
+        provider={buildProvider({ attach_photo: true, on_print_progress: true, photo_skip_events: [] })}
+        onClose={() => undefined}
+      />,
+    );
+
+    const group = await screen.findByRole('group', { name: 'Attach the photo to' });
+    const boxes = within(group).getAllByRole('checkbox');
+    // complete, failed, stopped, progress, confirm request, plate not empty
+    expect(within(group).getByLabelText('Progress')).toBeChecked();
+    expect(within(group).queryByLabelText('Start')).not.toBeInTheDocument();
+    expect(boxes.every((box) => (box as HTMLInputElement).checked)).toBe(true);
+  });
+
+  it('saves the unticked events as photo_skip_events', async () => {
+    let captured: Record<string, unknown> | null = null;
+    server.use(
+      http.patch('*/api/v1/notifications/1', async ({ request }) => {
+        captured = (await request.json()) as Record<string, unknown>;
+        return HttpResponse.json({ id: 1 });
+      }),
+    );
+    const onClose = vi.fn();
+    const user = userEvent.setup();
+    render(
+      <AddNotificationModal
+        provider={buildProvider({ attach_photo: true, on_print_progress: true, photo_skip_events: ['print_start'] })}
+        onClose={onClose}
+      />,
+    );
+
+    await screen.findByRole('group', { name: 'Attach the photo to' });
+    await user.click(within(photoEventsGroup()).getByLabelText('Progress'));
+    await user.click(screen.getByRole('button', { name: /^save$/i }));
+    await waitFor(() => expect(onClose).toHaveBeenCalled());
+
+    // print_start is hidden (event off) but keeps its choice.
+    expect(captured!.photo_skip_events).toEqual(['print_start', 'print_progress']);
+  });
+
+  it('re-ticking an event takes it off the skip list', async () => {
+    let captured: Record<string, unknown> | null = null;
+    server.use(
+      http.patch('*/api/v1/notifications/1', async ({ request }) => {
+        captured = (await request.json()) as Record<string, unknown>;
+        return HttpResponse.json({ id: 1 });
+      }),
+    );
+    const onClose = vi.fn();
+    const user = userEvent.setup();
+    render(
+      <AddNotificationModal
+        provider={buildProvider({ attach_photo: true, photo_skip_events: ['print_complete'] })}
+        onClose={onClose}
+      />,
+    );
+
+    const box = within(await screen.findByRole('group', { name: 'Attach the photo to' })).getByLabelText('Complete');
+    expect(box).not.toBeChecked();
+    await user.click(box);
+    await user.click(screen.getByRole('button', { name: /^save$/i }));
+    await waitFor(() => expect(onClose).toHaveBeenCalled());
+
+    expect(captured!.photo_skip_events).toEqual([]);
+  });
+
+  it('hides the list while Attach Photo is off', async () => {
+    render(
+      <AddNotificationModal provider={buildProvider({ attach_photo: false })} onClose={() => undefined} />,
+    );
+
+    await screen.findAllByText('Attach Photo');
+    expect(screen.queryByRole('group', { name: 'Attach the photo to' })).not.toBeInTheDocument();
+  });
+
+  it('the card names the events sent without a photo', async () => {
+    const user = userEvent.setup();
+    render(
+      <NotificationProviderCard
+        provider={buildProvider({
+          attach_photo: true,
+          on_print_progress: true,
+          // print_start is off on this provider, so it is not named.
+          photo_skip_events: ['print_progress', 'print_start'],
+        })}
+        onEdit={() => undefined}
+      />,
+    );
+
+    await user.click(screen.getByRole('button', { name: /event settings/i }));
+    expect(screen.getByText('No photo for: Progress')).toBeInTheDocument();
+  });
+});

+ 16 - 0
frontend/src/api/client.ts

@@ -3284,6 +3284,19 @@ export type ProviderType = 'callmebot' | 'ntfy' | 'pushover' | 'telegram' | 'ema
 // How a Telegram provider collects the outcome verdict (#3046)
 export type TelegramVerdictMode = 'buttons' | 'reactions' | 'both';
 
+// Events that can carry a camera snapshot; a provider can skip it per event (#2877).
+export type NotificationPhotoEvent =
+  | 'print_start'
+  | 'print_complete'
+  | 'print_failed'
+  | 'print_stopped'
+  | 'print_progress'
+  | 'first_layer_complete'
+  | 'printer_error'
+  | 'ai_failure_detection'
+  | 'plate_not_empty'
+  | 'print_confirm_request';
+
 export interface NotificationProvider {
   id: number;
   name: string;
@@ -3291,6 +3304,7 @@ export interface NotificationProvider {
   enabled: boolean;
   config: Record<string, unknown>;
   attach_photo: boolean;
+  photo_skip_events: NotificationPhotoEvent[];
   // Print lifecycle events
   on_print_start: boolean;
   on_print_complete: boolean;
@@ -3361,6 +3375,7 @@ export interface NotificationProviderCreate {
   enabled?: boolean;
   config: Record<string, unknown>;
   attach_photo?: boolean;
+  photo_skip_events?: NotificationPhotoEvent[];
   // Print lifecycle events
   on_print_start?: boolean;
   on_print_complete?: boolean;
@@ -3424,6 +3439,7 @@ export interface NotificationProviderUpdate {
   enabled?: boolean;
   config?: Record<string, unknown>;
   attach_photo?: boolean;
+  photo_skip_events?: NotificationPhotoEvent[];
   // Print lifecycle events
   on_print_start?: boolean;
   on_print_complete?: boolean;

+ 42 - 1
frontend/src/components/AddNotificationModal.tsx

@@ -3,10 +3,11 @@ import { useMutation, useQueryClient, useQuery } from '@tanstack/react-query';
 import { useTranslation } from 'react-i18next';
 import { X, Save, Loader2, Send, CheckCircle, XCircle } from 'lucide-react';
 import { api } from '../api/client';
-import type { NotificationProvider, NotificationProviderCreate, NotificationProviderUpdate, ProviderType, TelegramVerdictMode } from '../api/client';
+import type { NotificationPhotoEvent, NotificationProvider, NotificationProviderCreate, NotificationProviderUpdate, ProviderType, TelegramVerdictMode } from '../api/client';
 import { Button } from './Button';
 import { Toggle } from './Toggle';
 import { isNotifyPushOnlyTarget, isNotifyPhotoUnsupported } from '../utils/notify';
+import { enabledPhotoEvents } from '../utils/notificationPhotoEvents';
 import { SECRET_PLACEHOLDER, selectPlaceholderOnFocus } from '../utils/secrets';
 
 interface ConfigField {
@@ -45,6 +46,8 @@ export function AddNotificationModal({ provider, onClose }: AddNotificationModal
       ? false
       : provider?.attach_photo ?? true
   );
+  // Events sent without the snapshot although Attach Photo is on (#2877).
+  const [photoSkipEvents, setPhotoSkipEvents] = useState<NotificationPhotoEvent[]>(provider?.photo_skip_events ?? []);
   const [quietHoursEnabled, setQuietHoursEnabled] = useState(provider?.quiet_hours_enabled || false);
   const [quietHoursStart, setQuietHoursStart] = useState(provider?.quiet_hours_start || '22:00');
   const [quietHoursEnd, setQuietHoursEnd] = useState(provider?.quiet_hours_end || '07:00');
@@ -83,6 +86,21 @@ export function AddNotificationModal({ provider, onClose }: AddNotificationModal
   const [onFirstLayerComplete, setOnFirstLayerComplete] = useState(provider?.on_first_layer_complete ?? false);
   const [onPrintPauseUpcoming, setOnPrintPauseUpcoming] = useState(provider?.on_print_pause_upcoming ?? false);
   const [onAppMessage, setOnAppMessage] = useState(provider?.on_app_message ?? false);
+  // Only the photo events this provider sends; skipped ones that are hidden
+  // keep their choice for when the event is switched back on.
+  const photoEvents = enabledPhotoEvents({
+    on_print_start: onPrintStart,
+    on_print_complete: onPrintComplete,
+    on_print_failed: onPrintFailed,
+    on_print_stopped: onPrintStopped,
+    on_print_progress: onPrintProgress,
+    on_first_layer_complete: onFirstLayerComplete,
+    on_printer_error: onPrinterError,
+    on_ai_failure_detection: onAiFailureDetection,
+    // No toggle in this dialog; it is set on the card.
+    on_plate_not_empty: provider?.on_plate_not_empty ?? true,
+    on_print_confirm_request: onPrintConfirmRequest,
+  });
 
   const [notifyLiveActivities, setNotifyLiveActivities] = useState(
     provider?.config?.live_activities === true && !isNotifyPushOnlyTarget(String(provider?.config?.device_id || ''))
@@ -244,6 +262,7 @@ export function AddNotificationModal({ provider, onClose }: AddNotificationModal
       config: finalConfig,
       printer_id: printerId,
       attach_photo: attachPhoto && !notifyPhotosUnsupported,
+      photo_skip_events: photoSkipEvents,
       quiet_hours_enabled: quietHoursEnabled,
       quiet_hours_start: quietHoursEnabled ? quietHoursStart : null,
       quiet_hours_end: quietHoursEnabled ? quietHoursEnd : null,
@@ -755,6 +774,28 @@ export function AddNotificationModal({ provider, onClose }: AddNotificationModal
               onChange={setAttachPhoto}
             />
           </div>
+          {attachPhoto && !notifyPhotosUnsupported && photoEvents.length > 0 && (
+            <fieldset className="pl-4 border-l-2 border-bambu-dark-tertiary">
+              <legend className="text-xs text-bambu-gray mb-2">{t('notifications.attachPhotoEvents')}</legend>
+              <div className="flex flex-wrap gap-x-4 gap-y-2">
+                {photoEvents.map(({ event, labelKey }) => (
+                  <label key={event} className="flex items-center gap-1 text-sm text-white">
+                    <input
+                      type="checkbox"
+                      checked={!photoSkipEvents.includes(event)}
+                      onChange={(e) =>
+                        setPhotoSkipEvents(e.target.checked
+                          ? photoSkipEvents.filter((skipped) => skipped !== event)
+                          : [...photoSkipEvents, event])
+                      }
+                      className="accent-bambu-green"
+                    />
+                    {t(labelKey)}
+                  </label>
+                ))}
+              </div>
+            </fieldset>
+          )}
 
           {/* Quiet Hours */}
           <div className="space-y-2">

+ 13 - 0
frontend/src/components/NotificationProviderCard.tsx

@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
 import { Bell, Trash2, Settings2, Edit2, Send, Loader2, CheckCircle, XCircle, Moon, Clock, ChevronDown, ChevronUp, Calendar, Camera, CameraOff } from 'lucide-react';
 import { api } from '../api/client';
 import { formatDateOnly, parseUTCDate } from '../utils/date';
+import { enabledPhotoEvents } from '../utils/notificationPhotoEvents';
 import type { NotificationProvider, NotificationProviderUpdate } from '../api/client';
 import { Card, CardContent } from './Card';
 import { Button } from './Button';
@@ -765,6 +766,18 @@ export function NotificationProviderCard({ provider, onEdit }: NotificationProvi
                   onChange={(checked) => updateMutation.mutate({ attach_photo: checked })}
                 />
               </div>
+              {!notifyPhotosUnsupported && (provider.attach_photo ?? true) && (() => {
+                // Per-event opt-out (#2877), edited in the provider dialog.
+                const skipped = enabledPhotoEvents(provider).filter(({ event }) =>
+                  (provider.photo_skip_events ?? []).includes(event)
+                );
+                if (skipped.length === 0) return null;
+                return (
+                  <p className="text-xs text-bambu-gray pl-6">
+                    {t('notifications.attachPhotoSkipped', { events: skipped.map(({ labelKey }) => t(labelKey)).join(', ') })}
+                  </p>
+                );
+              })()}
 
               {/* Action Buttons */}
               <div className="flex gap-2 pt-2">

+ 2 - 0
frontend/src/i18n/locales/de.ts

@@ -7052,6 +7052,8 @@ export default {
     onlyFromPrinter: 'Nur Benachrichtigungen für Ereignisse von diesem Drucker senden',
     attachPhotoLabel: 'Foto anhängen',
     attachPhotoDescription: 'Einen Kamera-Schnappschuss mitsenden, sofern für das Ereignis einer aufgenommen wurde',
+    attachPhotoEvents: 'Foto anhängen bei',
+    attachPhotoSkipped: 'Kein Foto bei: {{events}}',
     quietHoursDnd: 'Ruhezeiten (Nicht stören)',
     quietStart: 'Start',
     quietEnd: 'Ende',

+ 2 - 0
frontend/src/i18n/locales/en.ts

@@ -7105,6 +7105,8 @@ export default {
     onlyFromPrinter: 'Only send notifications for events from this printer',
     attachPhotoLabel: 'Attach Photo',
     attachPhotoDescription: 'Include a camera snapshot with notifications, when one was captured for the event',
+    attachPhotoEvents: 'Attach the photo to',
+    attachPhotoSkipped: 'No photo for: {{events}}',
     quietHoursDnd: 'Quiet Hours (Do Not Disturb)',
     quietStart: 'Start',
     quietEnd: 'End',

+ 2 - 0
frontend/src/i18n/locales/es.ts

@@ -7060,6 +7060,8 @@ export default {
     onlyFromPrinter: 'Enviar notificaciones solo para los eventos de esta impresora',
     attachPhotoLabel: 'Adjuntar foto',
     attachPhotoDescription: 'Incluir una captura de la cámara en las notificaciones, cuando se haya tomado una para el evento',
+    attachPhotoEvents: 'Adjuntar la foto en',
+    attachPhotoSkipped: 'Sin foto en: {{events}}',
     quietHoursDnd: 'Horas de silencio (no molestar)',
     quietStart: 'Inicio',
     quietEnd: 'Fin',

+ 2 - 0
frontend/src/i18n/locales/fr.ts

@@ -7040,6 +7040,8 @@ export default {
     onlyFromPrinter: 'Envoyer uniquement les notifications pour les événements de cette imprimante',
     attachPhotoLabel: 'Joindre une photo',
     attachPhotoDescription: 'Inclure une capture de la caméra dans les notifications, lorsqu\'une capture a été prise pour l\'événement',
+    attachPhotoEvents: 'Joindre la photo pour',
+    attachPhotoSkipped: 'Pas de photo pour : {{events}}',
     quietHoursDnd: 'Heures silencieuses (Ne pas déranger)',
     quietStart: 'Début',
     quietEnd: 'Fin',

+ 2 - 0
frontend/src/i18n/locales/it.ts

@@ -7039,6 +7039,8 @@ export default {
     onlyFromPrinter: 'Invia notifiche solo per eventi da questa stampante',
     attachPhotoLabel: 'Allega foto',
     attachPhotoDescription: 'Includi un\'istantanea della fotocamera nelle notifiche, quando ne è stata acquisita una per l\'evento',
+    attachPhotoEvents: 'Allega la foto per',
+    attachPhotoSkipped: 'Nessuna foto per: {{events}}',
     quietHoursDnd: 'Ore silenziose (Non disturbare)',
     quietStart: 'Inizio',
     quietEnd: 'Fine',

+ 2 - 0
frontend/src/i18n/locales/ja.ts

@@ -7053,6 +7053,8 @@ export default {
     onlyFromPrinter: 'このプリンターからのイベントのみ通知を送信',
     attachPhotoLabel: '写真を添付',
     attachPhotoDescription: 'イベントでカメラのスナップショットが撮影された場合、通知に添付します',
+    attachPhotoEvents: '写真を添付するイベント',
+    attachPhotoSkipped: '写真なし: {{events}}',
     quietHoursDnd: '静音時間(おやすみモード)',
     quietStart: '開始',
     quietEnd: '終了',

+ 2 - 0
frontend/src/i18n/locales/ko.ts

@@ -6766,6 +6766,8 @@ export default {
     onlyFromPrinter: '이 프린터의 이벤트에 대한 알림만 전송',
     attachPhotoLabel: '사진 첨부',
     attachPhotoDescription: '이벤트에 대해 카메라 스냅샷이 촬영된 경우 알림에 포함합니다',
+    attachPhotoEvents: '사진을 첨부할 이벤트',
+    attachPhotoSkipped: '사진 없음: {{events}}',
     quietHoursDnd: '방해 금지 시간',
     quietStart: '시작',
     quietEnd: '종료',

+ 2 - 0
frontend/src/i18n/locales/nl.ts

@@ -7103,6 +7103,8 @@ export default {
     onlyFromPrinter: 'Alleen meldingen verzenden voor gebeurtenissen van deze printer',
     attachPhotoLabel: 'Foto bijvoegen',
     attachPhotoDescription: 'Een camera-momentopname meesturen met meldingen, als er een is gemaakt voor de gebeurtenis',
+    attachPhotoEvents: 'Foto meesturen bij',
+    attachPhotoSkipped: 'Geen foto bij: {{events}}',
     quietHoursDnd: 'Stille uren (Niet storen)',
     quietStart: 'Start',
     quietEnd: 'Einde',

+ 2 - 0
frontend/src/i18n/locales/pl.ts

@@ -7105,6 +7105,8 @@ export default {
     onlyFromPrinter: 'Wysyłaj powiadomienia tylko o zdarzeniach z tej drukarki',
     attachPhotoLabel: 'Dołącz zdjęcie',
     attachPhotoDescription: 'Dołączaj do powiadomień zdjęcie z kamery, jeśli zostało wykonane dla zdarzenia',
+    attachPhotoEvents: 'Dołączaj zdjęcie do',
+    attachPhotoSkipped: 'Bez zdjęcia: {{events}}',
     quietHoursDnd: 'Godziny ciszy (Nie przeszkadzać)',
     quietStart: 'Początek',
     quietEnd: 'Koniec',

+ 2 - 0
frontend/src/i18n/locales/pt-BR.ts

@@ -7039,6 +7039,8 @@ export default {
     onlyFromPrinter: 'Enviar notificações apenas para eventos desta impressora',
     attachPhotoLabel: 'Anexar foto',
     attachPhotoDescription: 'Incluir uma captura da câmera nas notificações, quando uma tiver sido feita para o evento',
+    attachPhotoEvents: 'Anexar a foto em',
+    attachPhotoSkipped: 'Sem foto em: {{events}}',
     quietHoursDnd: 'Horário de Silêncio (Não Perturbe)',
     quietStart: 'Início',
     quietEnd: 'Fim',

+ 2 - 0
frontend/src/i18n/locales/ru.ts

@@ -6753,6 +6753,8 @@ export default {
     onlyFromPrinter: "Отправлять уведомления только о событиях этого принтера",
     attachPhotoLabel: "Прикреплять фото",
     attachPhotoDescription: "Добавлять снимок с камеры к уведомлениям, если он был сделан для события",
+    attachPhotoEvents: "Прикреплять снимок к",
+    attachPhotoSkipped: "Без снимка: {{events}}",
     quietHoursDnd: "Тихие часы (не беспокоить)",
     quietStart: "Начало",
     quietEnd: "Окончание",

+ 2 - 0
frontend/src/i18n/locales/sv.ts

@@ -7134,6 +7134,8 @@ errors: {
     onlyFromPrinter: 'Skicka notiser endast för händelser från denna skrivare',
     attachPhotoLabel: 'Bifoga foto',
     attachPhotoDescription: 'Skicka med en kamerabild i notiser när en har tagits för händelsen',
+    attachPhotoEvents: 'Bifoga bilden vid',
+    attachPhotoSkipped: 'Ingen bild vid: {{events}}',
     quietHoursDnd: 'Tysta timmar (Stör ej)',
     quietStart: 'Start',
     quietEnd: 'Slut',

+ 2 - 0
frontend/src/i18n/locales/tr.ts

@@ -7002,6 +7002,8 @@ export default {
     onlyFromPrinter: 'Yalnızca bu yazıcının olayları için bildirim gönder',
     attachPhotoLabel: 'Fotoğraf ekle',
     attachPhotoDescription: 'Olay için bir kamera görüntüsü alındıysa bildirimlere ekle',
+    attachPhotoEvents: 'Fotoğrafın ekleneceği olaylar',
+    attachPhotoSkipped: 'Fotoğrafsız: {{events}}',
     quietHoursDnd: 'Sessiz Saatler (Rahatsız Etme)',
     quietStart: 'Başlangıç',
     quietEnd: 'Bitiş',

+ 2 - 0
frontend/src/i18n/locales/uk.ts

@@ -7093,6 +7093,8 @@ export default {
     onlyFromPrinter: "Надсилати лише сповіщення про події з цього принтера",
     attachPhotoLabel: "Додавати фото",
     attachPhotoDescription: "Додавати знімок з камери до сповіщень, якщо його було зроблено для події",
+    attachPhotoEvents: "Додавати знімок до",
+    attachPhotoSkipped: "Без знімка: {{events}}",
     quietHoursDnd: "Тихі години (не турбувати)",
     quietStart: "Початок",
     quietEnd: "Кінець",

+ 2 - 0
frontend/src/i18n/locales/zh-CN.ts

@@ -7038,6 +7038,8 @@ export default {
     onlyFromPrinter: '仅发送来自此打印机的事件通知',
     attachPhotoLabel: '附加照片',
     attachPhotoDescription: '若事件拍摄了摄像头快照,则随通知一并发送',
+    attachPhotoEvents: '附加照片的事件',
+    attachPhotoSkipped: '不附照片:{{events}}',
     quietHoursDnd: '免打扰时段',
     quietStart: '开始',
     quietEnd: '结束',

+ 2 - 0
frontend/src/i18n/locales/zh-TW.ts

@@ -7038,6 +7038,8 @@ export default {
     onlyFromPrinter: '僅傳送來自此印表機的事件通知',
     attachPhotoLabel: '附加照片',
     attachPhotoDescription: '若事件拍攝了攝影機快照,則隨通知一併傳送',
+    attachPhotoEvents: '附加照片的事件',
+    attachPhotoSkipped: '不附照片:{{events}}',
     quietHoursDnd: '免打擾時段',
     quietStart: '開始',
     quietEnd: '結束',

+ 36 - 0
frontend/src/utils/notificationPhotoEvents.ts

@@ -0,0 +1,36 @@
+import type { NotificationPhotoEvent, NotificationProvider } from '../api/client';
+
+type EventToggle =
+  | 'on_print_start'
+  | 'on_print_complete'
+  | 'on_print_failed'
+  | 'on_print_stopped'
+  | 'on_print_progress'
+  | 'on_first_layer_complete'
+  | 'on_printer_error'
+  | 'on_ai_failure_detection'
+  | 'on_plate_not_empty'
+  | 'on_print_confirm_request';
+
+/**
+ * The events that can carry a camera snapshot, with the provider toggle that
+ * switches the event on and the label it already has in the event list.
+ * A provider can send any of them without the photo (#2877).
+ */
+export const PHOTO_EVENTS: ReadonlyArray<{ event: NotificationPhotoEvent; toggle: EventToggle; labelKey: string }> = [
+  { event: 'print_start', toggle: 'on_print_start', labelKey: 'notifications.start' },
+  { event: 'print_progress', toggle: 'on_print_progress', labelKey: 'notifications.progress' },
+  { event: 'first_layer_complete', toggle: 'on_first_layer_complete', labelKey: 'notifications.firstLayerCompleteLabel' },
+  { event: 'print_complete', toggle: 'on_print_complete', labelKey: 'notifications.complete' },
+  { event: 'print_failed', toggle: 'on_print_failed', labelKey: 'notifications.failed' },
+  { event: 'print_stopped', toggle: 'on_print_stopped', labelKey: 'notifications.stopped' },
+  { event: 'print_confirm_request', toggle: 'on_print_confirm_request', labelKey: 'notifications.printConfirmRequest' },
+  { event: 'printer_error', toggle: 'on_printer_error', labelKey: 'notifications.error' },
+  { event: 'ai_failure_detection', toggle: 'on_ai_failure_detection', labelKey: 'notifications.aiFailureDetection' },
+  { event: 'plate_not_empty', toggle: 'on_plate_not_empty', labelKey: 'notifications.plateNotEmpty' },
+];
+
+/** The photo events whose notification the provider has switched on. */
+export function enabledPhotoEvents(toggles: Partial<Pick<NotificationProvider, EventToggle>>) {
+  return PHOTO_EVENTS.filter(({ toggle }) => toggles[toggle]);
+}

File diff suppressed because it is too large
+ 0 - 0
static/assets/ArchivesPage-SaxFULhm.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/CamWallPage-BULJvhVm.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/CameraPage-9Zmssl6v.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/FileManagerPage-Vy3pn8Fu.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/InventoryPage-Cn4wibBS.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/Layout-DU75Yw6s.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/ModelSourcesPage-DFHEUBvY.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/PrintersPage-BR3tAzcM.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/SettingsPage-7a7wSe23.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/SliceModal-DfMkMLa_.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/SpoolBuddyInventoryPage-BQTA8vhi.js


File diff suppressed because it is too large
+ 1 - 1
static/assets/SpoolBuddySettingsPage-DvwkS9CZ.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/SpoolBuddyWriteTagPage-CTZnKR0m.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/de-Cbnj1m80.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/es-By7MKag1.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/fr-CXsYiYRW.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/index-DiZoeKH_.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/it-DY0-4sMP.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/ja-26fblY7-.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/ko-DPWne3AC.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/locationSensorDefaults-gowXD_hZ.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/nl-CCiNvmGh.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/pl-DkuENbjS.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/pt-BR-Dus71v3l.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/ru-DCvToIFe.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/spoolCost-LDvVStel.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/sv-WOoUanVA.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/tr-DiaFyaEr.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/uk-CliAC6eU.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/usePageFileDrop-4ICkhsFX.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/zh-CN-B6l2Dwta.js


File diff suppressed because it is too large
+ 0 - 0
static/assets/zh-TW-CgrTzJjX.js


+ 2 - 2
static/index.html

@@ -26,7 +26,7 @@
 
     <!-- Splash screens for iOS -->
     <link rel="apple-touch-startup-image" href="/img/android-chrome-512x512.png" />
-    <script type="module" crossorigin src="/assets/index-B4Av1J0I.js"></script>
+    <script type="module" crossorigin src="/assets/index-DiZoeKH_.js"></script>
     <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-aKtaBQYM.js">
     <link rel="modulepreload" crossorigin href="/assets/client-Bol9xAus.js">
     <link rel="modulepreload" crossorigin href="/assets/react-dom-DOwGWmSv.js">
@@ -122,7 +122,7 @@
     <link rel="modulepreload" crossorigin href="/assets/useColorCatalogVersion-5VMJBKdj.js">
     <link rel="modulepreload" crossorigin href="/assets/circle-minus-PUlx2UXc.js">
     <link rel="modulepreload" crossorigin href="/assets/ConnectionDiagnostic-CKKaaGUZ.js">
-    <link rel="modulepreload" crossorigin href="/assets/Layout-BhqOYUia.js">
+    <link rel="modulepreload" crossorigin href="/assets/Layout-DU75Yw6s.js">
     <link rel="stylesheet" crossorigin href="/assets/index-DJkvOUma.css">
   </head>
   <body>

Some files were not shown because too many files changed in this diff