From 8089040bfd8c88c3ab25625f42f9b2b9a0a19940 Mon Sep 17 00:00:00 2001 From: zurdi Date: Fri, 25 Sep 2026 09:01:16 +0200 Subject: [PATCH 01/15] feat(notifications): rebuild notification channels on Apprise Forward notifications to any of the 100+ services Apprise reaches instead of the two hand-coded webhook formats. The channel form lists every Apprise service with the fields it takes, and the backend builds the Apprise URL from them. - New `apprise` channel type, admin only: Apprise opens its own connections, past the SSRF guard. The owner's role is checked again at every delivery. - GET /api/notification-channels/apprise-services describes each service from Apprise's plugin details: URL tokens as fields, options as advanced fields. A field is required only when every URL template needs it. - A channel stores the service and its fields sealed; the URL is built from the template those fields fill at each send. Local schemas, the options that read files and the ones RomM sets are never offered. Apprise follows no redirects, does not retry and its timeouts are capped. - The RomM JSON webhook keeps its payload and HMAC signature; its Discord and ntfy formats go, Apprise covers them. Email is unchanged. - The v2 dialog picks the type from one searchable list and renders the service's fields, options folded under "Advanced options". Co-Authored-By: Claude Opus 5.5 --- backend/endpoints/notification_channels.py | 66 ++- .../responses/notification_channel.py | 117 ++++- .../handler/notification_channels/__init__.py | 2 +- .../notification_channels/apprise_channel.py | 494 ++++++++++++++++++ .../handler/notification_channels/channels.py | 144 +++-- .../handler/notification_channels/config.py | 11 +- .../handler/notification_channels/delivery.py | 44 +- .../handler/notification_channels/webhook.py | 115 +--- backend/models/notification_channel.py | 14 +- .../endpoints/test_notification_channels.py | 84 ++- .../test_apprise_channel.py | 274 ++++++++++ .../notification_channels/test_channels.py | 133 +++-- .../notification_channels/test_delivery.py | 47 +- .../notification_channels/test_webhook.py | 114 +--- docs/BACKEND_ARCHITECTURE.md | 31 +- frontend/src/__generated__/index.ts | 4 +- .../models/AppriseChannelCreatePayload.ts | 15 + .../models/AppriseFieldSchema.ts | 17 + .../models/AppriseServiceSchema.ts | 12 + .../models/NotificationChannelSchema.ts | 5 +- .../models/NotificationChannelType.ts | 2 +- .../NotificationChannelUpdatePayload.ts | 3 +- .../models/WebhookChannelCreatePayload.ts | 2 - .../src/__generated__/models/WebhookFormat.ts | 5 - frontend/src/locales/bg_BG/notifications.json | 26 +- frontend/src/locales/cs_CZ/notifications.json | 26 +- frontend/src/locales/de_DE/notifications.json | 26 +- frontend/src/locales/en_GB/notifications.json | 26 +- frontend/src/locales/en_US/notifications.json | 26 +- frontend/src/locales/es_ES/notifications.json | 26 +- frontend/src/locales/fr_FR/notifications.json | 26 +- frontend/src/locales/hu_HU/notifications.json | 26 +- frontend/src/locales/it_IT/notifications.json | 26 +- frontend/src/locales/ja_JP/notifications.json | 26 +- frontend/src/locales/ko_KR/notifications.json | 26 +- frontend/src/locales/pl_PL/notifications.json | 26 +- frontend/src/locales/pt_BR/notifications.json | 26 +- frontend/src/locales/ro_RO/notifications.json | 26 +- frontend/src/locales/ru_RU/notifications.json | 26 +- frontend/src/locales/tr_TR/notifications.json | 26 +- frontend/src/locales/zh_CN/notifications.json | 26 +- frontend/src/locales/zh_TW/notifications.json | 26 +- .../src/services/api/notificationChannel.ts | 18 +- .../Notifications/AppriseFieldInput.vue | 105 ++++ .../Notifications/AppriseServiceFields.vue | 77 +++ .../NotificationChannelDialog.test.ts | 144 ++++- .../NotificationChannelDialog.vue | 292 +++++++---- .../NotificationChannelsSection.test.ts | 11 +- .../NotificationChannelsSection.vue | 25 +- .../v2/utils/notificationChannels.fixtures.ts | 84 ++- .../src/v2/utils/notificationChannels.test.ts | 65 +++ frontend/src/v2/utils/notificationChannels.ts | 92 +++- pyproject.toml | 1 + uv.lock | 51 ++ 54 files changed, 2500 insertions(+), 688 deletions(-) create mode 100644 backend/handler/notification_channels/apprise_channel.py create mode 100644 backend/tests/handler/notification_channels/test_apprise_channel.py create mode 100644 frontend/src/__generated__/models/AppriseChannelCreatePayload.ts create mode 100644 frontend/src/__generated__/models/AppriseFieldSchema.ts create mode 100644 frontend/src/__generated__/models/AppriseServiceSchema.ts delete mode 100644 frontend/src/__generated__/models/WebhookFormat.ts create mode 100644 frontend/src/v2/components/Notifications/AppriseFieldInput.vue create mode 100644 frontend/src/v2/components/Notifications/AppriseServiceFields.vue create mode 100644 frontend/src/v2/utils/notificationChannels.test.ts diff --git a/backend/endpoints/notification_channels.py b/backend/endpoints/notification_channels.py index 423363461..47a01d923 100644 --- a/backend/endpoints/notification_channels.py +++ b/backend/endpoints/notification_channels.py @@ -5,6 +5,8 @@ from fastapi import HTTPException, Request, status from decorators.auth import protected_route from endpoints.responses.notification_channel import ( + AppriseChannelCreatePayload, + AppriseServiceSchema, EmailChannelCreatePayload, NotificationChannelCodePayload, NotificationChannelCreatePayload, @@ -67,31 +69,53 @@ def get_notification_channels(request: Request) -> list[NotificationChannelSchem ] +@protected_route(router.get, "/apprise-services", [Scope.ME_READ]) +def get_apprise_services(request: Request) -> list[AppriseServiceSchema]: + """Every service an admin's Apprise channel can go out on, with its fields.""" + try: + found = channels.apprise_services(request.user) + except ChannelError as exc: + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, detail=str(exc) + ) from exc + return [AppriseServiceSchema.from_service(service) for service in found] + + @protected_route(router.post, "", [Scope.ME_WRITE], status_code=status.HTTP_201_CREATED) async def create_notification_channel( request: Request, payload: NotificationChannelCreatePayload ) -> NotificationChannelSchema: """Add a channel; an email address gets a code to confirm it with first.""" - if isinstance(payload, EmailChannelCreatePayload): - created = channels.create_channel( - request.user, - NotificationChannelType.EMAIL, - payload.name, - payload.min_level, - payload.topics, - address=payload.address, - ) - else: - created = channels.create_channel( - request.user, - NotificationChannelType.WEBHOOK, - payload.name, - payload.min_level, - payload.topics, - url=payload.url, - format=payload.format, - secret=payload.secret, - ) + match payload: + case EmailChannelCreatePayload(): + created = channels.create_channel( + request.user, + NotificationChannelType.EMAIL, + payload.name, + payload.min_level, + payload.topics, + address=payload.address, + ) + case AppriseChannelCreatePayload(): + created = channels.create_channel( + request.user, + NotificationChannelType.APPRISE, + payload.name, + payload.min_level, + payload.topics, + service=payload.service, + fields=payload.fields, + ) + case _: + created = channels.create_channel( + request.user, + NotificationChannelType.WEBHOOK, + payload.name, + payload.min_level, + payload.topics, + url=payload.url, + secret=payload.secret, + ) return NotificationChannelSchema.from_channel(await _as_http(created)) @@ -116,10 +140,10 @@ async def update_notification_channel( request.user, changes, url=payload.url, - format=payload.format, secret=payload.secret, secret_given="secret" in payload.model_fields_set, address=payload.address, + fields=payload.fields, ) ) return NotificationChannelSchema.from_channel(updated) diff --git a/backend/endpoints/responses/notification_channel.py b/backend/endpoints/responses/notification_channel.py index ef1bc3982..bfa548778 100644 --- a/backend/endpoints/responses/notification_channel.py +++ b/backend/endpoints/responses/notification_channel.py @@ -1,19 +1,26 @@ from typing import Annotated, Literal, Self -from pydantic import Field, field_validator +from pydantic import Field, StrictBool, field_validator +from handler.notification_channels import apprise_channel +from handler.notification_channels.apprise_channel import ( + AppriseField, + AppriseService, + FieldType, +) from handler.notification_channels.config import masked_url, read_config from models.notification import NotificationTopic from models.notification_channel import ( NOTIFICATION_CHANNEL_ADDRESS_MAX_LENGTH, NOTIFICATION_CHANNEL_CODE_MAX_LENGTH, + NOTIFICATION_CHANNEL_MAX_FIELDS, NOTIFICATION_CHANNEL_NAME_MAX_LENGTH, NOTIFICATION_CHANNEL_SECRET_MAX_LENGTH, + NOTIFICATION_CHANNEL_SERVICE_MAX_LENGTH, NOTIFICATION_CHANNEL_URL_MAX_LENGTH, NotificationChannel, NotificationChannelMinLevel, NotificationChannelType, - WebhookFormat, ) from utils.validation import EMAIL_PATTERN @@ -22,11 +29,19 @@ from .base import BaseModel, UTCDatetime ChannelName = Annotated[ str, Field(min_length=1, max_length=NOTIFICATION_CHANNEL_NAME_MAX_LENGTH) ] -WebhookUrl = Annotated[ +ChannelUrl = Annotated[ str, Field(min_length=1, max_length=NOTIFICATION_CHANNEL_URL_MAX_LENGTH) ] ChannelSecret = Annotated[str, Field(max_length=NOTIFICATION_CHANNEL_SECRET_MAX_LENGTH)] EmailAddress = Annotated[str, Field(max_length=NOTIFICATION_CHANNEL_ADDRESS_MAX_LENGTH)] +AppriseServiceId = Annotated[ + str, Field(min_length=1, max_length=NOTIFICATION_CHANNEL_SERVICE_MAX_LENGTH) +] +_FieldText = Annotated[str, Field(max_length=NOTIFICATION_CHANNEL_URL_MAX_LENGTH)] +AppriseFieldValue = StrictBool | int | float | _FieldText | list[_FieldText] +AppriseFields = Annotated[ + dict[str, AppriseFieldValue], Field(max_length=NOTIFICATION_CHANNEL_MAX_FIELDS) +] def _check_address(address: str | None) -> str | None: @@ -43,9 +58,12 @@ class NotificationChannelSchema(BaseModel): min_level: NotificationChannelMinLevel # None forwards every topic. topics: list[NotificationTopic] | None - # A webhook's URL with its token hidden, or an email address. + # The URL with its secrets hidden, or an email address. target: str - format: WebhookFormat | None + # An Apprise channel's service, its name, and the fields that aren't secrets. + service: str | None + service_name: str | None + fields: dict[str, AppriseFieldValue] | None has_secret: bool confirmed: bool last_delivered_at: UTCDatetime | None @@ -56,7 +74,17 @@ class NotificationChannelSchema(BaseModel): @classmethod def from_channel(cls, channel: NotificationChannel) -> Self: config = read_config(channel.config) - is_webhook = channel.type == NotificationChannelType.WEBHOOK + service = config.get("service") + stored_fields = config.get("fields", {}) + service_name, fields = None, None + match channel.type: + case NotificationChannelType.APPRISE if service: + service_name, target = apprise_channel.describe(service, stored_fields) + fields = apprise_channel.public_fields(service, stored_fields) + case NotificationChannelType.WEBHOOK if config.get("url"): + target = masked_url(config["url"]) + case _: + target = config.get("address", "") return cls( id=channel.id, type=NotificationChannelType(channel.type), @@ -68,12 +96,10 @@ class NotificationChannelSchema(BaseModel): if channel.topics is not None else None ), - target=( - masked_url(config["url"]) - if is_webhook and "url" in config - else config.get("address", "") - ), - format=config.get("format") if is_webhook else None, + target=target, + service=service, + service_name=service_name, + fields=fields, has_secret=bool(config.get("secret")), confirmed=channel.confirmed_at is not None, last_delivered_at=channel.last_delivered_at, @@ -88,12 +114,18 @@ class _ChannelFilters(BaseModel): topics: list[NotificationTopic] | None = None +class AppriseChannelCreatePayload(_ChannelFilters): + type: Literal["apprise"] + name: ChannelName + service: AppriseServiceId + fields: AppriseFields + + class WebhookChannelCreatePayload(_ChannelFilters): type: Literal["webhook"] name: ChannelName - url: WebhookUrl - format: WebhookFormat = WebhookFormat.JSON - # The HMAC key of a JSON webhook, or an ntfy access token. + url: ChannelUrl + # The key the payload is signed with. secret: ChannelSecret | None = None @@ -106,7 +138,9 @@ class EmailChannelCreatePayload(_ChannelFilters): NotificationChannelCreatePayload = Annotated[ - WebhookChannelCreatePayload | EmailChannelCreatePayload, + AppriseChannelCreatePayload + | WebhookChannelCreatePayload + | EmailChannelCreatePayload, Field(discriminator="type"), ] @@ -118,10 +152,11 @@ class NotificationChannelUpdatePayload(BaseModel): enabled: bool | None = None min_level: NotificationChannelMinLevel | None = None topics: list[NotificationTopic] | None = None - url: WebhookUrl | None = None - format: WebhookFormat | None = None + url: ChannelUrl | None = None secret: ChannelSecret | None = None address: EmailAddress | None = None + # An Apprise channel's fields; a secret left out keeps its current value. + fields: AppriseFields | None = None check_address = field_validator("address")(_check_address) @@ -130,6 +165,52 @@ class NotificationChannelCodePayload(BaseModel): code: str = Field(min_length=1, max_length=NOTIFICATION_CHANNEL_CODE_MAX_LENGTH) +class AppriseFieldSchema(BaseModel): + key: str + label: str + type: FieldType + required: bool + private: bool + # Sent as an option rather than as part of the address. + advanced: bool + default: AppriseFieldValue | None + # A choice's values, as text: that is how they sit in the URL. + values: list[str] | None + min: float | None + max: float | None + + @classmethod + def from_field(cls, field: AppriseField) -> Self: + return cls( + key=field.key, + label=field.label, + type=field.type, + required=field.required, + private=field.private, + advanced=field.advanced, + default=field.default, + values=[str(value) for value in field.values] if field.values else None, + min=field.min, + max=field.max, + ) + + +class AppriseServiceSchema(BaseModel): + id: str + name: str + setup_url: str | None + fields: list[AppriseFieldSchema] + + @classmethod + def from_service(cls, service: AppriseService) -> Self: + return cls( + id=service.id, + name=service.name, + setup_url=service.setup_url, + fields=[AppriseFieldSchema.from_field(field) for field in service.fields], + ) + + class NotificationChannelTestResult(BaseModel): ok: bool error: str | None diff --git a/backend/handler/notification_channels/__init__.py b/backend/handler/notification_channels/__init__.py index 5008cecfb..d4be3f7b9 100644 --- a/backend/handler/notification_channels/__init__.py +++ b/backend/handler/notification_channels/__init__.py @@ -1 +1 @@ -"""Forwarding a user's notifications to their webhooks and email addresses.""" +"""Forwarding a user's notifications to Apprise services, webhooks and email addresses.""" diff --git a/backend/handler/notification_channels/apprise_channel.py b/backend/handler/notification_channels/apprise_channel.py new file mode 100644 index 000000000..123fa8066 --- /dev/null +++ b/backend/handler/notification_channels/apprise_channel.py @@ -0,0 +1,494 @@ +"""Deliveries through Apprise, which reaches 100+ services from a URL built from their fields.""" + +import json +import logging +import re +from collections.abc import Mapping +from contextvars import ContextVar +from dataclasses import dataclass +from functools import cache +from typing import Any, Final, Literal +from urllib.parse import quote, urlencode, urlsplit, urlunsplit + +from apprise import ( + Apprise, + AppriseAsset, + NotificationManager, + NotifyBase, + NotifyFormat, + NotifyType, +) + +from models.notification import NotificationLevel + +from .messages import OutboundMessage + +ADMINS_ONLY: Final = "Only admins can use Apprise channels" + +# A service can ask for longer (?cto=, ?rto=), which would hold a worker. +CONNECT_TIMEOUT_SECONDS: Final = 10.0 +READ_TIMEOUT_SECONDS: Final = 15.0 + +# Schemas that act on the machine running RomM instead of reaching a service. +LOCAL_SCHEMAS: Final = ( + "syslog", + "windows", + "macosx", + "dbus", + "gnome", + "kde", + "qt", + "glib", + "blink1", +) +# Options Apprise loads as a local file or a URL it fetches. +FILE_OPTIONS: Final = frozenset( + {"template", "keyfile", "subfile", "pgppub", "pgpkey", "pgpprv"} +) +# Options every service shares that RomM sets itself or that don't apply here. +MANAGED_OPTIONS: Final = frozenset( + { + "cto", + "rto", + "retry", + "wait", + "redirect", + "store", + "optional", + "overflow", + "format", + "emojis", + "tz", + } +) +# Services that post to any path on their host, which no token names. +FREE_PATH_SERVICES: Final = frozenset({"json", "xml", "form"}) + +NOTIFY_TYPES: Final[dict[str, NotifyType]] = { + NotificationLevel.INFO: NotifyType.INFO, + NotificationLevel.SUCCESS: NotifyType.SUCCESS, + NotificationLevel.WARNING: NotifyType.WARNING, + NotificationLevel.ERROR: NotifyType.FAILURE, +} + +_ASSET: Final = AppriseAsset( + app_id="RomM", + app_desc="RomM", + app_url="https://romm.app", + # Nothing a plugin keeps (tokens, generated keys) is written to disk. + storage_mode="memory", + pgp_autogen=False, + pem_autogen=False, + http_redirects=False, + secure_logging=True, +) + +NotificationManager().disable(*LOCAL_SCHEMAS) + +_PLACEHOLDER: Final = re.compile(r"{(\w+)}") +# A token that is a URL path, which Apprise wants between slashes. +_PATH_TOKEN: Final = "path" + +FieldType = Literal["string", "int", "float", "bool", "choice", "list"] +FieldValue = str | int | float | bool | list[str] + +# The warnings Apprise logs during the send running in this context. +_warnings: ContextVar[list[str] | None] = ContextVar("apprise_warnings", default=None) + + +class _WarningCollector(logging.Handler): + def emit(self, record: logging.LogRecord) -> None: + collected = _warnings.get() + if collected is not None: + collected.append(record.getMessage()) + + +# Warnings and up only: debug records carry the remote end's response body. +logging.getLogger("apprise").addHandler(_WarningCollector(logging.WARNING)) + + +class AppriseError(RuntimeError): + """The service refused the notification or could not be reached.""" + + +@dataclass(frozen=True) +class AppriseField: + key: str + label: str + type: FieldType + required: bool + private: bool + # An option sent as a query argument rather than part of the URL itself. + advanced: bool + default: str | int | float | bool | None = None + values: tuple[str | int, ...] | None = None + min: float | None = None + max: float | None = None + # Separates a list's items in the URL. + delimiter: str = "," + # Singular tokens a template can take instead of this list. + members: tuple[str, ...] = () + + +@dataclass(frozen=True) +class AppriseService: + id: str + name: str + setup_url: str | None + schemas: tuple[str, ...] + default_schema: str + templates: tuple[str, ...] + fields: tuple[AppriseField, ...] + + def field(self, key: str) -> AppriseField | None: + return next((field for field in self.fields if field.key == key), None) + + +_FIELD_TYPES: Final[dict[str, FieldType]] = { + "string": "string", + "int": "int", + "float": "float", + "bool": "bool", + "choice": "choice", + "list": "list", +} + + +def _field_type(kind: str) -> FieldType | None: + """Apprise's `choice:string` or `list:int` by the form control it needs.""" + return _FIELD_TYPES.get(kind.split(":", 1)[0]) + + +def _field( + key: str, meta: dict[str, Any], *, advanced: bool, required: bool = False +) -> AppriseField | None: + field_type = _field_type(meta.get("type", "string")) + if field_type is None: + return None + values = meta.get("values") + return AppriseField( + key=key, + label=meta.get("name") or key, + type=field_type, + required=required, + private=bool(meta.get("private")), + advanced=advanced, + default=meta.get("default"), + values=tuple(values) if values else None, + min=meta.get("min"), + max=meta.get("max"), + delimiter=(meta.get("delim") or [","])[0], + members=tuple(sorted(meta.get("group") or ())), + ) + + +def _service(entry: dict[str, Any]) -> AppriseService | None: + details = entry["details"] + tokens: dict[str, dict[str, Any]] = details["tokens"] + templates = tuple(details["templates"]) + placeholders = [set(_PLACEHOLDER.findall(template)) for template in templates] + protocols = [ + *(entry.get("protocols") or []), + *(entry.get("secure_protocols") or []), + ] + if not protocols or not templates: + return None + + secure = entry.get("secure_protocols") or [] + default_schema = secure[0] if secure else protocols[0] + members = {member for meta in tokens.values() for member in meta.get("group") or ()} + fields: list[AppriseField] = [] + if len(protocols) > 1: + fields.append( + AppriseField( + key="schema", + label=tokens.get("schema", {}).get("name") or "Schema", + type="choice", + required=True, + private=False, + advanced=False, + default=default_schema, + values=tuple(protocols), + ) + ) + for key, meta in tokens.items(): + if key == "schema" or key in members: + continue + spelled = {key, *(meta.get("group") or ())} + # Alternative credentials are each required somewhere, so only what + # every template needs is required. + required = all(spelled & needed for needed in placeholders) + field = _field(key, meta, advanced=False, required=required) + if field: + fields.append(field) + + if protocols[0] in FREE_PATH_SERVICES: + fields.append( + AppriseField( + key=_PATH_TOKEN, + label="Path", + type="string", + required=False, + private=False, + advanced=False, + ) + ) + + shown = {field.key for field in fields} + for key, meta in details["args"].items(): + if ( + "alias_of" in meta + or key in shown + or key in tokens + or key in FILE_OPTIONS + or key in MANAGED_OPTIONS + ): + continue + field = _field(key, meta, advanced=True) + if field: + fields.append(field) + + return AppriseService( + id=protocols[0], + name=entry.get("service_name") or protocols[0], + setup_url=entry.get("setup_url"), + schemas=tuple(protocols), + default_schema=default_schema, + templates=templates, + fields=tuple(fields), + ) + + +@cache +def services() -> tuple[AppriseService, ...]: + """Every service Apprise can reach from here, by name.""" + # Apprise's own serializer, as its details hold sets; it answers False + # when it can't serialize them. + serialized = Apprise().json() + if not isinstance(serialized, str): + return () + found = (_service(entry) for entry in json.loads(serialized)["schemas"]) + return tuple(sorted((s for s in found if s), key=lambda s: s.name.lower())) + + +def find_service(service_id: str) -> AppriseService: + """Raises: + ValueError: RomM has no such Apprise service. + """ + for service in services(): + if service.id == service_id: + return service + raise ValueError("Apprise has no such service") + + +def _blank(value: object) -> bool: + return value is None or value == "" or value == [] + + +def _text(field: AppriseField, value: FieldValue) -> str: + if isinstance(value, bool): + return "yes" if value else "no" + if isinstance(value, list): + return field.delimiter.join(str(item) for item in value) + return str(value) + + +def _segment(key: str, value: FieldValue, field: AppriseField | None) -> str: + """A token's value as it sits in the URL.""" + if key == "host": + text = str(value).strip() + if not text or re.search(r"[/@?#\s]", text): + raise ValueError(f"{field.label if field else key} isn't a hostname") + return text + if key == _PATH_TOKEN: + # Gotify's {host}{path}{token} needs the path between slashes. + path = str(value).strip("/") + return f"/{quote(path)}/" if path else "/" + if isinstance(value, list): + delimiter = field.delimiter if field else "/" + return delimiter.join(quote(str(item), safe="") for item in value) + return quote(str(value), safe="") + + +def _fill( + service: AppriseService, template: str, tokens: dict[str, FieldValue] +) -> tuple[str, set[str]] | None: + """The template with its tokens filled in and the tokens it took, or None + when it needs one that wasn't given.""" + owners = {member: f.key for f in service.fields for member in f.members} + filled, used = template, set() + for key in _PLACEHOLDER.findall(template): + if key == "schema": + continue + if key in tokens: + text = _segment(key, tokens[key], service.field(key)) + used.add(key) + else: + # A singular token can come from its list when that holds one item. + owner = owners.get(key) + items = tokens.get(owner) if owner else None + if owner is None or not isinstance(items, list) or len(items) != 1: + return None + text = _segment(key, items[0], None) + used.add(owner) + filled = filled.replace(f"{{{key}}}", text, 1) + return filled, used + + +def build_url(service_id: str, fields: Mapping[str, FieldValue]) -> str: + """The Apprise URL for a service's fields. + + Raises: + ValueError: With a reason fit to show the user. + """ + service = find_service(service_id) + tokens: dict[str, FieldValue] = {} + options: dict[str, str] = {} + for key, value in fields.items(): + field = service.field(key) + if field is None or key == "schema" or _blank(value): + continue + if field.advanced: + options[key] = _text(field, value) + else: + tokens[key] = value + schema = str(fields.get("schema") or service.default_schema) + if schema not in service.schemas: + raise ValueError(f"{service.name} doesn't take {schema}://") + + extra_path = ( + tokens.pop(_PATH_TOKEN, None) if service.id in FREE_PATH_SERVICES else None + ) + + fits = [ + filled + for template in service.templates + if (filled := _fill(service, template, tokens)) and filled[1] == set(tokens) + ] + if not fits: + missing = [ + f.label + for f in service.fields + if f.required and f.key != "schema" and f.key not in tokens + ] + raise ValueError( + f"{service.name} needs {', '.join(missing)}" + if missing + else f"{service.name} can't take these fields together" + ) + + url = fits[0][0].replace("{schema}", schema, 1) + if extra_path: + url += "/" + quote(str(extra_path).lstrip("/")) + return f"{url}?{urlencode(options)}" if options else url + + +def _plugin(url: str) -> NotifyBase: + """Raises: + ValueError: With a reason fit to show the user. + """ + try: + plugin = Apprise.instantiate(url, asset=_ASSET, suppress_exceptions=False) + except Exception as exc: # noqa: BLE001 - a plugin says why it refused the URL + raise ValueError(str(exc) or "Apprise can't use these fields") from exc + if plugin is None: + raise ValueError("Apprise can't use these fields") + return plugin + + +def check(service_id: str, fields: Mapping[str, FieldValue]) -> None: + """Refuse fields Apprise can't deliver with. + + Raises: + ValueError: With a reason fit to show the user. + """ + _plugin(build_url(service_id, fields)) + + +def describe( + service_id: str, fields: Mapping[str, FieldValue] +) -> tuple[str | None, str]: + """The service's name, and its URL with the secrets and options hidden.""" + try: + service = find_service(service_id) + plugin = _plugin(build_url(service_id, fields)) + except ValueError: + return None, "" + scheme, netloc, path, _, _ = urlsplit(plugin.url(privacy=True)) + return service.name, urlunsplit((scheme, netloc, path, "", "")) + + +def public_fields( + service_id: str, fields: Mapping[str, FieldValue] +) -> dict[str, FieldValue]: + """The fields that aren't secrets, for the owner's form.""" + try: + service = find_service(service_id) + except ValueError: + return {} + return { + key: value + for key, value in fields.items() + if (field := service.field(key)) is not None and not field.private + } + + +def merge_fields( + service_id: str, + stored: Mapping[str, FieldValue], + given: Mapping[str, FieldValue], +) -> dict[str, FieldValue]: + """The fields after an edit, where a secret left blank keeps the stored one.""" + service = find_service(service_id) + merged = {key: value for key, value in given.items() if not _blank(value)} + for field in service.fields: + if field.private and field.key not in merged and field.key in stored: + merged[field.key] = stored[field.key] + return merged + + +def _bounded(plugin: NotifyBase) -> NotifyBase: + plugin.redirects = False + # RQ retries a failed delivery on its own schedule. + plugin.retry = 0 + plugin.socket_connect_timeout = min( + plugin.socket_connect_timeout or CONNECT_TIMEOUT_SECONDS, + CONNECT_TIMEOUT_SECONDS, + ) + plugin.socket_read_timeout = min( + plugin.socket_read_timeout or READ_TIMEOUT_SECONDS, READ_TIMEOUT_SECONDS + ) + return plugin + + +def send( + service_id: str, fields: Mapping[str, FieldValue], message: OutboundMessage +) -> None: + """Deliver the message through Apprise; blocks until the service answers. + + Raises: + ValueError: The fields no longer make a URL Apprise can use. + AppriseError: The service refused it, or could not be reached. + """ + plugin = _bounded(_plugin(build_url(service_id, fields))) + apprise = Apprise(asset=_ASSET) + apprise.add(plugin) + body = "\n\n".join(part for part in (message.body, message.url) if part) + + collected: list[str] = [] + token = _warnings.set(collected) + try: + sent = apprise.notify( + body=body or message.title, + title=message.title, + notify_type=NOTIFY_TYPES.get(message.notification.level, NotifyType.INFO), + body_format=NotifyFormat.TEXT, + ) + finally: + _warnings.reset(token) + + if not sent: + raise AppriseError( + " ".join(dict.fromkeys(collected)) + or f"{plugin.service_name} did not take the notification" + ) diff --git a/backend/handler/notification_channels/channels.py b/backend/handler/notification_channels/channels.py index 684b1a2b9..7d01eb009 100644 --- a/backend/handler/notification_channels/channels.py +++ b/backend/handler/notification_channels/channels.py @@ -1,6 +1,6 @@ """Adding, changing, testing and confirming a user's notification channels.""" -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from datetime import datetime, timezone from typing import Any @@ -12,11 +12,19 @@ from models.notification_channel import ( NotificationChannel, NotificationChannelMinLevel, NotificationChannelType, - WebhookFormat, ) from models.user import User -from .config import EmailConfig, WebhookConfig, origin, read_config, seal_config +from . import apprise_channel +from .apprise_channel import AppriseService, FieldValue +from .config import ( + AppriseConfig, + EmailConfig, + WebhookConfig, + origin, + read_config, + seal_config, +) from .confirmation import check_code, issue_code from .delivery import ( describe_error, @@ -31,16 +39,40 @@ class ChannelError(ValueError): """A change the channel can't take, worded for the user.""" -def _webhook_config( - url: str, format: WebhookFormat, secret: str | None, user: User -) -> WebhookConfig: - """A webhook's config once its URL checks out; Discord takes no secret.""" +def _require_apprise(user: User) -> None: + if not may_reach_private_network(user.role): + raise ChannelError(apprise_channel.ADMINS_ONLY) + + +def _apprise_config( + service: str, fields: Mapping[str, FieldValue], user: User +) -> AppriseConfig: + """An Apprise channel's config once its owner and fields check out.""" + _require_apprise(user) try: - check_url(url, format, allow_private=may_reach_private_network(user.role)) + apprise_channel.check(service, fields) except ValueError as exc: raise ChannelError(str(exc)) from exc - secret = None if format == WebhookFormat.DISCORD else secret - return WebhookConfig(url=url, format=format, secret=secret or None) + return AppriseConfig(service=service, fields=dict(fields)) + + +def apprise_services(user: User) -> tuple[AppriseService, ...]: + """The services an Apprise channel can go out on. + + Raises: + ChannelError: The user isn't an admin. + """ + _require_apprise(user) + return apprise_channel.services() + + +def _webhook_config(url: str, secret: str | None, user: User) -> WebhookConfig: + """A webhook's config once its URL checks out.""" + try: + check_url(url, allow_private=may_reach_private_network(user.role)) + except ValueError as exc: + raise ChannelError(str(exc)) from exc + return WebhookConfig(url=url, secret=secret or None) def _require_email() -> None: @@ -56,9 +88,10 @@ async def create_channel( topics: Sequence[NotificationTopic] | None, *, url: str | None = None, - format: WebhookFormat = WebhookFormat.JSON, secret: str | None = None, address: str | None = None, + service: str | None = None, + fields: Mapping[str, FieldValue] | None = None, ) -> NotificationChannel: """Add a channel; an email address gets a code to confirm it with first. @@ -67,18 +100,23 @@ async def create_channel( CodeCooldownError, EmailError: The confirmation code could not go out, in which case the channel is not kept. """ - config: WebhookConfig | EmailConfig - if type == NotificationChannelType.EMAIL: - _require_email() - if not address: - raise ChannelError("An email channel needs an address") - config = EmailConfig(address=address) - confirmed_at = None - else: - if not url: - raise ChannelError("A webhook needs a URL") - config = _webhook_config(url, format, secret, user) - confirmed_at = datetime.now(timezone.utc) + config: AppriseConfig | WebhookConfig | EmailConfig + confirmed_at: datetime | None = datetime.now(timezone.utc) + match type: + case NotificationChannelType.EMAIL: + _require_email() + if not address: + raise ChannelError("An email channel needs an address") + config = EmailConfig(address=address) + confirmed_at = None + case NotificationChannelType.APPRISE: + if not service: + raise ChannelError("An Apprise channel needs a service") + config = _apprise_config(service, fields or {}, user) + case _: + if not url: + raise ChannelError("A webhook needs a URL") + config = _webhook_config(url, secret, user) channel = db_notification_channel_handler.add_channel( NotificationChannel( @@ -114,16 +152,17 @@ async def update_channel( changes: dict[str, Any], *, url: str | None = None, - format: WebhookFormat | None = None, secret: str | None = None, secret_given: bool = False, address: str | None = None, + fields: Mapping[str, FieldValue] | None = None, ) -> NotificationChannel: """Change a channel; a new email address has to be confirmed again. Args: changes: New values for the name, `enabled`, `min_level` and `topics`. secret_given: Whether `secret` was sent, since an empty one drops it. + fields: An Apprise channel's fields, where a secret left out stays. Raises: ChannelError: The change can't be made as asked. @@ -136,33 +175,38 @@ async def update_channel( changes["consecutive_failures"] = 0 config = read_config(channel.config) - if channel.type == NotificationChannelType.EMAIL: - if address and address != config.get("address"): - _require_email() - # The code goes out first, so an address it can't reach isn't kept. - await issue_code(channel.id, user.id, address) - changes["config"] = seal_config(EmailConfig(address=address)) - changes["confirmed_at"] = None - elif url or format or secret_given: - new_url = url or config.get("url") - new_format = WebhookFormat(format or config.get("format") or WebhookFormat.JSON) - if not new_url: - raise ChannelError("The channel needs its URL again") - new_config = _webhook_config( - new_url, - new_format, - secret if secret_given else config.get("secret"), - user, - ) - moved = new_format != config.get("format") or origin(new_url) != origin( - config.get("url", "") - ) - # A kept secret only goes where it was given for. - if moved and not secret_given and new_config.get("secret"): - raise ChannelError( - "Enter the secret again for the new URL or format, or remove it" + match channel.type: + case NotificationChannelType.EMAIL: + if address and address != config.get("address"): + _require_email() + # The code goes out first, so an address it can't reach isn't kept. + await issue_code(channel.id, user.id, address) + changes["config"] = seal_config(EmailConfig(address=address)) + changes["confirmed_at"] = None + case NotificationChannelType.APPRISE: + if fields is not None: + service = config.get("service", "") + try: + merged = apprise_channel.merge_fields( + service, config.get("fields", {}), fields + ) + except ValueError as exc: + raise ChannelError(str(exc)) from exc + changes["config"] = seal_config(_apprise_config(service, merged, user)) + case _ if url or secret_given: + new_url = url or config.get("url") + if not new_url: + raise ChannelError("The channel needs its URL again") + new_config = _webhook_config( + new_url, secret if secret_given else config.get("secret"), user ) - changes["config"] = seal_config(new_config) + moved = origin(new_url) != origin(config.get("url", "")) + # A kept secret only goes where it was given for. + if moved and not secret_given and new_config.get("secret"): + raise ChannelError( + "Enter the secret again for the new URL, or remove it" + ) + changes["config"] = seal_config(new_config) if not changes: return channel diff --git a/backend/handler/notification_channels/config.py b/backend/handler/notification_channels/config.py index 8334aaa7c..8caf8411b 100644 --- a/backend/handler/notification_channels/config.py +++ b/backend/handler/notification_channels/config.py @@ -6,10 +6,15 @@ from urllib.parse import urlsplit from utils.secret_box import UnsealError, seal, unseal +class AppriseConfig(TypedDict): + service: str + # What the owner filled in, which the Apprise URL is built from. + fields: dict[str, Any] + + class WebhookConfig(TypedDict): url: str - format: str - # The HMAC key of a JSON webhook, or the access token of an ntfy topic. + # The key the payload is signed with. secret: NotRequired[str | None] @@ -17,7 +22,7 @@ class EmailConfig(TypedDict): address: str -def seal_config(config: WebhookConfig | EmailConfig) -> str: +def seal_config(config: AppriseConfig | WebhookConfig | EmailConfig) -> str: return seal(dict(config)) diff --git a/backend/handler/notification_channels/delivery.py b/backend/handler/notification_channels/delivery.py index aec68f602..689a5537f 100644 --- a/backend/handler/notification_channels/delivery.py +++ b/backend/handler/notification_channels/delivery.py @@ -18,7 +18,8 @@ from models.notification_channel import NotificationChannel, NotificationChannel from models.user import Role from utils.secret_box import unseal -from . import webhook +from . import apprise_channel, webhook +from .apprise_channel import AppriseError from .config import WebhookConfig from .messages import OutboundMessage, render @@ -89,26 +90,31 @@ async def send_to_channel( Raises: UnsealError: ROMM_AUTH_SECRET_KEY changed since the channel was saved. - WebhookError, EmailError: The delivery failed. + AppriseError, WebhookError, EmailError: The delivery failed. """ config = unseal(channel.config) - if channel.type == NotificationChannelType.EMAIL: - text = "\n\n".join(part for part in (message.body, message.url) if part) - await asyncio.to_thread( - send_email, - config["address"], - f"[RomM] {message.title}", - text or message.title, - ) - else: - await webhook.send( - WebhookConfig( - url=config["url"], format=config["format"], secret=config.get("secret") - ), - message, - allow_private=allow_private, - channel_name=channel.name, - ) + match channel.type: + case NotificationChannelType.APPRISE: + # Apprise opens its own connections, past the SSRF guard. + if not allow_private: + raise AppriseError(apprise_channel.ADMINS_ONLY) + await asyncio.to_thread( + apprise_channel.send, config["service"], config["fields"], message + ) + case NotificationChannelType.EMAIL: + text = "\n\n".join(part for part in (message.body, message.url) if part) + await asyncio.to_thread( + send_email, + config["address"], + f"[RomM] {message.title}", + text or message.title, + ) + case _: + await webhook.send( + WebhookConfig(url=config["url"], secret=config.get("secret")), + message, + allow_private=allow_private, + ) def sample_message() -> OutboundMessage: diff --git a/backend/handler/notification_channels/webhook.py b/backend/handler/notification_channels/webhook.py index 373412078..7ca782ca7 100644 --- a/backend/handler/notification_channels/webhook.py +++ b/backend/handler/notification_channels/webhook.py @@ -1,4 +1,4 @@ -"""Webhook deliveries: RomM's own JSON, a Discord embed or an ntfy message.""" +"""Webhook deliveries: RomM's own JSON, signed when the channel has a secret.""" import asyncio import hashlib @@ -6,13 +6,11 @@ import hmac import json from dataclasses import dataclass from typing import Any, Final -from urllib.parse import urlsplit, urlunsplit +from urllib.parse import urlsplit import httpx from config import has_proxy_env -from models.notification import NotificationLevel -from models.notification_channel import WebhookFormat from utils.context import create_httpx_async_client from utils.ssrf import validate_url_for_http_request from utils.validation import ValidationError @@ -26,22 +24,6 @@ SIGNATURE_HEADER: Final = "X-RomM-Signature" ERROR_DETAIL_BYTES: Final = 1024 ERROR_DETAIL_CHARS: Final = 200 -DISCORD_COLORS: Final[dict[str, int]] = { - NotificationLevel.INFO: 0x3498DB, - NotificationLevel.SUCCESS: 0x2ECC71, - NotificationLevel.WARNING: 0xF1C40F, - NotificationLevel.ERROR: 0xE74C3C, -} -NTFY_TAGS: Final[dict[str, str]] = { - NotificationLevel.INFO: "information_source", - NotificationLevel.SUCCESS: "white_check_mark", - NotificationLevel.WARNING: "warning", - NotificationLevel.ERROR: "rotating_light", -} -# ntfy's scale runs 1 to 5, where 3 is the default and 4 is high. -NTFY_ERROR_PRIORITY: Final = 4 -NTFY_DEFAULT_PRIORITY: Final = 3 - class WebhookError(RuntimeError): """The destination refused the delivery or could not be reached.""" @@ -54,22 +36,7 @@ class WebhookRequest: headers: dict[str, str] -def split_ntfy_url(url: str) -> tuple[str, str]: - """The server a topic URL points at and the topic, for ntfy's JSON publishing. - - Raises: - ValueError: The URL names no topic. - """ - parts = urlsplit(url) - base_path, _, topic = parts.path.rstrip("/").rpartition("/") - if not topic: - raise ValueError( - "An ntfy URL ends with its topic, such as https://ntfy.sh/romm" - ) - return urlunsplit((parts.scheme, parts.netloc, base_path or "/", "", "")), topic - - -def check_url(url: str, format: WebhookFormat, allow_private: bool) -> None: +def check_url(url: str, allow_private: bool) -> None: """Refuse a webhook URL that can never be delivered to. Args: @@ -93,8 +60,6 @@ def check_url(url: str, format: WebhookFormat, allow_private: bool) -> None: validate_url_for_http_request(url) except ValidationError as exc: raise ValueError(exc.message) from exc - if format == WebhookFormat.NTFY: - split_ntfy_url(url) def _json_payload(message: OutboundMessage) -> dict[str, Any]: @@ -113,77 +78,20 @@ def _json_payload(message: OutboundMessage) -> dict[str, Any]: } -def _discord_payload(message: OutboundMessage, channel_name: str) -> dict[str, Any]: - n = message.notification - embed: dict[str, Any] = { - # Discord's own limits on an embed's title and description. - "title": message.title[:256], - "color": DISCORD_COLORS.get(n.level, DISCORD_COLORS[NotificationLevel.INFO]), - "timestamp": n.created_at.isoformat(), - } - if message.body: - embed["description"] = message.body[:4096] - if message.url: - embed["url"] = message.url - footer = [channel_name, f"From {n.actor.username}" if n.actor else ""] - embed["footer"] = {"text": " · ".join(part for part in footer if part)[:2048]} - # A user's own text must not ping @everyone or a role. - return {"username": "RomM", "embeds": [embed], "allowed_mentions": {"parse": []}} - - -def _ntfy_payload(message: OutboundMessage, topic: str) -> dict[str, Any]: - n = message.notification - payload: dict[str, Any] = { - "topic": topic, - "title": message.title, - "message": message.body or message.title, - "priority": ( - NTFY_ERROR_PRIORITY - if n.level == NotificationLevel.ERROR - else NTFY_DEFAULT_PRIORITY - ), - "tags": [NTFY_TAGS.get(n.level, NTFY_TAGS[NotificationLevel.INFO])], - } - if message.url: - payload["click"] = message.url - return payload - - -def build_request( - config: WebhookConfig, message: OutboundMessage, channel_name: str = "" -) -> WebhookRequest: - """The request a webhook gets for a message. - - Args: - channel_name: What the owner called the channel, which a Discord embed - shows in its footer. - """ +def build_request(config: WebhookConfig, message: OutboundMessage) -> WebhookRequest: + """The request a webhook gets for a message.""" # Identity, so a refusal's body is read as sent rather than decompressed. headers = { "Content-Type": "application/json", "User-Agent": "RomM", "Accept-Encoding": "identity", } + content = json.dumps(_json_payload(message)).encode() secret = config.get("secret") - url = config["url"] - - match config["format"]: - case WebhookFormat.DISCORD: - payload = _discord_payload(message, channel_name) - case WebhookFormat.NTFY: - # JSON publishing takes non-ASCII titles that headers can't carry. - url, topic = split_ntfy_url(url) - payload = _ntfy_payload(message, topic) - if secret: - headers["Authorization"] = f"Bearer {secret}" - case _: - payload = _json_payload(message) - - content = json.dumps(payload).encode() - if secret and config["format"] == WebhookFormat.JSON: + if secret: digest = hmac.new(secret.encode(), content, hashlib.sha256).hexdigest() headers[SIGNATURE_HEADER] = f"sha256={digest}" - return WebhookRequest(url=url, content=content, headers=headers) + return WebhookRequest(url=config["url"], content=content, headers=headers) def _client(allow_private: bool) -> httpx.AsyncClient: @@ -205,17 +113,14 @@ async def _error_detail(response: httpx.Response) -> str: async def send( - config: WebhookConfig, - message: OutboundMessage, - allow_private: bool, - channel_name: str = "", + config: WebhookConfig, message: OutboundMessage, allow_private: bool ) -> None: """POST the message to the webhook, giving it TIMEOUT_SECONDS in all. Raises: WebhookError: The destination refused it, or could not be reached. """ - request = build_request(config, message, channel_name) + request = build_request(config, message) host = urlsplit(request.url).hostname try: async with ( diff --git a/backend/models/notification_channel.py b/backend/models/notification_channel.py index f113a44b6..ea2e6c871 100644 --- a/backend/models/notification_channel.py +++ b/backend/models/notification_channel.py @@ -12,16 +12,13 @@ from utils.database import CustomJSON class NotificationChannelType(enum.StrEnum): + # Any service Apprise speaks to, from one URL. + APPRISE = "apprise" + # RomM's own JSON payload, signed when the channel has a secret. WEBHOOK = "webhook" EMAIL = "email" -class WebhookFormat(enum.StrEnum): - JSON = "json" - DISCORD = "discord" - NTFY = "ntfy" - - class NotificationChannelMinLevel(enum.StrEnum): """The least severe notification a channel forwards; success ranks as info.""" @@ -36,6 +33,9 @@ NOTIFICATION_CHANNEL_SECRET_MAX_LENGTH: Final = 255 NOTIFICATION_CHANNEL_ERROR_MAX_LENGTH: Final = 1000 NOTIFICATION_CHANNEL_ADDRESS_MAX_LENGTH: Final = 320 NOTIFICATION_CHANNEL_CODE_MAX_LENGTH: Final = 16 +NOTIFICATION_CHANNEL_SERVICE_MAX_LENGTH: Final = 32 +# An Apprise service's fields: the most any has, with room to spare. +NOTIFICATION_CHANNEL_MAX_FIELDS: Final = 64 MAX_NOTIFICATION_CHANNELS_PER_USER: Final = 20 # A channel that fails this many deliveries in a row turns itself off. MAX_CONSECUTIVE_DELIVERY_FAILURES: Final = 10 @@ -51,7 +51,7 @@ class NotificationChannel(BaseModel): ) type: Mapped[str] = mapped_column(String(16)) name: Mapped[str] = mapped_column(String(NOTIFICATION_CHANNEL_NAME_MAX_LENGTH)) - # Sealed with `utils.secret_box`: a webhook URL can carry its own token. + # Sealed with `utils.secret_box`: a URL can carry its own token. config: Mapped[str] = mapped_column(Text) min_level: Mapped[str] = mapped_column(String(16), default="info") # None forwards every topic. diff --git a/backend/tests/endpoints/test_notification_channels.py b/backend/tests/endpoints/test_notification_channels.py index 1927c7735..72a4a9491 100644 --- a/backend/tests/endpoints/test_notification_channels.py +++ b/backend/tests/endpoints/test_notification_channels.py @@ -23,6 +23,18 @@ def _webhook(url: str = "https://hooks.example.com/romm/token", **fields) -> dic return {"type": "webhook", "name": "Hook", "url": url, **fields} +_DISCORD = {"webhook_id": "1234567890", "webhook_token": "abcdefghijklmnop"} + + +def _apprise(service: str = "discord", **fields) -> dict: + return { + "type": "apprise", + "name": "Discord", + "service": service, + "fields": fields or _DISCORD, + } + + @pytest.fixture def emailed(mocker): mocker.patch.object(channels, "EMAIL_ENABLED", True) @@ -37,7 +49,7 @@ def sent(mocker): class TestCreate: def test_a_webhook_hides_its_token(self, client, access_token): response = client.post( - API, json=_webhook(secret="k", format="json"), headers=_auth(access_token) + API, json=_webhook(secret="k"), headers=_auth(access_token) ) assert response.status_code == status.HTTP_201_CREATED @@ -64,6 +76,37 @@ class TestCreate: assert response.status_code == status.HTTP_400_BAD_REQUEST + def test_an_admin_forwards_through_apprise(self, client, access_token): + response = client.post( + API, json=_apprise(**_DISCORD, botname="RomM"), headers=_auth(access_token) + ) + + assert response.status_code == status.HTTP_201_CREATED + body = response.json() + assert (body["type"], body["service"], body["service_name"]) == ( + "apprise", + "discord", + "Discord", + ) + assert body["target"] == "discord://RomM@1...0/a...p/" + assert body["fields"] == {"botname": "RomM"} + assert "abcdefghijklmnop" not in response.text + + def test_a_user_may_not_use_apprise(self, client, viewer_access_token): + response = client.post(API, json=_apprise(), headers=_auth(viewer_access_token)) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + assert response.json()["detail"] == "Only admins can use Apprise channels" + + @pytest.mark.parametrize( + "payload", + [_apprise("syslog", host="localhost"), _apprise(webhook_id="1234567890")], + ) + def test_fields_apprise_cannot_use_are_refused(self, client, access_token, payload): + response = client.post(API, json=payload, headers=_auth(access_token)) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + def test_a_user_has_at_most_so_many(self, client, access_token): for n in range(MAX_NOTIFICATION_CHANNELS_PER_USER): created = client.post( @@ -83,6 +126,7 @@ class TestCreate: [ {"type": "sms", "name": "x", "url": "https://example.com"}, {"type": "email", "name": "x", "address": "not-an-address"}, + {"type": "apprise", "name": "x", "service": "discord"}, _webhook(topics=["everything"]), _webhook(name=""), ], @@ -118,6 +162,28 @@ class TestCreate: assert db_notification_channel_handler.get_channels(admin_user.id) == [] +class TestAppriseServices: + def test_an_admin_gets_each_service_with_its_fields(self, client, access_token): + response = client.get(f"{API}/apprise-services", headers=_auth(access_token)) + + assert response.status_code == status.HTTP_200_OK + discord = next(s for s in response.json() if s["id"] == "discord") + token = next(f for f in discord["fields"] if f["key"] == "webhook_token") + assert discord["name"] == "Discord" + assert (token["required"], token["private"], token["advanced"]) == ( + True, + True, + False, + ) + + def test_a_user_gets_none(self, client, viewer_access_token): + response = client.get( + f"{API}/apprise-services", headers=_auth(viewer_access_token) + ) + + assert response.status_code == status.HTTP_403_FORBIDDEN + + class TestEmailConfirmation: def test_the_emailed_code_confirms_the_address(self, client, access_token, emailed): created = client.post( @@ -215,6 +281,22 @@ class TestUpdate: assert body["has_secret"] is False assert body["enabled"] is False + def test_apprise_secrets_stay_until_given_again(self, client, access_token): + created = client.post(API, json=_apprise(), headers=_auth(access_token)).json() + path = f"{API}/{created['id']}" + + renamed = client.patch( + path, json={"name": "Phone"}, headers=_auth(access_token) + ) + retitled = client.patch( + path, + json={"fields": {"webhook_id": "1234567890", "botname": "Bot"}}, + headers=_auth(access_token), + ) + + assert renamed.json()["target"] == created["target"] + assert retitled.json()["target"] == "discord://Bot@1...0/a...p/" + def test_null_topics_forwards_everything_again(self, client, access_token): created = client.post( API, json=_webhook(topics=["scans"]), headers=_auth(access_token) diff --git a/backend/tests/handler/notification_channels/test_apprise_channel.py b/backend/tests/handler/notification_channels/test_apprise_channel.py new file mode 100644 index 000000000..120f37908 --- /dev/null +++ b/backend/tests/handler/notification_channels/test_apprise_channel.py @@ -0,0 +1,274 @@ +import logging +from typing import Any + +import pytest +from apprise import Apprise, NotifyFormat, NotifyType + +from handler.notification_channels import apprise_channel +from handler.notification_channels.apprise_channel import ( + AppriseError, + FieldValue, + build_url, + check, + describe, + find_service, + merge_fields, + public_fields, + send, + services, +) +from handler.notification_channels.messages import OutboundMessage +from models.notification import NotificationLevel + +from .fixtures import make_notification + +_DISCORD = {"webhook_id": "1234567890", "webhook_token": "abcdefghijklmnop"} +_JSON = {"host": "hooks.example.com", "path": "romm"} + + +def _message(**overrides: Any) -> OutboundMessage: + fields: dict[str, Any] = { + "notification": make_notification(), + "title": "Maintenance tonight", + "body": "RomM restarts at 23:00", + "url": "https://romm.example.com/platforms", + } + return OutboundMessage(**{**fields, **overrides}) + + +def _keys(service_id: str, advanced: bool = False) -> list[str]: + return [f.key for f in find_service(service_id).fields if f.advanced is advanced] + + +class TestCatalog: + def test_lists_what_apprise_reaches_but_nothing_local(self): + ids = [service.id for service in services()] + + assert {"discord", "ntfy", "tgram", "json"} <= set(ids) + assert "syslog" not in ids + names = [service.name.lower() for service in services()] + assert names == sorted(names) + + def test_requires_only_what_every_template_needs(self): + discord = find_service("discord") + slack = find_service("slack") + + assert [f.key for f in discord.fields if f.required] == [ + "webhook_id", + "webhook_token", + ] + # A bot token or three webhook tokens: neither is needed by both. + assert not any(f.required for f in slack.fields) + + def test_a_list_stands_in_for_its_singular_tokens(self): + targets = find_service("ntfy").field("targets") + + assert "topic" not in _keys("ntfy") + assert targets is not None + assert (targets.type, targets.required) == ("list", True) + + def test_offers_the_schema_only_when_there_is_a_choice(self): + schema = find_service("ntfy").field("schema") + + assert schema is not None + assert (schema.values, schema.default) == (("ntfy", "ntfys"), "ntfys") + assert find_service("discord").field("schema") is None + + def test_leaves_out_options_romm_sets_or_that_read_files(self): + options = _keys("discord", advanced=True) + + assert "ping" in options + assert not {"template", "cto", "rto", "retry", "redirect", "url"} & set(options) + + def test_json_takes_a_path_after_its_host(self): + assert "path" in _keys("json") + + +class TestBuildUrl: + @pytest.mark.parametrize( + "service,fields,url", + [ + ("discord", _DISCORD, "discord://1234567890/abcdefghijklmnop"), + ( + "discord", + {**_DISCORD, "botname": "RomM", "image": True, "ping": ["@here"]}, + "discord://RomM@1234567890/abcdefghijklmnop?image=yes&ping=%40here", + ), + ("ntfy", {"targets": ["romm"]}, "ntfys://romm"), + ( + "ntfy", + {"host": "ntfy.example.com", "targets": ["romm"], "token": "tk_1"}, + "ntfys://tk_1@ntfy.example.com/romm", + ), + ( + "ntfy", + { + "schema": "ntfy", + "host": "192.168.1.5", + "port": 8080, + "user": "me", + "password": "p@ss/word", + "targets": ["a", "b"], + }, + "ntfy://me:p%40ss%2Fword@192.168.1.5:8080/a/b", + ), + ( + "gotify", + {"host": "push.example.com", "path": "gotify", "token": "abc"}, + "gotifys://push.example.com/gotify/abc", + ), + ( + "json", + {"host": "hooks.example.com", "path": "/api/romm"}, + "jsons://hooks.example.com/api/romm", + ), + ], + ) + def test_fills_in_the_template_the_fields_make_up(self, service, fields, url): + assert build_url(service, fields) == url + check(service, fields) + + def test_says_what_is_missing(self): + with pytest.raises(ValueError, match="^Discord needs Webhook Token$"): + build_url("discord", {"webhook_id": "1234567890"}) + + def test_refuses_fields_no_template_takes_together(self): + fields: dict[str, FieldValue] = { + "host": "h.example.com", + "targets": ["a"], + "user": "u", + "token": "t", + } + + with pytest.raises(ValueError, match="can't take these fields together"): + build_url("ntfy", {**fields, "password": "p"}) + + def test_a_host_is_only_a_host(self): + with pytest.raises(ValueError, match="isn't a hostname"): + build_url("json", {"host": "example.com/hook?x=1"}) + + def test_ignores_fields_the_form_never_offered(self): + url = build_url("discord", {**_DISCORD, "template": "/etc/passwd"}) + + assert "template" not in url + + @pytest.mark.parametrize("service", ["syslog", "nowhere"]) + def test_knows_only_the_services_it_lists(self, service): + with pytest.raises(ValueError, match="no such service"): + build_url(service, {}) + + +class TestFields: + def test_describes_the_service_and_hides_its_token(self): + assert describe("discord", _DISCORD) == ("Discord", "discord://1...0/a...p/") + + def test_describes_fields_it_can_no_longer_use_as_nothing(self): + assert describe("discord", {}) == (None, "") + + def test_keeps_the_secrets_out_of_what_the_form_gets_back(self): + assert public_fields("discord", {**_DISCORD, "botname": "RomM"}) == { + "botname": "RomM" + } + + def test_an_edit_keeps_the_secrets_it_leaves_blank(self): + stored = {**_DISCORD, "botname": "RomM"} + + merged = merge_fields("discord", stored, {"webhook_token": "", "botname": ""}) + + assert merged == _DISCORD + + +class TestSend: + @pytest.fixture + def notify(self, mocker): + """Stands in for Apprise's notify; keeps what it got and returns `result`.""" + calls: list[tuple[Apprise, dict[str, Any]]] = [] + + def install(result: bool = True, log: Any = None): + def fake(self: Apprise, **kwargs: Any) -> bool: + calls.append((self, kwargs)) + if log: + log() + return result + + mocker.patch.object(apprise_channel.Apprise, "notify", fake) + return calls + + return install + + def test_sends_the_title_body_and_link(self, notify): + calls = notify() + + send("json", _JSON, _message()) + + [(_, kwargs)] = calls + assert kwargs == { + "title": "Maintenance tonight", + "body": "RomM restarts at 23:00\n\nhttps://romm.example.com/platforms", + "notify_type": NotifyType.INFO, + "body_format": NotifyFormat.TEXT, + } + + def test_a_title_alone_is_also_the_body(self, notify): + calls = notify() + + send("json", _JSON, _message(body=None, url=None)) + + [(_, kwargs)] = calls + assert kwargs["body"] == "Maintenance tonight" + + @pytest.mark.parametrize( + "level,notify_type", + [ + (NotificationLevel.INFO, NotifyType.INFO), + (NotificationLevel.SUCCESS, NotifyType.SUCCESS), + (NotificationLevel.WARNING, NotifyType.WARNING), + (NotificationLevel.ERROR, NotifyType.FAILURE), + ], + ) + def test_carries_the_level(self, notify, level, notify_type): + calls = notify() + + send("json", _JSON, _message(notification=make_notification(level=level))) + + [(_, kwargs)] = calls + assert kwargs["notify_type"] == notify_type + + def test_holds_a_service_to_its_own_limits(self, notify): + calls = notify() + + # Apprise gives email 15 seconds to connect. + send("mailto", {"host": "smtp.example.com", "user": "me"}, _message()) + + [(apprise, _)] = calls + plugin = apprise[0] + assert plugin.socket_connect_timeout == apprise_channel.CONNECT_TIMEOUT_SECONDS + assert (plugin.retry, plugin.redirects) == (0, False) + + def test_a_refusal_says_what_apprise_warned_but_not_the_reply(self, notify): + def log(): + logger = logging.getLogger("apprise") + logger.warning("Failed to send JSON POST notification: error=500.") + logger.debug("Response Details: internal secret") + + notify(result=False, log=log) + + with pytest.raises(AppriseError) as caught: + send("json", _JSON, _message()) + + assert str(caught.value) == "Failed to send JSON POST notification: error=500." + + def test_keeps_no_warning_logged_outside_a_send(self, notify): + logging.getLogger("apprise").warning("Something from another send") + notify(result=False) + + with pytest.raises(AppriseError, match="^JSON did not take the notification$"): + send("json", _JSON, _message()) + + def test_an_unreachable_service_is_an_apprise_error(self): + with pytest.raises(AppriseError, match="Connection error"): + send( + "json", + {"schema": "json", "host": "127.0.0.1", "port": 1}, + _message(), + ) diff --git a/backend/tests/handler/notification_channels/test_channels.py b/backend/tests/handler/notification_channels/test_channels.py index 3a39d6f5a..5f810adc0 100644 --- a/backend/tests/handler/notification_channels/test_channels.py +++ b/backend/tests/handler/notification_channels/test_channels.py @@ -18,12 +18,12 @@ from handler.notification_channels.confirmation import CodeCooldownError from models.notification_channel import ( NotificationChannelMinLevel, NotificationChannelType, - WebhookFormat, ) from models.user import Role ADMIN = MagicMock(id=1, role=Role.ADMIN) USER = MagicMock(id=2, role=Role.USER) +DISCORD = {"webhook_id": "1234567890", "webhook_token": "abcdefghijklmnop"} @pytest.fixture @@ -62,33 +62,60 @@ class TestCreate: channel = await create_channel( USER, NotificationChannelType.WEBHOOK, - "Discord", + "Hooks", NotificationChannelMinLevel.WARNING, None, - url="https://discord.com/api/webhooks/1/t", - format=WebhookFormat.DISCORD, + url="https://hooks.example.com/romm", ) assert channel.confirmed_at is not None assert read_config(channel.config) == { - "url": "https://discord.com/api/webhooks/1/t", - "format": "discord", + "url": "https://hooks.example.com/romm", "secret": None, } - async def test_a_discord_webhook_keeps_no_secret(self, db): + async def test_an_admin_forwards_through_apprise(self, db): channel = await create_channel( - USER, - NotificationChannelType.WEBHOOK, - "Discord", + ADMIN, + NotificationChannelType.APPRISE, + "Phone", NotificationChannelMinLevel.INFO, None, - url="https://discord.com/api/webhooks/1/t", - format=WebhookFormat.DISCORD, - secret="unused", + service="ntfy", + fields={"targets": ["romm"]}, ) - assert read_config(channel.config)["secret"] is None + assert channel.confirmed_at is not None + assert read_config(channel.config) == { + "service": "ntfy", + "fields": {"targets": ["romm"]}, + } + + async def test_a_user_may_not_use_apprise(self, db): + with pytest.raises(ChannelError, match="Only admins"): + await create_channel( + USER, + NotificationChannelType.APPRISE, + "Phone", + NotificationChannelMinLevel.INFO, + None, + service="ntfy", + fields={"targets": ["romm"]}, + ) + + db.add_channel.assert_not_called() + + async def test_fields_apprise_cannot_use_are_refused(self, db): + with pytest.raises(ChannelError, match="needs Webhook Token"): + await create_channel( + ADMIN, + NotificationChannelType.APPRISE, + "Discord", + NotificationChannelMinLevel.INFO, + None, + service="discord", + fields={"webhook_id": "1234567890"}, + ) async def test_a_user_stays_off_the_local_network(self, db): with pytest.raises(ChannelError): @@ -171,7 +198,7 @@ class TestCreate: class TestUpdate: async def test_keeps_the_secret_unless_given(self, db): - stored = _stored(url="https://hooks.example.com/a", format="json", secret="k") + stored = _stored(url="https://hooks.example.com/a", secret="k") updated = await update_channel( stored, USER, {}, url="https://hooks.example.com/b" @@ -179,41 +206,22 @@ class TestUpdate: assert read_config(updated.config) == { "url": "https://hooks.example.com/b", - "format": "json", "secret": "k", } @pytest.mark.parametrize( - "change", - [ - {"url": "https://elsewhere.example.com/a"}, - {"url": "https://hooks.example.com:8443/a"}, - {"format": WebhookFormat.NTFY}, - ], + "url", ["https://elsewhere.example.com/a", "https://hooks.example.com:8443/a"] ) - async def test_a_kept_secret_does_not_follow_it_elsewhere(self, db, change): - stored = _stored(url="https://hooks.example.com/a", format="json", secret="k") + async def test_a_kept_secret_does_not_follow_it_elsewhere(self, db, url): + stored = _stored(url="https://hooks.example.com/a", secret="k") with pytest.raises(ChannelError, match="secret again"): - await update_channel(stored, USER, {}, **change) + await update_channel(stored, USER, {}, url=url) db.update_channel.assert_not_called() - async def test_moving_to_discord_drops_the_secret_it_never_sends(self, db): - stored = _stored(url="https://hooks.example.com/a", format="json", secret="k") - - updated = await update_channel( - stored, - USER, - {}, - url="https://discord.com/api/webhooks/1/t", - format=WebhookFormat.DISCORD, - ) - - assert read_config(updated.config)["secret"] is None - async def test_a_secret_given_again_goes_to_the_new_url(self, db): - stored = _stored(url="https://hooks.example.com/a", format="json", secret="k") + stored = _stored(url="https://hooks.example.com/a", secret="k") updated = await update_channel( stored, @@ -227,14 +235,57 @@ class TestUpdate: assert read_config(updated.config)["secret"] == "k2" async def test_an_empty_secret_drops_it(self, db): - stored = _stored(url="https://hooks.example.com/a", format="json", secret="k") + stored = _stored(url="https://hooks.example.com/a", secret="k") updated = await update_channel(stored, USER, {}, secret="", secret_given=True) assert read_config(updated.config)["secret"] is None + async def test_apprise_fields_left_out_stay(self, db): + stored = _stored( + NotificationChannelType.APPRISE, service="discord", fields=DISCORD + ) + + await update_channel(stored, ADMIN, {"name": "Phone"}) + + db.update_channel.assert_called_once_with(4, ADMIN.id, {"name": "Phone"}) + + async def test_an_apprise_secret_left_blank_stays(self, db): + stored = _stored( + NotificationChannelType.APPRISE, service="discord", fields=DISCORD + ) + + updated = await update_channel( + stored, ADMIN, {}, fields={"webhook_id": "987654321", "botname": "RomM"} + ) + + assert read_config(updated.config)["fields"] == { + "webhook_id": "987654321", + "webhook_token": DISCORD["webhook_token"], + "botname": "RomM", + } + + async def test_new_apprise_fields_are_checked(self, db): + stored = _stored( + NotificationChannelType.APPRISE, service="ntfy", fields={"targets": ["a"]} + ) + + with pytest.raises(ChannelError, match="ntfy needs Targets"): + await update_channel(stored, ADMIN, {}, fields={"targets": []}) + + db.update_channel.assert_not_called() + + async def test_a_demoted_admin_can_rename_but_not_repoint_it(self, db): + stored = _stored( + NotificationChannelType.APPRISE, service="discord", fields=DISCORD + ) + + await update_channel(stored, USER, {"name": "Old phone"}) + with pytest.raises(ChannelError, match="Only admins"): + await update_channel(stored, USER, {}, fields=DISCORD) + async def test_turning_it_back_on_forgets_past_failures(self, db): - stored = _stored(url="https://hooks.example.com/a", format="json") + stored = _stored(url="https://hooks.example.com/a") stored.enabled = False updated = await update_channel(stored, USER, {"enabled": True}) diff --git a/backend/tests/handler/notification_channels/test_delivery.py b/backend/tests/handler/notification_channels/test_delivery.py index 948940c16..f37fff322 100644 --- a/backend/tests/handler/notification_channels/test_delivery.py +++ b/backend/tests/handler/notification_channels/test_delivery.py @@ -1,15 +1,20 @@ -from unittest.mock import MagicMock +from unittest.mock import AsyncMock, MagicMock import pytest -from handler.notification_channels import delivery +from handler.notification_channels import apprise_channel, delivery, webhook +from handler.notification_channels.apprise_channel import AppriseError +from handler.notification_channels.config import seal_config from handler.notification_channels.delivery import ( deliver_to_channel, enqueue_channel_deliveries, forwards, + sample_message, + send_to_channel, ) from handler.notification_channels.webhook import WebhookError from models.notification import NotificationKind, NotificationLevel, NotificationTopic +from models.notification_channel import NotificationChannelType from models.user import Role from .fixtures import make_notification @@ -88,6 +93,44 @@ class TestEnqueue: enqueue_channel_deliveries([(5, make_notification())]) +class TestSendToChannel: + async def test_an_apprise_channel_goes_out_through_apprise(self, mocker): + send = mocker.patch.object(apprise_channel, "send") + channel = _channel( + type=NotificationChannelType.APPRISE, + config=seal_config({"service": "ntfy", "fields": {"targets": ["romm"]}}), + ) + message = sample_message() + + await send_to_channel(channel, message, allow_private=True) + + send.assert_called_once_with("ntfy", {"targets": ["romm"]}, message) + + async def test_only_an_admins_apprise_channel_goes_out(self, mocker): + send = mocker.patch.object(apprise_channel, "send") + channel = _channel( + type=NotificationChannelType.APPRISE, + config=seal_config({"service": "ntfy", "fields": {"targets": ["romm"]}}), + ) + + with pytest.raises(AppriseError, match="Only admins"): + await send_to_channel(channel, sample_message(), allow_private=False) + + send.assert_not_called() + + async def test_a_webhook_gets_its_url_and_secret(self, mocker): + send = mocker.patch.object(webhook, "send", AsyncMock()) + channel = _channel( + type=NotificationChannelType.WEBHOOK, + config=seal_config({"url": "https://hooks.example.com", "secret": "k"}), + ) + + await send_to_channel(channel, sample_message(), allow_private=False) + + config, _ = send.await_args.args + assert config == {"url": "https://hooks.example.com", "secret": "k"} + + class TestDeliverToChannel: @pytest.fixture def db(self, mocker): diff --git a/backend/tests/handler/notification_channels/test_webhook.py b/backend/tests/handler/notification_channels/test_webhook.py index 9ae0b0dc6..ff4fed7e6 100644 --- a/backend/tests/handler/notification_channels/test_webhook.py +++ b/backend/tests/handler/notification_channels/test_webhook.py @@ -14,10 +14,7 @@ from handler.notification_channels.webhook import ( build_request, check_url, send, - split_ntfy_url, ) -from models.notification import NotificationLevel -from models.notification_channel import WebhookFormat from .fixtures import make_actor, make_notification @@ -31,10 +28,10 @@ def _message(**overrides) -> OutboundMessage: ) -class TestJsonFormat: +class TestBuildRequest: def test_carries_the_notification_and_its_text(self): request = build_request( - WebhookConfig(url="https://hooks.example.com/romm", format="json"), + WebhookConfig(url="https://hooks.example.com/romm"), _message(actor=make_actor()), ) @@ -48,7 +45,7 @@ class TestJsonFormat: def test_is_signed_with_the_secret(self): request = build_request( - WebhookConfig(url="https://hooks.example.com", format="json", secret="k"), + WebhookConfig(url="https://hooks.example.com", secret="k"), _message(), ) @@ -56,101 +53,18 @@ class TestJsonFormat: assert request.headers[webhook.SIGNATURE_HEADER] == f"sha256={expected}" -class TestDiscordFormat: - def test_sends_an_embed_that_pings_nobody(self): - request = build_request( - WebhookConfig(url="https://discord.com/api/webhooks/1/t", format="discord"), - _message(level=NotificationLevel.ERROR, actor=make_actor()), - "#romm", - ) - - payload = json.loads(request.content) - [embed] = payload["embeds"] - assert embed["title"] == "Maintenance tonight" - assert embed["description"] == "RomM restarts at 23:00" - assert embed["url"] == "https://romm.example.com/platforms" - assert embed["color"] == webhook.DISCORD_COLORS[NotificationLevel.ERROR] - assert embed["footer"] == {"text": "#romm · From admin"} - assert payload["allowed_mentions"] == {"parse": []} - - def test_names_the_channel_alone_without_a_sender(self): - request = build_request( - WebhookConfig(url="https://discord.com/api/webhooks/1/t", format="discord"), - _message(), - "#romm", - ) - - [embed] = json.loads(request.content)["embeds"] - assert embed["footer"] == {"text": "#romm"} - - def test_keeps_within_discords_limits(self): - message = OutboundMessage( - notification=make_notification(), - title="t" * 300, - body="b" * 5000, - url=None, - ) - - [embed] = json.loads( - build_request( - WebhookConfig( - url="https://discord.com/api/webhooks/1/t", format="discord" - ), - message, - ).content - )["embeds"] - - assert (len(embed["title"]), len(embed["description"])) == (256, 4096) - assert "url" not in embed - - -class TestNtfyFormat: - def test_publishes_json_to_the_server_with_the_topic(self): - request = build_request( - WebhookConfig( - url="https://ntfy.example.com/sub/romm", format="ntfy", secret="tk_1" - ), - _message(level=NotificationLevel.ERROR), - ) - - payload = json.loads(request.content) - assert request.url == "https://ntfy.example.com/sub" - assert payload["topic"] == "romm" - assert payload["message"] == "RomM restarts at 23:00" - assert payload["priority"] == webhook.NTFY_ERROR_PRIORITY - assert payload["click"] == "https://romm.example.com/platforms" - assert request.headers["Authorization"] == "Bearer tk_1" - assert webhook.SIGNATURE_HEADER not in request.headers - - @pytest.mark.parametrize( - "url,expected", - [ - ("https://ntfy.sh/romm", ("https://ntfy.sh/", "romm")), - ("https://host/ntfy/romm/", ("https://host/ntfy", "romm")), - ], - ) - def test_splits_a_topic_url(self, url, expected): - assert split_ntfy_url(url) == expected - - def test_a_url_without_a_topic_is_refused(self): - with pytest.raises(ValueError, match="topic"): - split_ntfy_url("https://ntfy.sh/") - - class TestCheckUrl: @pytest.mark.parametrize("url", ["ftp://example.com/x", "not a url", "https://"]) def test_refuses_anything_but_http(self, url): with pytest.raises(ValueError): - check_url(url, WebhookFormat.JSON, allow_private=True) + check_url(url, allow_private=True) def test_keeps_a_user_off_the_local_network(self): with pytest.raises(ValueError): - check_url( - "http://192.168.1.10/hook", WebhookFormat.JSON, allow_private=False - ) + check_url("http://192.168.1.10/hook", allow_private=False) def test_lets_an_admin_reach_the_local_network(self): - check_url("http://192.168.1.10/hook", WebhookFormat.JSON, allow_private=True) + check_url("http://192.168.1.10/hook", allow_private=True) @pytest.mark.parametrize( "url", @@ -162,7 +76,7 @@ class TestCheckUrl: ) def test_refuses_a_port_that_isnt_one(self, url): with pytest.raises(ValueError, match="port"): - check_url(url, WebhookFormat.JSON, allow_private=True) + check_url(url, allow_private=True) def _serve(mocker, handler) -> None: @@ -173,7 +87,7 @@ def _serve(mocker, handler) -> None: ) -_CONFIG = WebhookConfig(url="https://hooks.example.com/romm", format="json") +_CONFIG = WebhookConfig(url="https://hooks.example.com/romm") class TestSend: @@ -207,14 +121,10 @@ class TestSend: async def test_a_refusal_says_who_refused_and_why(self, respond): respond(404, '{"message": "Unknown Webhook"}') - with pytest.raises(WebhookError, match="discord.com answered 404: .*Unknown"): - await send( - WebhookConfig( - url="https://discord.com/api/webhooks/1/t", format="discord" - ), - _message(), - allow_private=False, - ) + with pytest.raises( + WebhookError, match="hooks.example.com answered 404: .*Unknown" + ): + await send(_CONFIG, _message(), allow_private=False) async def test_a_redirect_is_a_delivery_that_did_not_land(self, mocker): _serve( diff --git a/docs/BACKEND_ARCHITECTURE.md b/docs/BACKEND_ARCHITECTURE.md index 29f8ca94e..ebd66f9d2 100644 --- a/docs/BACKEND_ARCHITECTURE.md +++ b/docs/BACKEND_ARCHITECTURE.md @@ -1096,19 +1096,26 @@ curl -X POST "$ROMM/api/notifications" -H "Authorization: Bearer $TOKEN" \ #### Notification channels (`/api/notification-channels`) -Each user forwards their own notifications to webhooks and email addresses. A channel filters by minimum level and by topic (`scans`, `tasks`, `streaming`, `account`, `custom`); every stored notification that passes goes out in its own RQ job, retried at 30 s, 2 min and 10 min. A channel that fails 10 deliveries in a row turns itself off and tells its owner. +Each user forwards their own notifications to other services. A channel is one of three types: -| Method | Path | Scope | Description | -| ------ | ------------------- | -------- | ------------------------------------------------------ | -| GET | `/` | ME_READ | Caller's channels, secrets masked | -| POST | `/` | ME_WRITE | Add a webhook, or an email address that gets a code | -| PATCH | `/{id}` | ME_WRITE | Change it; a blank URL or secret keeps the current one | -| DELETE | `/{id}` | ME_WRITE | Delete it | -| POST | `/{id}/test` | ME_WRITE | Send a sample notification now | -| POST | `/{id}/confirm` | ME_WRITE | Confirm an email address with its code | -| POST | `/{id}/resend-code` | ME_WRITE | Email a new code (once a minute) | +- `apprise`: any of the 100+ services [Apprise](https://github.com/caronc/apprise#supported-notifications) reaches (Discord, Telegram, ntfy, Slack, Gotify…), set up through that service's own fields. **Admins only**, since Apprise opens its own connections, past the SSRF guard. The owner's role is checked again at every delivery, so a demoted admin's channel fails until it turns off. +- `webhook`: RomM's own JSON payload (below), POSTed to an http(s) URL. +- `email`: a plain-text email over the server's SMTP, to an address confirmed with a 6-digit code first. -A webhook's `format` is `json` (RomM's payload below), `discord` (an embed that mentions nobody) or `ntfy` (JSON publishing to the topic's server, with the secret as its access token). Only an admin's webhooks may reach private addresses; everyone else's go through the SSRF guard. A kept secret doesn't follow a channel to another origin or format; it has to be given again. A delivery gets 15 s in all, and only the start of a refusal's body is read. Text for RomM's own kinds is English until outbound messages are translated. Links are absolute only when `ROMM_BASE_URL` is shareable. +A channel filters by minimum level and by topic (`scans`, `tasks`, `streaming`, `account`, `custom`); every stored notification that passes goes out in its own RQ job, retried at 30 s, 2 min and 10 min. A channel that fails 10 deliveries in a row turns itself off and tells its owner. + +| Method | Path | Scope | Description | +| ------ | ------------------- | -------- | --------------------------------------------------------------------- | +| GET | `/` | ME_READ | Caller's channels, secrets masked | +| GET | `/apprise-services` | ME_READ | Every Apprise service and its fields (admins only, else 403) | +| POST | `/` | ME_WRITE | Add a channel; an email address gets a code | +| PATCH | `/{id}` | ME_WRITE | Change it; an omitted URL or secret stays, an empty secret is dropped | +| DELETE | `/{id}` | ME_WRITE | Delete it | +| POST | `/{id}/test` | ME_WRITE | Send a sample notification now | +| POST | `/{id}/confirm` | ME_WRITE | Confirm an email address with its code | +| POST | `/{id}/resend-code` | ME_WRITE | Email a new code (once a minute) | + +The service catalog comes from Apprise's own description of each plugin: its URL tokens become the main fields (a field is required only when every URL template needs it, since alternative credentials are each "required" in Apprise's eyes), and its options become advanced fields. A channel stores the service and the fields it was given, sealed, and the backend builds the Apprise URL from the template those fields fill completely, at each delivery. Schemas that act on the host (`syslog`, `dbus`, `windows` and the like) aren't offered, nor are the options Apprise reads from a local file (`template`, `keyfile`, `subfile`, `pgppub`, `pgpkey`, `pgpprv`) or the ones RomM sets itself (timeouts, retries, redirects). Apprise follows no redirects, doesn't retry on its own, and its timeouts are capped at 10 s to connect and 15 s to read. The API returns a channel's service, the fields that aren't secret (a secret left blank on edit keeps its value), and its URL through Apprise's own masking, without the query. Only an admin's webhooks may reach private addresses; everyone else's go through the SSRF guard. A kept webhook secret doesn't follow the channel to another origin; it has to be given again. A webhook delivery gets 15 s in all, and only the start of a refusal's body is read. Text for RomM's own kinds is English until outbound messages are translated. Links are absolute only when `ROMM_BASE_URL` is shareable. ```json { @@ -1125,7 +1132,7 @@ A webhook's `format` is `json` (RomM's payload below), `discord` (an embed that } ``` -With a secret, the JSON format adds `X-RomM-Signature: sha256=`. Email needs `SMTP_HOST` and `SMTP_FROM` (see `env.template`); the heartbeat's `NOTIFICATIONS.EMAIL_ENABLED` says whether it's set up. Channel configs are sealed with a key derived from `ROMM_AUTH_SECRET_KEY`, so rotating it means entering their URLs again. +With a secret, a webhook adds `X-RomM-Signature: sha256=`. Email needs `SMTP_HOST` and `SMTP_FROM` (see `env.template`); the heartbeat's `NOTIFICATIONS.EMAIL_ENABLED` says whether it's set up. Channel configs are sealed with a key derived from `ROMM_AUTH_SECRET_KEY`, so rotating it means entering their URLs again. ### 6.17 Audit Events (`/api/audit-events`) diff --git a/frontend/src/__generated__/index.ts b/frontend/src/__generated__/index.ts index 6793cf626..0ee7f3d14 100644 --- a/frontend/src/__generated__/index.ts +++ b/frontend/src/__generated__/index.ts @@ -10,6 +10,9 @@ export type { AdminContainerSchema } from './models/AdminContainerSchema'; export type { AdminContainersResponse } from './models/AdminContainersResponse'; export type { AdminSessionSchema } from './models/AdminSessionSchema'; export type { AdminSessionsResponse } from './models/AdminSessionsResponse'; +export type { AppriseChannelCreatePayload } from './models/AppriseChannelCreatePayload'; +export type { AppriseFieldSchema } from './models/AppriseFieldSchema'; +export type { AppriseServiceSchema } from './models/AppriseServiceSchema'; export type { AuditAction } from './models/AuditAction'; export type { AuditActorKind } from './models/AuditActorKind'; export type { AuditCategory } from './models/AuditCategory'; @@ -304,7 +307,6 @@ export type { VolumeResponse } from './models/VolumeResponse'; export type { WatcherTaskMeta } from './models/WatcherTaskMeta'; export type { WatcherTaskStatusResponse } from './models/WatcherTaskStatusResponse'; export type { WebhookChannelCreatePayload } from './models/WebhookChannelCreatePayload'; -export type { WebhookFormat } from './models/WebhookFormat'; export type { WebrcadeFeedCategorySchema } from './models/WebrcadeFeedCategorySchema'; export type { WebrcadeFeedItemPropsSchema } from './models/WebrcadeFeedItemPropsSchema'; export type { WebrcadeFeedItemSchema } from './models/WebrcadeFeedItemSchema'; diff --git a/frontend/src/__generated__/models/AppriseChannelCreatePayload.ts b/frontend/src/__generated__/models/AppriseChannelCreatePayload.ts new file mode 100644 index 000000000..753a4b7df --- /dev/null +++ b/frontend/src/__generated__/models/AppriseChannelCreatePayload.ts @@ -0,0 +1,15 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +import type { NotificationChannelMinLevel } from './NotificationChannelMinLevel'; +import type { NotificationTopic } from './NotificationTopic'; +export type AppriseChannelCreatePayload = { + min_level?: NotificationChannelMinLevel; + topics?: (Array | null); + type: string; + name: string; + service: string; + fields: Record)>; +}; + diff --git a/frontend/src/__generated__/models/AppriseFieldSchema.ts b/frontend/src/__generated__/models/AppriseFieldSchema.ts new file mode 100644 index 000000000..6954a3642 --- /dev/null +++ b/frontend/src/__generated__/models/AppriseFieldSchema.ts @@ -0,0 +1,17 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +export type AppriseFieldSchema = { + key: string; + label: string; + type: 'string' | 'int' | 'float' | 'bool' | 'choice' | 'list'; + required: boolean; + private: boolean; + advanced: boolean; + default: (boolean | number | string | Array | null); + values: (Array | null); + min: (number | null); + max: (number | null); +}; + diff --git a/frontend/src/__generated__/models/AppriseServiceSchema.ts b/frontend/src/__generated__/models/AppriseServiceSchema.ts new file mode 100644 index 000000000..2541bfef2 --- /dev/null +++ b/frontend/src/__generated__/models/AppriseServiceSchema.ts @@ -0,0 +1,12 @@ +/* generated using openapi-typescript-codegen -- do not edit */ +/* istanbul ignore file */ +/* tslint:disable */ +/* eslint-disable */ +import type { AppriseFieldSchema } from './AppriseFieldSchema'; +export type AppriseServiceSchema = { + id: string; + name: string; + setup_url: (string | null); + fields: Array; +}; + diff --git a/frontend/src/__generated__/models/NotificationChannelSchema.ts b/frontend/src/__generated__/models/NotificationChannelSchema.ts index 980419e92..f76aad4dd 100644 --- a/frontend/src/__generated__/models/NotificationChannelSchema.ts +++ b/frontend/src/__generated__/models/NotificationChannelSchema.ts @@ -5,7 +5,6 @@ import type { NotificationChannelMinLevel } from './NotificationChannelMinLevel'; import type { NotificationChannelType } from './NotificationChannelType'; import type { NotificationTopic } from './NotificationTopic'; -import type { WebhookFormat } from './WebhookFormat'; export type NotificationChannelSchema = { id: number; type: NotificationChannelType; @@ -14,7 +13,9 @@ export type NotificationChannelSchema = { min_level: NotificationChannelMinLevel; topics: (Array | null); target: string; - format: (WebhookFormat | null); + service: (string | null); + service_name: (string | null); + fields: (Record)> | null); has_secret: boolean; confirmed: boolean; last_delivered_at: (string | null); diff --git a/frontend/src/__generated__/models/NotificationChannelType.ts b/frontend/src/__generated__/models/NotificationChannelType.ts index 1a4577f3e..0f7728ac8 100644 --- a/frontend/src/__generated__/models/NotificationChannelType.ts +++ b/frontend/src/__generated__/models/NotificationChannelType.ts @@ -2,4 +2,4 @@ /* istanbul ignore file */ /* tslint:disable */ /* eslint-disable */ -export type NotificationChannelType = 'webhook' | 'email'; +export type NotificationChannelType = 'apprise' | 'webhook' | 'email'; diff --git a/frontend/src/__generated__/models/NotificationChannelUpdatePayload.ts b/frontend/src/__generated__/models/NotificationChannelUpdatePayload.ts index d57169b9f..176138b6b 100644 --- a/frontend/src/__generated__/models/NotificationChannelUpdatePayload.ts +++ b/frontend/src/__generated__/models/NotificationChannelUpdatePayload.ts @@ -4,7 +4,6 @@ /* eslint-disable */ import type { NotificationChannelMinLevel } from './NotificationChannelMinLevel'; import type { NotificationTopic } from './NotificationTopic'; -import type { WebhookFormat } from './WebhookFormat'; /** * The fields to change; a null `topics` forwards every topic, an empty `secret` drops it. */ @@ -14,8 +13,8 @@ export type NotificationChannelUpdatePayload = { min_level?: (NotificationChannelMinLevel | null); topics?: (Array | null); url?: (string | null); - format?: (WebhookFormat | null); secret?: (string | null); address?: (string | null); + fields?: (Record)> | null); }; diff --git a/frontend/src/__generated__/models/WebhookChannelCreatePayload.ts b/frontend/src/__generated__/models/WebhookChannelCreatePayload.ts index e94eb8103..d36827a84 100644 --- a/frontend/src/__generated__/models/WebhookChannelCreatePayload.ts +++ b/frontend/src/__generated__/models/WebhookChannelCreatePayload.ts @@ -4,14 +4,12 @@ /* eslint-disable */ import type { NotificationChannelMinLevel } from './NotificationChannelMinLevel'; import type { NotificationTopic } from './NotificationTopic'; -import type { WebhookFormat } from './WebhookFormat'; export type WebhookChannelCreatePayload = { min_level?: NotificationChannelMinLevel; topics?: (Array | null); type: string; name: string; url: string; - format?: WebhookFormat; secret?: (string | null); }; diff --git a/frontend/src/__generated__/models/WebhookFormat.ts b/frontend/src/__generated__/models/WebhookFormat.ts deleted file mode 100644 index 0786f840d..000000000 --- a/frontend/src/__generated__/models/WebhookFormat.ts +++ /dev/null @@ -1,5 +0,0 @@ -/* generated using openapi-typescript-codegen -- do not edit */ -/* istanbul ignore file */ -/* tslint:disable */ -/* eslint-disable */ -export type WebhookFormat = 'json' | 'discord' | 'ntfy'; diff --git a/frontend/src/locales/bg_BG/notifications.json b/frontend/src/locales/bg_BG/notifications.json index 90a543cca..4d57ebb34 100644 --- a/frontend/src/locales/bg_BG/notifications.json +++ b/frontend/src/locales/bg_BG/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Добави канал", "channel-address": "Имейл адрес", "channel-address-hint": "Ще изпратим код, за да потвърдим, че е ваш", + "channel-advanced": "Разширени настройки", "channel-awaiting-code": "Въведете кода от имейла, за да започнете да получавате известия тук", "channel-code": "Код", "channel-code-sent": "Изпратихме код на {address}", @@ -15,10 +16,17 @@ "channel-edit": "Редактирай канала", "channel-email-unavailable": "Имейлът не е настроен на този сървър", "channel-enabled": "Изпращай известия тук", - "channel-format": "Формат", - "channel-format-discord": "Discord", - "channel-format-json": "JSON на RomM", - "channel-format-ntfy": "ntfy", + "channel-field-host": "Хост", + "channel-field-list-hint": "Натиснете Enter след всеки", + "channel-field-number": "Трябва да е число от {min} до {max}", + "channel-field-password": "Парола", + "channel-field-path": "Път", + "channel-field-port": "Порт", + "channel-field-schema": "Протокол", + "channel-field-targets": "Получатели", + "channel-field-token": "Токен", + "channel-field-user": "Потребителско име", + "channel-field-verify": "Проверка на SSL сертификата", "channel-last-error": "Последна грешка: {error}", "channel-last-sent": "Последно изпратено: {when}", "channel-level-error": "Само грешки", @@ -31,10 +39,12 @@ "channel-resend-failed": "Не можа да се изпрати нов код", "channel-save-failed": "Каналът не можа да бъде запазен", "channel-saved": "Каналът е запазен", - "channel-secret-json": "Таен ключ за подпис (по избор)", + "channel-search-services": "Търсене на услуги", + "channel-secret": "Таен ключ за подпис (по избор)", "channel-secret-keep": "Оставете празно, за да запазите текущия", - "channel-secret-ntfy": "Токен за достъп (по избор)", "channel-secret-remove": "Премахни го", + "channel-services-failed": "Услугите на Apprise не можаха да се заредят", + "channel-setup-guide": "Как да настроите {service}", "channel-test": "Изпрати тест", "channel-test-failed": "Тестът е неуспешен: {error}", "channel-test-ok": "Тестът е изпратен", @@ -42,14 +52,14 @@ "channel-topics-all": "Всички теми", "channel-type": "Тип", "channel-type-email": "Имейл", - "channel-type-webhook": "Уебхук", + "channel-type-webhook": "Уебхук на RomM (JSON)", "channel-update-failed": "Каналът не можа да бъде обновен", "channel-url": "URL", "channel-url-invalid": "Трябва да започва с http:// или https://", "channel-url-keep": "Оставете празно, за да запазите текущия URL", "channels": "Канали", "channels-empty": "Все още няма канали", - "channels-empty-hint": "Препращайте известията си към Discord, ntfy, имейл или всеки уебхук.", + "channels-empty-hint": "Препращайте известията си извън RomM: към уебхук, имейл адрес и други.", "channels-load-failed": "Каналите ви не можаха да бъдат заредени", "dismiss-all": "Затвори всички", "dismiss-all-body": "Всички известия ще бъдат премахнати.", diff --git a/frontend/src/locales/cs_CZ/notifications.json b/frontend/src/locales/cs_CZ/notifications.json index 896b3d2e7..fb9019daf 100644 --- a/frontend/src/locales/cs_CZ/notifications.json +++ b/frontend/src/locales/cs_CZ/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Přidat kanál", "channel-address": "E-mailová adresa", "channel-address-hint": "Pošleme kód, abychom ověřili, že je vaše", + "channel-advanced": "Pokročilé možnosti", "channel-awaiting-code": "Zadejte kód z e-mailu a začněte sem dostávat oznámení", "channel-code": "Kód", "channel-code-sent": "Poslali jsme kód na {address}", @@ -15,10 +16,17 @@ "channel-edit": "Upravit kanál", "channel-email-unavailable": "E-mail není na tomto serveru nastaven", "channel-enabled": "Posílat oznámení sem", - "channel-format": "Formát", - "channel-format-discord": "Discord", - "channel-format-json": "JSON RomM", - "channel-format-ntfy": "ntfy", + "channel-field-host": "Hostitel", + "channel-field-list-hint": "Po každé položce stiskněte Enter", + "channel-field-number": "Musí být číslo od {min} do {max}", + "channel-field-password": "Heslo", + "channel-field-path": "Cesta", + "channel-field-port": "Port", + "channel-field-schema": "Protokol", + "channel-field-targets": "Cíle", + "channel-field-token": "Token", + "channel-field-user": "Uživatelské jméno", + "channel-field-verify": "Ověřovat certifikát SSL", "channel-last-error": "Poslední chyba: {error}", "channel-last-sent": "Naposledy odesláno: {when}", "channel-level-error": "Pouze chyby", @@ -31,10 +39,12 @@ "channel-resend-failed": "Nový kód se nepodařilo odeslat", "channel-save-failed": "Kanál se nepodařilo uložit", "channel-saved": "Kanál uložen", - "channel-secret-json": "Podpisový klíč (volitelné)", + "channel-search-services": "Hledat služby", + "channel-secret": "Podpisový klíč (volitelné)", "channel-secret-keep": "Ponechte prázdné pro zachování stávajícího", - "channel-secret-ntfy": "Přístupový token (volitelné)", "channel-secret-remove": "Odebrat", + "channel-services-failed": "Služby Apprise se nepodařilo načíst", + "channel-setup-guide": "Jak nastavit {service}", "channel-test": "Poslat test", "channel-test-failed": "Test selhal: {error}", "channel-test-ok": "Test odeslán", @@ -42,14 +52,14 @@ "channel-topics-all": "Všechna témata", "channel-type": "Typ", "channel-type-email": "E-mail", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "Webhook RomM (JSON)", "channel-update-failed": "Kanál se nepodařilo aktualizovat", "channel-url": "URL", "channel-url-invalid": "Musí začínat http:// nebo https://", "channel-url-keep": "Ponechte prázdné pro zachování stávající URL", "channels": "Kanály", "channels-empty": "Zatím žádné kanály", - "channels-empty-hint": "Přeposílejte oznámení na Discord, ntfy, e-mail nebo jakýkoli webhook.", + "channels-empty-hint": "Přeposílejte oznámení mimo RomM: na webhook, e-mailovou adresu a další.", "channels-load-failed": "Vaše kanály se nepodařilo načíst", "dismiss-all": "Zavřít vše", "dismiss-all-body": "Všechna oznámení budou odstraněna.", diff --git a/frontend/src/locales/de_DE/notifications.json b/frontend/src/locales/de_DE/notifications.json index c06a066ae..7606fd99c 100644 --- a/frontend/src/locales/de_DE/notifications.json +++ b/frontend/src/locales/de_DE/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Kanal hinzufügen", "channel-address": "E-Mail-Adresse", "channel-address-hint": "Wir schicken einen Code, um zu bestätigen, dass sie dir gehört", + "channel-advanced": "Erweiterte Optionen", "channel-awaiting-code": "Gib den Code aus der E-Mail ein, um hier Benachrichtigungen zu erhalten", "channel-code": "Code", "channel-code-sent": "Wir haben einen Code an {address} geschickt", @@ -15,10 +16,17 @@ "channel-edit": "Kanal bearbeiten", "channel-email-unavailable": "E-Mail ist auf diesem Server nicht eingerichtet", "channel-enabled": "Benachrichtigungen hierher senden", - "channel-format": "Format", - "channel-format-discord": "Discord", - "channel-format-json": "RomM-JSON", - "channel-format-ntfy": "ntfy", + "channel-field-host": "Host", + "channel-field-list-hint": "Nach jedem Eintrag Enter drücken", + "channel-field-number": "Muss eine Zahl von {min} bis {max} sein", + "channel-field-password": "Passwort", + "channel-field-path": "Pfad", + "channel-field-port": "Port", + "channel-field-schema": "Protokoll", + "channel-field-targets": "Ziele", + "channel-field-token": "Token", + "channel-field-user": "Benutzername", + "channel-field-verify": "SSL-Zertifikat prüfen", "channel-last-error": "Letzter Fehler: {error}", "channel-last-sent": "Zuletzt gesendet: {when}", "channel-level-error": "Nur Fehler", @@ -31,10 +39,12 @@ "channel-resend-failed": "Es konnte kein neuer Code gesendet werden", "channel-save-failed": "Der Kanal konnte nicht gespeichert werden", "channel-saved": "Kanal gespeichert", - "channel-secret-json": "Signaturgeheimnis (optional)", + "channel-search-services": "Dienste durchsuchen", + "channel-secret": "Signaturgeheimnis (optional)", "channel-secret-keep": "Leer lassen, um das aktuelle zu behalten", - "channel-secret-ntfy": "Zugriffstoken (optional)", "channel-secret-remove": "Entfernen", + "channel-services-failed": "Die Apprise-Dienste konnten nicht geladen werden", + "channel-setup-guide": "So richtest du {service} ein", "channel-test": "Test senden", "channel-test-failed": "Test fehlgeschlagen: {error}", "channel-test-ok": "Test gesendet", @@ -42,14 +52,14 @@ "channel-topics-all": "Alle Themen", "channel-type": "Typ", "channel-type-email": "E-Mail", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "RomM-Webhook (JSON)", "channel-update-failed": "Der Kanal konnte nicht aktualisiert werden", "channel-url": "URL", "channel-url-invalid": "Muss mit http:// oder https:// beginnen", "channel-url-keep": "Leer lassen, um die aktuelle URL zu behalten", "channels": "Kanäle", "channels-empty": "Noch keine Kanäle", - "channels-empty-hint": "Leite deine Benachrichtigungen an Discord, ntfy, E-Mail oder einen beliebigen Webhook weiter.", + "channels-empty-hint": "Leite deine Benachrichtigungen aus RomM heraus weiter: an einen Webhook, eine E-Mail-Adresse und mehr.", "channels-load-failed": "Deine Kanäle konnten nicht geladen werden", "dismiss-all": "Alle verwerfen", "dismiss-all-body": "Alle Benachrichtigungen werden entfernt.", diff --git a/frontend/src/locales/en_GB/notifications.json b/frontend/src/locales/en_GB/notifications.json index 00200a192..caeb4e324 100644 --- a/frontend/src/locales/en_GB/notifications.json +++ b/frontend/src/locales/en_GB/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Add channel", "channel-address": "Email address", "channel-address-hint": "We'll email a code to confirm it's yours", + "channel-advanced": "Advanced options", "channel-awaiting-code": "Enter the code we emailed to start getting notifications here", "channel-code": "Code", "channel-code-sent": "We sent a code to {address}", @@ -15,10 +16,17 @@ "channel-edit": "Edit channel", "channel-email-unavailable": "Email isn't set up on this server", "channel-enabled": "Send notifications here", - "channel-format": "Format", - "channel-format-discord": "Discord", - "channel-format-json": "RomM JSON", - "channel-format-ntfy": "ntfy", + "channel-field-host": "Host", + "channel-field-list-hint": "Press Enter after each one", + "channel-field-number": "Must be a number from {min} to {max}", + "channel-field-password": "Password", + "channel-field-path": "Path", + "channel-field-port": "Port", + "channel-field-schema": "Protocol", + "channel-field-targets": "Targets", + "channel-field-token": "Token", + "channel-field-user": "Username", + "channel-field-verify": "Verify the SSL certificate", "channel-last-error": "Last error: {error}", "channel-last-sent": "Last sent {when}", "channel-level-error": "Errors only", @@ -31,10 +39,12 @@ "channel-resend-failed": "Could not send a new code", "channel-save-failed": "Could not save the channel", "channel-saved": "Channel saved", - "channel-secret-json": "Signing secret (optional)", + "channel-search-services": "Search services", + "channel-secret": "Signing secret (optional)", "channel-secret-keep": "Leave empty to keep the current one", - "channel-secret-ntfy": "Access token (optional)", "channel-secret-remove": "Remove it", + "channel-services-failed": "Could not load the Apprise services", + "channel-setup-guide": "How to set up {service}", "channel-test": "Send a test", "channel-test-failed": "Test failed: {error}", "channel-test-ok": "Test sent", @@ -42,14 +52,14 @@ "channel-topics-all": "All topics", "channel-type": "Type", "channel-type-email": "Email", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "RomM webhook (JSON)", "channel-update-failed": "Could not update the channel", "channel-url": "URL", "channel-url-invalid": "Must start with http:// or https://", "channel-url-keep": "Leave empty to keep the current URL", "channels": "Channels", "channels-empty": "No channels yet", - "channels-empty-hint": "Forward your notifications to Discord, ntfy, email or any webhook.", + "channels-empty-hint": "Forward your notifications outside RomM, to a webhook, an email address and more.", "channels-load-failed": "Could not load your channels", "dismiss-all": "Dismiss all", "dismiss-all-body": "Every notification will be removed.", diff --git a/frontend/src/locales/en_US/notifications.json b/frontend/src/locales/en_US/notifications.json index 00200a192..caeb4e324 100644 --- a/frontend/src/locales/en_US/notifications.json +++ b/frontend/src/locales/en_US/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Add channel", "channel-address": "Email address", "channel-address-hint": "We'll email a code to confirm it's yours", + "channel-advanced": "Advanced options", "channel-awaiting-code": "Enter the code we emailed to start getting notifications here", "channel-code": "Code", "channel-code-sent": "We sent a code to {address}", @@ -15,10 +16,17 @@ "channel-edit": "Edit channel", "channel-email-unavailable": "Email isn't set up on this server", "channel-enabled": "Send notifications here", - "channel-format": "Format", - "channel-format-discord": "Discord", - "channel-format-json": "RomM JSON", - "channel-format-ntfy": "ntfy", + "channel-field-host": "Host", + "channel-field-list-hint": "Press Enter after each one", + "channel-field-number": "Must be a number from {min} to {max}", + "channel-field-password": "Password", + "channel-field-path": "Path", + "channel-field-port": "Port", + "channel-field-schema": "Protocol", + "channel-field-targets": "Targets", + "channel-field-token": "Token", + "channel-field-user": "Username", + "channel-field-verify": "Verify the SSL certificate", "channel-last-error": "Last error: {error}", "channel-last-sent": "Last sent {when}", "channel-level-error": "Errors only", @@ -31,10 +39,12 @@ "channel-resend-failed": "Could not send a new code", "channel-save-failed": "Could not save the channel", "channel-saved": "Channel saved", - "channel-secret-json": "Signing secret (optional)", + "channel-search-services": "Search services", + "channel-secret": "Signing secret (optional)", "channel-secret-keep": "Leave empty to keep the current one", - "channel-secret-ntfy": "Access token (optional)", "channel-secret-remove": "Remove it", + "channel-services-failed": "Could not load the Apprise services", + "channel-setup-guide": "How to set up {service}", "channel-test": "Send a test", "channel-test-failed": "Test failed: {error}", "channel-test-ok": "Test sent", @@ -42,14 +52,14 @@ "channel-topics-all": "All topics", "channel-type": "Type", "channel-type-email": "Email", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "RomM webhook (JSON)", "channel-update-failed": "Could not update the channel", "channel-url": "URL", "channel-url-invalid": "Must start with http:// or https://", "channel-url-keep": "Leave empty to keep the current URL", "channels": "Channels", "channels-empty": "No channels yet", - "channels-empty-hint": "Forward your notifications to Discord, ntfy, email or any webhook.", + "channels-empty-hint": "Forward your notifications outside RomM, to a webhook, an email address and more.", "channels-load-failed": "Could not load your channels", "dismiss-all": "Dismiss all", "dismiss-all-body": "Every notification will be removed.", diff --git a/frontend/src/locales/es_ES/notifications.json b/frontend/src/locales/es_ES/notifications.json index 0f902c094..4dcede8fc 100644 --- a/frontend/src/locales/es_ES/notifications.json +++ b/frontend/src/locales/es_ES/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Añadir canal", "channel-address": "Dirección de correo", "channel-address-hint": "Te enviaremos un código para confirmar que es tuya", + "channel-advanced": "Opciones avanzadas", "channel-awaiting-code": "Introduce el código que te hemos enviado para empezar a recibir notificaciones aquí", "channel-code": "Código", "channel-code-sent": "Hemos enviado un código a {address}", @@ -15,10 +16,17 @@ "channel-edit": "Editar canal", "channel-email-unavailable": "El correo no está configurado en este servidor", "channel-enabled": "Enviar notificaciones aquí", - "channel-format": "Formato", - "channel-format-discord": "Discord", - "channel-format-json": "JSON de RomM", - "channel-format-ntfy": "ntfy", + "channel-field-host": "Host", + "channel-field-list-hint": "Pulsa Intro después de cada uno", + "channel-field-number": "Debe ser un número entre {min} y {max}", + "channel-field-password": "Contraseña", + "channel-field-path": "Ruta", + "channel-field-port": "Puerto", + "channel-field-schema": "Protocolo", + "channel-field-targets": "Destinos", + "channel-field-token": "Token", + "channel-field-user": "Usuario", + "channel-field-verify": "Verificar el certificado SSL", "channel-last-error": "Último error: {error}", "channel-last-sent": "Último envío: {when}", "channel-level-error": "Solo errores", @@ -31,10 +39,12 @@ "channel-resend-failed": "No se pudo enviar otro código", "channel-save-failed": "No se pudo guardar el canal", "channel-saved": "Canal guardado", - "channel-secret-json": "Secreto de firma (opcional)", + "channel-search-services": "Buscar servicios", + "channel-secret": "Secreto de firma (opcional)", "channel-secret-keep": "Déjalo vacío para mantener el actual", - "channel-secret-ntfy": "Token de acceso (opcional)", "channel-secret-remove": "Quitarlo", + "channel-services-failed": "No se pudieron cargar los servicios de Apprise", + "channel-setup-guide": "Cómo configurar {service}", "channel-test": "Enviar una prueba", "channel-test-failed": "La prueba ha fallado: {error}", "channel-test-ok": "Prueba enviada", @@ -42,14 +52,14 @@ "channel-topics-all": "Todos los temas", "channel-type": "Tipo", "channel-type-email": "Correo", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "Webhook de RomM (JSON)", "channel-update-failed": "No se pudo actualizar el canal", "channel-url": "URL", "channel-url-invalid": "Debe empezar por http:// o https://", "channel-url-keep": "Déjalo vacío para mantener la URL actual", "channels": "Canales", "channels-empty": "Aún no hay canales", - "channels-empty-hint": "Reenvía tus notificaciones a Discord, ntfy, correo o cualquier webhook.", + "channels-empty-hint": "Reenvía tus notificaciones fuera de RomM: a un webhook, a un correo y más.", "channels-load-failed": "No se pudieron cargar tus canales", "dismiss-all": "Descartar todas", "dismiss-all-body": "Se eliminarán todas las notificaciones.", diff --git a/frontend/src/locales/fr_FR/notifications.json b/frontend/src/locales/fr_FR/notifications.json index 9347b7748..13be0682b 100644 --- a/frontend/src/locales/fr_FR/notifications.json +++ b/frontend/src/locales/fr_FR/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Ajouter un canal", "channel-address": "Adresse e-mail", "channel-address-hint": "Nous enverrons un code pour confirmer qu'elle est à vous", + "channel-advanced": "Options avancées", "channel-awaiting-code": "Saisissez le code reçu par e-mail pour commencer à recevoir des notifications ici", "channel-code": "Code", "channel-code-sent": "Nous avons envoyé un code à {address}", @@ -15,10 +16,17 @@ "channel-edit": "Modifier le canal", "channel-email-unavailable": "L'e-mail n'est pas configuré sur ce serveur", "channel-enabled": "Envoyer les notifications ici", - "channel-format": "Format", - "channel-format-discord": "Discord", - "channel-format-json": "JSON RomM", - "channel-format-ntfy": "ntfy", + "channel-field-host": "Hôte", + "channel-field-list-hint": "Appuyez sur Entrée après chacun", + "channel-field-number": "Doit être un nombre entre {min} et {max}", + "channel-field-password": "Mot de passe", + "channel-field-path": "Chemin", + "channel-field-port": "Port", + "channel-field-schema": "Protocole", + "channel-field-targets": "Destinataires", + "channel-field-token": "Jeton", + "channel-field-user": "Nom d'utilisateur", + "channel-field-verify": "Vérifier le certificat SSL", "channel-last-error": "Dernière erreur : {error}", "channel-last-sent": "Dernier envoi : {when}", "channel-level-error": "Erreurs uniquement", @@ -31,10 +39,12 @@ "channel-resend-failed": "Impossible d'envoyer un nouveau code", "channel-save-failed": "Impossible d'enregistrer le canal", "channel-saved": "Canal enregistré", - "channel-secret-json": "Secret de signature (facultatif)", + "channel-search-services": "Rechercher un service", + "channel-secret": "Secret de signature (facultatif)", "channel-secret-keep": "Laissez vide pour conserver l'actuel", - "channel-secret-ntfy": "Jeton d'accès (facultatif)", "channel-secret-remove": "Le supprimer", + "channel-services-failed": "Impossible de charger les services Apprise", + "channel-setup-guide": "Comment configurer {service}", "channel-test": "Envoyer un test", "channel-test-failed": "Échec du test : {error}", "channel-test-ok": "Test envoyé", @@ -42,14 +52,14 @@ "channel-topics-all": "Tous les sujets", "channel-type": "Type", "channel-type-email": "E-mail", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "Webhook RomM (JSON)", "channel-update-failed": "Impossible de mettre à jour le canal", "channel-url": "URL", "channel-url-invalid": "Doit commencer par http:// ou https://", "channel-url-keep": "Laissez vide pour conserver l'URL actuelle", "channels": "Canaux", "channels-empty": "Aucun canal pour l'instant", - "channels-empty-hint": "Transférez vos notifications vers Discord, ntfy, l'e-mail ou n'importe quel webhook.", + "channels-empty-hint": "Transférez vos notifications hors de RomM : vers un webhook, une adresse e-mail et plus encore.", "channels-load-failed": "Impossible de charger vos canaux", "dismiss-all": "Tout ignorer", "dismiss-all-body": "Toutes les notifications seront supprimées.", diff --git a/frontend/src/locales/hu_HU/notifications.json b/frontend/src/locales/hu_HU/notifications.json index a70e285f2..4a62ecf97 100644 --- a/frontend/src/locales/hu_HU/notifications.json +++ b/frontend/src/locales/hu_HU/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Csatorna hozzáadása", "channel-address": "E-mail-cím", "channel-address-hint": "Küldünk egy kódot, hogy megerősítsd, a tiéd", + "channel-advanced": "Speciális beállítások", "channel-awaiting-code": "Add meg az e-mailben kapott kódot, hogy itt is értesítéseket kapj", "channel-code": "Kód", "channel-code-sent": "Kódot küldtünk ide: {address}", @@ -15,10 +16,17 @@ "channel-edit": "Csatorna szerkesztése", "channel-email-unavailable": "Az e-mail nincs beállítva ezen a szerveren", "channel-enabled": "Értesítések küldése ide", - "channel-format": "Formátum", - "channel-format-discord": "Discord", - "channel-format-json": "RomM JSON", - "channel-format-ntfy": "ntfy", + "channel-field-host": "Kiszolgáló", + "channel-field-list-hint": "Mindegyik után nyomj Entert", + "channel-field-number": "{min} és {max} közötti számnak kell lennie", + "channel-field-password": "Jelszó", + "channel-field-path": "Útvonal", + "channel-field-port": "Port", + "channel-field-schema": "Protokoll", + "channel-field-targets": "Címzettek", + "channel-field-token": "Token", + "channel-field-user": "Felhasználónév", + "channel-field-verify": "SSL-tanúsítvány ellenőrzése", "channel-last-error": "Utolsó hiba: {error}", "channel-last-sent": "Utoljára elküldve: {when}", "channel-level-error": "Csak hibák", @@ -31,10 +39,12 @@ "channel-resend-failed": "Nem sikerült új kódot küldeni", "channel-save-failed": "Nem sikerült menteni a csatornát", "channel-saved": "Csatorna mentve", - "channel-secret-json": "Aláírási titok (nem kötelező)", + "channel-search-services": "Szolgáltatások keresése", + "channel-secret": "Aláírási titok (nem kötelező)", "channel-secret-keep": "Hagyd üresen a jelenlegi megtartásához", - "channel-secret-ntfy": "Hozzáférési token (nem kötelező)", "channel-secret-remove": "Eltávolítás", + "channel-services-failed": "Az Apprise-szolgáltatásokat nem sikerült betölteni", + "channel-setup-guide": "{service} beállítása", "channel-test": "Teszt küldése", "channel-test-failed": "A teszt sikertelen: {error}", "channel-test-ok": "Teszt elküldve", @@ -42,14 +52,14 @@ "channel-topics-all": "Minden téma", "channel-type": "Típus", "channel-type-email": "E-mail", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "RomM webhook (JSON)", "channel-update-failed": "Nem sikerült frissíteni a csatornát", "channel-url": "URL", "channel-url-invalid": "http:// vagy https:// kezdetűnek kell lennie", "channel-url-keep": "Hagyd üresen a jelenlegi URL megtartásához", "channels": "Csatornák", "channels-empty": "Még nincsenek csatornák", - "channels-empty-hint": "Továbbítsd az értesítéseidet Discordra, ntfy-ra, e-mailbe vagy bármilyen webhookra.", + "channels-empty-hint": "Továbbítsd az értesítéseidet a RomM-on kívülre: webhookra, e-mail-címre és máshová.", "channels-load-failed": "Nem sikerült betölteni a csatornáidat", "dismiss-all": "Összes elvetése", "dismiss-all-body": "Az összes értesítés törlődik.", diff --git a/frontend/src/locales/it_IT/notifications.json b/frontend/src/locales/it_IT/notifications.json index a44f21ccc..eab5850c4 100644 --- a/frontend/src/locales/it_IT/notifications.json +++ b/frontend/src/locales/it_IT/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Aggiungi canale", "channel-address": "Indirizzo email", "channel-address-hint": "Ti invieremo un codice per confermare che è tuo", + "channel-advanced": "Opzioni avanzate", "channel-awaiting-code": "Inserisci il codice che ti abbiamo inviato per iniziare a ricevere notifiche qui", "channel-code": "Codice", "channel-code-sent": "Abbiamo inviato un codice a {address}", @@ -15,10 +16,17 @@ "channel-edit": "Modifica canale", "channel-email-unavailable": "L'email non è configurata su questo server", "channel-enabled": "Invia notifiche qui", - "channel-format": "Formato", - "channel-format-discord": "Discord", - "channel-format-json": "JSON di RomM", - "channel-format-ntfy": "ntfy", + "channel-field-host": "Host", + "channel-field-list-hint": "Premi Invio dopo ognuno", + "channel-field-number": "Deve essere un numero da {min} a {max}", + "channel-field-password": "Password", + "channel-field-path": "Percorso", + "channel-field-port": "Porta", + "channel-field-schema": "Protocollo", + "channel-field-targets": "Destinatari", + "channel-field-token": "Token", + "channel-field-user": "Nome utente", + "channel-field-verify": "Verifica il certificato SSL", "channel-last-error": "Ultimo errore: {error}", "channel-last-sent": "Ultimo invio: {when}", "channel-level-error": "Solo errori", @@ -31,10 +39,12 @@ "channel-resend-failed": "Impossibile inviare un nuovo codice", "channel-save-failed": "Impossibile salvare il canale", "channel-saved": "Canale salvato", - "channel-secret-json": "Segreto di firma (facoltativo)", + "channel-search-services": "Cerca servizi", + "channel-secret": "Segreto di firma (facoltativo)", "channel-secret-keep": "Lascia vuoto per mantenere quello attuale", - "channel-secret-ntfy": "Token di accesso (facoltativo)", "channel-secret-remove": "Rimuovilo", + "channel-services-failed": "Impossibile caricare i servizi Apprise", + "channel-setup-guide": "Come configurare {service}", "channel-test": "Invia un test", "channel-test-failed": "Test non riuscito: {error}", "channel-test-ok": "Test inviato", @@ -42,14 +52,14 @@ "channel-topics-all": "Tutti gli argomenti", "channel-type": "Tipo", "channel-type-email": "Email", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "Webhook di RomM (JSON)", "channel-update-failed": "Impossibile aggiornare il canale", "channel-url": "URL", "channel-url-invalid": "Deve iniziare con http:// o https://", "channel-url-keep": "Lascia vuoto per mantenere l'URL attuale", "channels": "Canali", "channels-empty": "Ancora nessun canale", - "channels-empty-hint": "Inoltra le tue notifiche a Discord, ntfy, email o qualsiasi webhook.", + "channels-empty-hint": "Inoltra le tue notifiche fuori da RomM: a un webhook, a un indirizzo email e altro.", "channels-load-failed": "Impossibile caricare i tuoi canali", "dismiss-all": "Ignora tutte", "dismiss-all-body": "Tutte le notifiche verranno rimosse.", diff --git a/frontend/src/locales/ja_JP/notifications.json b/frontend/src/locales/ja_JP/notifications.json index b4ec992b2..09f5b6166 100644 --- a/frontend/src/locales/ja_JP/notifications.json +++ b/frontend/src/locales/ja_JP/notifications.json @@ -2,6 +2,7 @@ "channel-add": "チャンネルを追加", "channel-address": "メールアドレス", "channel-address-hint": "本人確認のためにコードをメールで送ります", + "channel-advanced": "詳細オプション", "channel-awaiting-code": "メールで届いたコードを入力すると、ここで通知を受け取れるようになります", "channel-code": "コード", "channel-code-sent": "{address} にコードを送信しました", @@ -15,10 +16,17 @@ "channel-edit": "チャンネルを編集", "channel-email-unavailable": "このサーバーではメールが設定されていません", "channel-enabled": "ここに通知を送る", - "channel-format": "形式", - "channel-format-discord": "Discord", - "channel-format-json": "RomM JSON", - "channel-format-ntfy": "ntfy", + "channel-field-host": "ホスト", + "channel-field-list-hint": "1 件ごとに Enter を押してください", + "channel-field-number": "{min} から {max} までの数値を入力してください", + "channel-field-password": "パスワード", + "channel-field-path": "パス", + "channel-field-port": "ポート", + "channel-field-schema": "プロトコル", + "channel-field-targets": "送信先", + "channel-field-token": "トークン", + "channel-field-user": "ユーザー名", + "channel-field-verify": "SSL 証明書を検証する", "channel-last-error": "最後のエラー: {error}", "channel-last-sent": "最終送信: {when}", "channel-level-error": "エラーのみ", @@ -31,10 +39,12 @@ "channel-resend-failed": "新しいコードを送信できませんでした", "channel-save-failed": "チャンネルを保存できませんでした", "channel-saved": "チャンネルを保存しました", - "channel-secret-json": "署名シークレット(任意)", + "channel-search-services": "サービスを検索", + "channel-secret": "署名シークレット(任意)", "channel-secret-keep": "現在の値を保持するには空欄のままにします", - "channel-secret-ntfy": "アクセストークン(任意)", "channel-secret-remove": "削除する", + "channel-services-failed": "Apprise のサービスを読み込めませんでした", + "channel-setup-guide": "{service} の設定方法", "channel-test": "テストを送信", "channel-test-failed": "テストに失敗しました: {error}", "channel-test-ok": "テストを送信しました", @@ -42,14 +52,14 @@ "channel-topics-all": "すべてのトピック", "channel-type": "種類", "channel-type-email": "メール", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "RomM Webhook(JSON)", "channel-update-failed": "チャンネルを更新できませんでした", "channel-url": "URL", "channel-url-invalid": "http:// または https:// で始める必要があります", "channel-url-keep": "現在の URL を保持するには空欄のままにします", "channels": "チャンネル", "channels-empty": "チャンネルはまだありません", - "channels-empty-hint": "通知を Discord、ntfy、メール、または任意の Webhook に転送できます。", + "channels-empty-hint": "通知を RomM の外へ転送できます。Webhook、メールアドレスなどに送れます。", "channels-load-failed": "チャンネルを読み込めませんでした", "dismiss-all": "すべて閉じる", "dismiss-all-body": "すべての通知が削除されます。", diff --git a/frontend/src/locales/ko_KR/notifications.json b/frontend/src/locales/ko_KR/notifications.json index 572d97e94..fa27010a4 100644 --- a/frontend/src/locales/ko_KR/notifications.json +++ b/frontend/src/locales/ko_KR/notifications.json @@ -2,6 +2,7 @@ "channel-add": "채널 추가", "channel-address": "이메일 주소", "channel-address-hint": "본인 주소인지 확인할 코드를 이메일로 보내드립니다", + "channel-advanced": "고급 옵션", "channel-awaiting-code": "이메일로 받은 코드를 입력하면 여기로 알림을 받기 시작합니다", "channel-code": "코드", "channel-code-sent": "{address}(으)로 코드를 보냈습니다", @@ -15,10 +16,17 @@ "channel-edit": "채널 편집", "channel-email-unavailable": "이 서버에는 이메일이 설정되어 있지 않습니다", "channel-enabled": "여기로 알림 보내기", - "channel-format": "형식", - "channel-format-discord": "Discord", - "channel-format-json": "RomM JSON", - "channel-format-ntfy": "ntfy", + "channel-field-host": "호스트", + "channel-field-list-hint": "항목마다 Enter를 누르세요", + "channel-field-number": "{min}에서 {max} 사이의 숫자여야 합니다", + "channel-field-password": "비밀번호", + "channel-field-path": "경로", + "channel-field-port": "포트", + "channel-field-schema": "프로토콜", + "channel-field-targets": "대상", + "channel-field-token": "토큰", + "channel-field-user": "사용자 이름", + "channel-field-verify": "SSL 인증서 확인", "channel-last-error": "마지막 오류: {error}", "channel-last-sent": "마지막 전송: {when}", "channel-level-error": "오류만", @@ -31,10 +39,12 @@ "channel-resend-failed": "새 코드를 보낼 수 없습니다", "channel-save-failed": "채널을 저장할 수 없습니다", "channel-saved": "채널이 저장되었습니다", - "channel-secret-json": "서명 비밀 키 (선택)", + "channel-search-services": "서비스 검색", + "channel-secret": "서명 비밀 키 (선택)", "channel-secret-keep": "현재 값을 유지하려면 비워 두세요", - "channel-secret-ntfy": "액세스 토큰 (선택)", "channel-secret-remove": "제거", + "channel-services-failed": "Apprise 서비스를 불러오지 못했습니다", + "channel-setup-guide": "{service} 설정 방법", "channel-test": "테스트 보내기", "channel-test-failed": "테스트 실패: {error}", "channel-test-ok": "테스트를 보냈습니다", @@ -42,14 +52,14 @@ "channel-topics-all": "모든 주제", "channel-type": "유형", "channel-type-email": "이메일", - "channel-type-webhook": "웹훅", + "channel-type-webhook": "RomM 웹훅 (JSON)", "channel-update-failed": "채널을 업데이트할 수 없습니다", "channel-url": "URL", "channel-url-invalid": "http:// 또는 https://로 시작해야 합니다", "channel-url-keep": "현재 URL을 유지하려면 비워 두세요", "channels": "채널", "channels-empty": "아직 채널이 없습니다", - "channels-empty-hint": "알림을 Discord, ntfy, 이메일 또는 모든 웹훅으로 전달하세요.", + "channels-empty-hint": "알림을 RomM 밖으로 전달하세요. 웹훅, 이메일 주소 등으로 보낼 수 있습니다.", "channels-load-failed": "채널을 불러올 수 없습니다", "dismiss-all": "모두 닫기", "dismiss-all-body": "모든 알림이 삭제됩니다.", diff --git a/frontend/src/locales/pl_PL/notifications.json b/frontend/src/locales/pl_PL/notifications.json index 3449f794d..08e9e8ebd 100644 --- a/frontend/src/locales/pl_PL/notifications.json +++ b/frontend/src/locales/pl_PL/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Dodaj kanał", "channel-address": "Adres e-mail", "channel-address-hint": "Wyślemy kod, aby potwierdzić, że należy do Ciebie", + "channel-advanced": "Opcje zaawansowane", "channel-awaiting-code": "Wpisz kod z e-maila, aby zacząć otrzymywać tu powiadomienia", "channel-code": "Kod", "channel-code-sent": "Wysłaliśmy kod na adres {address}", @@ -15,10 +16,17 @@ "channel-edit": "Edytuj kanał", "channel-email-unavailable": "E-mail nie jest skonfigurowany na tym serwerze", "channel-enabled": "Wysyłaj tu powiadomienia", - "channel-format": "Format", - "channel-format-discord": "Discord", - "channel-format-json": "JSON RomM", - "channel-format-ntfy": "ntfy", + "channel-field-host": "Host", + "channel-field-list-hint": "Po każdej pozycji naciśnij Enter", + "channel-field-number": "Musi być liczbą od {min} do {max}", + "channel-field-password": "Hasło", + "channel-field-path": "Ścieżka", + "channel-field-port": "Port", + "channel-field-schema": "Protokół", + "channel-field-targets": "Odbiorcy", + "channel-field-token": "Token", + "channel-field-user": "Nazwa użytkownika", + "channel-field-verify": "Weryfikuj certyfikat SSL", "channel-last-error": "Ostatni błąd: {error}", "channel-last-sent": "Ostatnio wysłano: {when}", "channel-level-error": "Tylko błędy", @@ -31,10 +39,12 @@ "channel-resend-failed": "Nie udało się wysłać nowego kodu", "channel-save-failed": "Nie udało się zapisać kanału", "channel-saved": "Kanał zapisany", - "channel-secret-json": "Sekret podpisu (opcjonalnie)", + "channel-search-services": "Szukaj usług", + "channel-secret": "Sekret podpisu (opcjonalnie)", "channel-secret-keep": "Zostaw puste, aby zachować obecny", - "channel-secret-ntfy": "Token dostępu (opcjonalnie)", "channel-secret-remove": "Usuń go", + "channel-services-failed": "Nie udało się wczytać usług Apprise", + "channel-setup-guide": "Jak skonfigurować {service}", "channel-test": "Wyślij test", "channel-test-failed": "Test nie powiódł się: {error}", "channel-test-ok": "Test wysłany", @@ -42,14 +52,14 @@ "channel-topics-all": "Wszystkie tematy", "channel-type": "Typ", "channel-type-email": "E-mail", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "Webhook RomM (JSON)", "channel-update-failed": "Nie udało się zaktualizować kanału", "channel-url": "URL", "channel-url-invalid": "Musi zaczynać się od http:// lub https://", "channel-url-keep": "Zostaw puste, aby zachować obecny URL", "channels": "Kanały", "channels-empty": "Brak kanałów", - "channels-empty-hint": "Przekazuj powiadomienia do Discorda, ntfy, na e-mail lub do dowolnego webhooka.", + "channels-empty-hint": "Przekazuj powiadomienia poza RomM: do webhooka, na adres e-mail i nie tylko.", "channels-load-failed": "Nie udało się wczytać Twoich kanałów", "dismiss-all": "Odrzuć wszystkie", "dismiss-all-body": "Wszystkie powiadomienia zostaną usunięte.", diff --git a/frontend/src/locales/pt_BR/notifications.json b/frontend/src/locales/pt_BR/notifications.json index cb73d3c0a..2e10edb6f 100644 --- a/frontend/src/locales/pt_BR/notifications.json +++ b/frontend/src/locales/pt_BR/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Adicionar canal", "channel-address": "Endereço de e-mail", "channel-address-hint": "Enviaremos um código para confirmar que é seu", + "channel-advanced": "Opções avançadas", "channel-awaiting-code": "Digite o código que enviamos por e-mail para começar a receber notificações aqui", "channel-code": "Código", "channel-code-sent": "Enviamos um código para {address}", @@ -15,10 +16,17 @@ "channel-edit": "Editar canal", "channel-email-unavailable": "O e-mail não está configurado neste servidor", "channel-enabled": "Enviar notificações aqui", - "channel-format": "Formato", - "channel-format-discord": "Discord", - "channel-format-json": "JSON do RomM", - "channel-format-ntfy": "ntfy", + "channel-field-host": "Host", + "channel-field-list-hint": "Pressione Enter depois de cada um", + "channel-field-number": "Deve ser um número de {min} a {max}", + "channel-field-password": "Senha", + "channel-field-path": "Caminho", + "channel-field-port": "Porta", + "channel-field-schema": "Protocolo", + "channel-field-targets": "Destinos", + "channel-field-token": "Token", + "channel-field-user": "Usuário", + "channel-field-verify": "Verificar o certificado SSL", "channel-last-error": "Último erro: {error}", "channel-last-sent": "Último envio: {when}", "channel-level-error": "Somente erros", @@ -31,10 +39,12 @@ "channel-resend-failed": "Não foi possível enviar um novo código", "channel-save-failed": "Não foi possível salvar o canal", "channel-saved": "Canal salvo", - "channel-secret-json": "Segredo de assinatura (opcional)", + "channel-search-services": "Buscar serviços", + "channel-secret": "Segredo de assinatura (opcional)", "channel-secret-keep": "Deixe em branco para manter o atual", - "channel-secret-ntfy": "Token de acesso (opcional)", "channel-secret-remove": "Removê-lo", + "channel-services-failed": "Não foi possível carregar os serviços do Apprise", + "channel-setup-guide": "Como configurar o {service}", "channel-test": "Enviar um teste", "channel-test-failed": "O teste falhou: {error}", "channel-test-ok": "Teste enviado", @@ -42,14 +52,14 @@ "channel-topics-all": "Todos os tópicos", "channel-type": "Tipo", "channel-type-email": "E-mail", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "Webhook do RomM (JSON)", "channel-update-failed": "Não foi possível atualizar o canal", "channel-url": "URL", "channel-url-invalid": "Deve começar com http:// ou https://", "channel-url-keep": "Deixe em branco para manter a URL atual", "channels": "Canais", "channels-empty": "Nenhum canal ainda", - "channels-empty-hint": "Encaminhe suas notificações para o Discord, ntfy, e-mail ou qualquer webhook.", + "channels-empty-hint": "Encaminhe suas notificações para fora do RomM: para um webhook, um endereço de e-mail e mais.", "channels-load-failed": "Não foi possível carregar seus canais", "dismiss-all": "Dispensar todas", "dismiss-all-body": "Todas as notificações serão removidas.", diff --git a/frontend/src/locales/ro_RO/notifications.json b/frontend/src/locales/ro_RO/notifications.json index b653deea8..bc94d4541 100644 --- a/frontend/src/locales/ro_RO/notifications.json +++ b/frontend/src/locales/ro_RO/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Adaugă canal", "channel-address": "Adresă de e-mail", "channel-address-hint": "Îți vom trimite un cod ca să confirmi că este a ta", + "channel-advanced": "Opțiuni avansate", "channel-awaiting-code": "Introdu codul primit pe e-mail ca să începi să primești notificări aici", "channel-code": "Cod", "channel-code-sent": "Am trimis un cod la {address}", @@ -15,10 +16,17 @@ "channel-edit": "Editează canalul", "channel-email-unavailable": "E-mailul nu este configurat pe acest server", "channel-enabled": "Trimite notificări aici", - "channel-format": "Format", - "channel-format-discord": "Discord", - "channel-format-json": "JSON RomM", - "channel-format-ntfy": "ntfy", + "channel-field-host": "Gazdă", + "channel-field-list-hint": "Apasă Enter după fiecare", + "channel-field-number": "Trebuie să fie un număr între {min} și {max}", + "channel-field-password": "Parolă", + "channel-field-path": "Cale", + "channel-field-port": "Port", + "channel-field-schema": "Protocol", + "channel-field-targets": "Destinatari", + "channel-field-token": "Token", + "channel-field-user": "Nume de utilizator", + "channel-field-verify": "Verifică certificatul SSL", "channel-last-error": "Ultima eroare: {error}", "channel-last-sent": "Ultima trimitere: {when}", "channel-level-error": "Doar erori", @@ -31,10 +39,12 @@ "channel-resend-failed": "Nu s-a putut trimite un cod nou", "channel-save-failed": "Canalul nu a putut fi salvat", "channel-saved": "Canal salvat", - "channel-secret-json": "Secret de semnare (opțional)", + "channel-search-services": "Caută servicii", + "channel-secret": "Secret de semnare (opțional)", "channel-secret-keep": "Lasă gol ca să păstrezi valoarea actuală", - "channel-secret-ntfy": "Token de acces (opțional)", "channel-secret-remove": "Elimină-l", + "channel-services-failed": "Serviciile Apprise nu au putut fi încărcate", + "channel-setup-guide": "Cum configurezi {service}", "channel-test": "Trimite un test", "channel-test-failed": "Testul a eșuat: {error}", "channel-test-ok": "Test trimis", @@ -42,14 +52,14 @@ "channel-topics-all": "Toate subiectele", "channel-type": "Tip", "channel-type-email": "E-mail", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "Webhook RomM (JSON)", "channel-update-failed": "Canalul nu a putut fi actualizat", "channel-url": "URL", "channel-url-invalid": "Trebuie să înceapă cu http:// sau https://", "channel-url-keep": "Lasă gol ca să păstrezi URL-ul actual", "channels": "Canale", "channels-empty": "Încă nu există canale", - "channels-empty-hint": "Redirecționează notificările către Discord, ntfy, e-mail sau orice webhook.", + "channels-empty-hint": "Redirecționează notificările în afara RomM: către un webhook, o adresă de e-mail și altele.", "channels-load-failed": "Canalele tale nu au putut fi încărcate", "dismiss-all": "Închide toate", "dismiss-all-body": "Toate notificările vor fi eliminate.", diff --git a/frontend/src/locales/ru_RU/notifications.json b/frontend/src/locales/ru_RU/notifications.json index 5edf2a668..3a0d8eddb 100644 --- a/frontend/src/locales/ru_RU/notifications.json +++ b/frontend/src/locales/ru_RU/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Добавить канал", "channel-address": "Адрес эл. почты", "channel-address-hint": "Мы отправим код, чтобы подтвердить, что адрес ваш", + "channel-advanced": "Дополнительные параметры", "channel-awaiting-code": "Введите код из письма, чтобы начать получать сюда уведомления", "channel-code": "Код", "channel-code-sent": "Мы отправили код на {address}", @@ -15,10 +16,17 @@ "channel-edit": "Изменить канал", "channel-email-unavailable": "Эл. почта на этом сервере не настроена", "channel-enabled": "Отправлять уведомления сюда", - "channel-format": "Формат", - "channel-format-discord": "Discord", - "channel-format-json": "JSON RomM", - "channel-format-ntfy": "ntfy", + "channel-field-host": "Хост", + "channel-field-list-hint": "Нажимайте Enter после каждого", + "channel-field-number": "Должно быть числом от {min} до {max}", + "channel-field-password": "Пароль", + "channel-field-path": "Путь", + "channel-field-port": "Порт", + "channel-field-schema": "Протокол", + "channel-field-targets": "Получатели", + "channel-field-token": "Токен", + "channel-field-user": "Имя пользователя", + "channel-field-verify": "Проверять SSL-сертификат", "channel-last-error": "Последняя ошибка: {error}", "channel-last-sent": "Последняя отправка: {when}", "channel-level-error": "Только ошибки", @@ -31,10 +39,12 @@ "channel-resend-failed": "Не удалось отправить новый код", "channel-save-failed": "Не удалось сохранить канал", "channel-saved": "Канал сохранён", - "channel-secret-json": "Секрет подписи (необязательно)", + "channel-search-services": "Поиск сервисов", + "channel-secret": "Секрет подписи (необязательно)", "channel-secret-keep": "Оставьте пустым, чтобы сохранить текущий", - "channel-secret-ntfy": "Токен доступа (необязательно)", "channel-secret-remove": "Удалить его", + "channel-services-failed": "Не удалось загрузить сервисы Apprise", + "channel-setup-guide": "Как настроить {service}", "channel-test": "Отправить тест", "channel-test-failed": "Тест не прошёл: {error}", "channel-test-ok": "Тест отправлен", @@ -42,14 +52,14 @@ "channel-topics-all": "Все темы", "channel-type": "Тип", "channel-type-email": "Эл. почта", - "channel-type-webhook": "Вебхук", + "channel-type-webhook": "Вебхук RomM (JSON)", "channel-update-failed": "Не удалось обновить канал", "channel-url": "URL", "channel-url-invalid": "Должен начинаться с http:// или https://", "channel-url-keep": "Оставьте пустым, чтобы сохранить текущий URL", "channels": "Каналы", "channels-empty": "Каналов пока нет", - "channels-empty-hint": "Пересылайте уведомления в Discord, ntfy, на эл. почту или в любой вебхук.", + "channels-empty-hint": "Пересылайте уведомления за пределы RomM: в вебхук, на адрес эл. почты и не только.", "channels-load-failed": "Не удалось загрузить ваши каналы", "dismiss-all": "Закрыть все", "dismiss-all-body": "Все уведомления будут удалены.", diff --git a/frontend/src/locales/tr_TR/notifications.json b/frontend/src/locales/tr_TR/notifications.json index 4540cbfee..79df1c1f4 100644 --- a/frontend/src/locales/tr_TR/notifications.json +++ b/frontend/src/locales/tr_TR/notifications.json @@ -2,6 +2,7 @@ "channel-add": "Kanal ekle", "channel-address": "E-posta adresi", "channel-address-hint": "Size ait olduğunu doğrulamak için bir kod göndereceğiz", + "channel-advanced": "Gelişmiş seçenekler", "channel-awaiting-code": "Buraya bildirim almaya başlamak için e-postayla gönderdiğimiz kodu girin", "channel-code": "Kod", "channel-code-sent": "{address} adresine bir kod gönderdik", @@ -15,10 +16,17 @@ "channel-edit": "Kanalı düzenle", "channel-email-unavailable": "Bu sunucuda e-posta ayarlanmamış", "channel-enabled": "Bildirimleri buraya gönder", - "channel-format": "Biçim", - "channel-format-discord": "Discord", - "channel-format-json": "RomM JSON", - "channel-format-ntfy": "ntfy", + "channel-field-host": "Sunucu", + "channel-field-list-hint": "Her birinden sonra Enter'a basın", + "channel-field-number": "{min} ile {max} arasında bir sayı olmalı", + "channel-field-password": "Parola", + "channel-field-path": "Yol", + "channel-field-port": "Port", + "channel-field-schema": "Protokol", + "channel-field-targets": "Hedefler", + "channel-field-token": "Token", + "channel-field-user": "Kullanıcı adı", + "channel-field-verify": "SSL sertifikasını doğrula", "channel-last-error": "Son hata: {error}", "channel-last-sent": "Son gönderim: {when}", "channel-level-error": "Yalnızca hatalar", @@ -31,10 +39,12 @@ "channel-resend-failed": "Yeni kod gönderilemedi", "channel-save-failed": "Kanal kaydedilemedi", "channel-saved": "Kanal kaydedildi", - "channel-secret-json": "İmza anahtarı (isteğe bağlı)", + "channel-search-services": "Hizmet ara", + "channel-secret": "İmza anahtarı (isteğe bağlı)", "channel-secret-keep": "Mevcut olanı korumak için boş bırakın", - "channel-secret-ntfy": "Erişim belirteci (isteğe bağlı)", "channel-secret-remove": "Kaldır", + "channel-services-failed": "Apprise hizmetleri yüklenemedi", + "channel-setup-guide": "{service} nasıl kurulur", "channel-test": "Test gönder", "channel-test-failed": "Test başarısız: {error}", "channel-test-ok": "Test gönderildi", @@ -42,14 +52,14 @@ "channel-topics-all": "Tüm konular", "channel-type": "Tür", "channel-type-email": "E-posta", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "RomM webhook'u (JSON)", "channel-update-failed": "Kanal güncellenemedi", "channel-url": "URL", "channel-url-invalid": "http:// veya https:// ile başlamalı", "channel-url-keep": "Mevcut URL'yi korumak için boş bırakın", "channels": "Kanallar", "channels-empty": "Henüz kanal yok", - "channels-empty-hint": "Bildirimlerinizi Discord, ntfy, e-posta veya herhangi bir webhook'a iletin.", + "channels-empty-hint": "Bildirimlerinizi RomM dışına iletin: bir webhook'a, bir e-posta adresine ve daha fazlasına.", "channels-load-failed": "Kanallarınız yüklenemedi", "dismiss-all": "Tümünü kapat", "dismiss-all-body": "Tüm bildirimler kaldırılacak.", diff --git a/frontend/src/locales/zh_CN/notifications.json b/frontend/src/locales/zh_CN/notifications.json index 27ad167b1..9a559998c 100644 --- a/frontend/src/locales/zh_CN/notifications.json +++ b/frontend/src/locales/zh_CN/notifications.json @@ -2,6 +2,7 @@ "channel-add": "添加渠道", "channel-address": "电子邮件地址", "channel-address-hint": "我们会发送验证码以确认该地址属于你", + "channel-advanced": "高级选项", "channel-awaiting-code": "输入邮件中的验证码,即可开始在这里接收通知", "channel-code": "验证码", "channel-code-sent": "我们已向 {address} 发送验证码", @@ -15,10 +16,17 @@ "channel-edit": "编辑渠道", "channel-email-unavailable": "此服务器未配置电子邮件", "channel-enabled": "向这里发送通知", - "channel-format": "格式", - "channel-format-discord": "Discord", - "channel-format-json": "RomM JSON", - "channel-format-ntfy": "ntfy", + "channel-field-host": "主机", + "channel-field-list-hint": "每输入一项后按回车", + "channel-field-number": "必须是 {min} 到 {max} 之间的数字", + "channel-field-password": "密码", + "channel-field-path": "路径", + "channel-field-port": "端口", + "channel-field-schema": "协议", + "channel-field-targets": "目标", + "channel-field-token": "令牌", + "channel-field-user": "用户名", + "channel-field-verify": "验证 SSL 证书", "channel-last-error": "最近的错误:{error}", "channel-last-sent": "最近发送:{when}", "channel-level-error": "仅错误", @@ -31,10 +39,12 @@ "channel-resend-failed": "无法发送新验证码", "channel-save-failed": "无法保存渠道", "channel-saved": "渠道已保存", - "channel-secret-json": "签名密钥(可选)", + "channel-search-services": "搜索服务", + "channel-secret": "签名密钥(可选)", "channel-secret-keep": "留空以保留当前值", - "channel-secret-ntfy": "访问令牌(可选)", "channel-secret-remove": "移除", + "channel-services-failed": "无法加载 Apprise 服务", + "channel-setup-guide": "如何设置 {service}", "channel-test": "发送测试", "channel-test-failed": "测试失败:{error}", "channel-test-ok": "测试已发送", @@ -42,14 +52,14 @@ "channel-topics-all": "所有主题", "channel-type": "类型", "channel-type-email": "电子邮件", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "RomM Webhook(JSON)", "channel-update-failed": "无法更新渠道", "channel-url": "URL", "channel-url-invalid": "必须以 http:// 或 https:// 开头", "channel-url-keep": "留空以保留当前 URL", "channels": "渠道", "channels-empty": "暂无渠道", - "channels-empty-hint": "将你的通知转发到 Discord、ntfy、电子邮件或任意 Webhook。", + "channels-empty-hint": "将你的通知转发到 RomM 之外:Webhook、电子邮件地址等。", "channels-load-failed": "无法加载你的渠道", "dismiss-all": "全部忽略", "dismiss-all-body": "所有通知都将被移除。", diff --git a/frontend/src/locales/zh_TW/notifications.json b/frontend/src/locales/zh_TW/notifications.json index eccb7d7e4..60d474d0b 100644 --- a/frontend/src/locales/zh_TW/notifications.json +++ b/frontend/src/locales/zh_TW/notifications.json @@ -2,6 +2,7 @@ "channel-add": "新增管道", "channel-address": "電子郵件地址", "channel-address-hint": "我們會寄送驗證碼以確認該地址屬於你", + "channel-advanced": "進階選項", "channel-awaiting-code": "輸入郵件中的驗證碼,即可開始在這裡接收通知", "channel-code": "驗證碼", "channel-code-sent": "我們已寄送驗證碼至 {address}", @@ -15,10 +16,17 @@ "channel-edit": "編輯管道", "channel-email-unavailable": "此伺服器未設定電子郵件", "channel-enabled": "將通知傳送到這裡", - "channel-format": "格式", - "channel-format-discord": "Discord", - "channel-format-json": "RomM JSON", - "channel-format-ntfy": "ntfy", + "channel-field-host": "主機", + "channel-field-list-hint": "每輸入一項後按 Enter", + "channel-field-number": "必須是 {min} 到 {max} 之間的數字", + "channel-field-password": "密碼", + "channel-field-path": "路徑", + "channel-field-port": "連接埠", + "channel-field-schema": "通訊協定", + "channel-field-targets": "目標", + "channel-field-token": "權杖", + "channel-field-user": "使用者名稱", + "channel-field-verify": "驗證 SSL 憑證", "channel-last-error": "最近的錯誤:{error}", "channel-last-sent": "最近傳送:{when}", "channel-level-error": "僅錯誤", @@ -31,10 +39,12 @@ "channel-resend-failed": "無法寄送新驗證碼", "channel-save-failed": "無法儲存管道", "channel-saved": "管道已儲存", - "channel-secret-json": "簽章密鑰(選填)", + "channel-search-services": "搜尋服務", + "channel-secret": "簽章密鑰(選填)", "channel-secret-keep": "留空以保留目前的值", - "channel-secret-ntfy": "存取權杖(選填)", "channel-secret-remove": "移除", + "channel-services-failed": "無法載入 Apprise 服務", + "channel-setup-guide": "如何設定 {service}", "channel-test": "傳送測試", "channel-test-failed": "測試失敗:{error}", "channel-test-ok": "測試已傳送", @@ -42,14 +52,14 @@ "channel-topics-all": "所有主題", "channel-type": "類型", "channel-type-email": "電子郵件", - "channel-type-webhook": "Webhook", + "channel-type-webhook": "RomM Webhook(JSON)", "channel-update-failed": "無法更新管道", "channel-url": "URL", "channel-url-invalid": "必須以 http:// 或 https:// 開頭", "channel-url-keep": "留空以保留目前的 URL", "channels": "管道", "channels-empty": "尚無管道", - "channels-empty-hint": "將你的通知轉發到 Discord、ntfy、電子郵件或任何 Webhook。", + "channels-empty-hint": "將你的通知轉發到 RomM 之外:Webhook、電子郵件地址等。", "channels-load-failed": "無法載入你的管道", "dismiss-all": "全部關閉", "dismiss-all-body": "所有通知都將被移除。", diff --git a/frontend/src/services/api/notificationChannel.ts b/frontend/src/services/api/notificationChannel.ts index ef8f412d4..2c632fe13 100644 --- a/frontend/src/services/api/notificationChannel.ts +++ b/frontend/src/services/api/notificationChannel.ts @@ -1,4 +1,6 @@ import type { + AppriseChannelCreatePayload, + AppriseServiceSchema, EmailChannelCreatePayload, NotificationChannelSchema, NotificationChannelTestResult, @@ -7,13 +9,22 @@ import type { } from "@/__generated__"; import api from "@/services/api"; +export type NotificationChannelCreatePayload = + | AppriseChannelCreatePayload + | WebhookChannelCreatePayload + | EmailChannelCreatePayload; + async function getChannels() { return api.get("/notification-channels"); } -async function create( - payload: WebhookChannelCreatePayload | EmailChannelCreatePayload, -) { +async function getAppriseServices() { + return api.get( + "/notification-channels/apprise-services", + ); +} + +async function create(payload: NotificationChannelCreatePayload) { return api.post("/notification-channels", payload); } @@ -47,6 +58,7 @@ async function resendCode(id: number) { export default { getChannels, + getAppriseServices, create, update, remove, diff --git a/frontend/src/v2/components/Notifications/AppriseFieldInput.vue b/frontend/src/v2/components/Notifications/AppriseFieldInput.vue new file mode 100644 index 000000000..2505faf83 --- /dev/null +++ b/frontend/src/v2/components/Notifications/AppriseFieldInput.vue @@ -0,0 +1,105 @@ + + + diff --git a/frontend/src/v2/components/Notifications/AppriseServiceFields.vue b/frontend/src/v2/components/Notifications/AppriseServiceFields.vue new file mode 100644 index 000000000..8d156f976 --- /dev/null +++ b/frontend/src/v2/components/Notifications/AppriseServiceFields.vue @@ -0,0 +1,77 @@ + + + + + diff --git a/frontend/src/v2/components/Notifications/NotificationChannelDialog.test.ts b/frontend/src/v2/components/Notifications/NotificationChannelDialog.test.ts index 8bc334794..4ba873383 100644 --- a/frontend/src/v2/components/Notifications/NotificationChannelDialog.test.ts +++ b/frontend/src/v2/components/Notifications/NotificationChannelDialog.test.ts @@ -1,12 +1,21 @@ +import { RComboboxField, RSelect } from "@v2/lib"; import { flushPromises, mount } from "@vue/test-utils"; import { createPinia, setActivePinia } from "pinia"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { defineComponent, nextTick } from "vue"; import type { NotificationChannelSchema } from "@/__generated__"; -import { makeChannel } from "@/v2/utils/notificationChannels.fixtures"; +import storePermissions from "@/stores/permissions"; +import { + makeAppriseService, + makeChannel, +} from "@/v2/utils/notificationChannels.fixtures"; import NotificationChannelDialog from "./NotificationChannelDialog.vue"; -const api = vi.hoisted(() => ({ create: vi.fn(), update: vi.fn() })); +const api = vi.hoisted(() => ({ + create: vi.fn(), + update: vi.fn(), + getAppriseServices: vi.fn(), +})); vi.mock("@/services/api/notificationChannel", () => ({ default: api })); vi.mock("vue-i18n", () => ({ @@ -18,16 +27,27 @@ function channel( ): NotificationChannelSchema { return makeChannel({ id: 4, + type: "webhook", name: "Hook", topics: ["scans"], target: "https://hooks.example.com/…oken", - format: "json", + service: null, + service_name: null, + fields: null, has_secret: true, ...overrides, }); } -async function open(existing: NotificationChannelSchema | null = null) { +const WEBHOOK_PLACEHOLDER = '[placeholder="https://example.com/hooks/romm"]'; + +async function open( + existing: NotificationChannelSchema | null = null, + { admin = false } = {}, +) { + const permissions = storePermissions(); + permissions.isAdmin = admin; + permissions.hydrated = true; const wrapper = mount(NotificationChannelDialog, { props: { modelValue: false, channel: existing }, attachTo: document.body, @@ -41,7 +61,7 @@ async function open(existing: NotificationChannelSchema | null = null) { }, }); await wrapper.setProps({ modelValue: true }); - await nextTick(); + await flushPromises(); return wrapper; } @@ -51,6 +71,18 @@ function input(wrapper: Wrapper, selector: string) { return wrapper.find(`input${selector}`); } +async function pick(wrapper: Wrapper, kind: string) { + wrapper.findAllComponents(RSelect)[0].vm.$emit("update:modelValue", kind); + await nextTick(); +} + +function textField(wrapper: Wrapper, label: string) { + return wrapper + .findAll(".r-text-field") + .find((field) => field.text().includes(label)) + ?.find("input"); +} + async function save(wrapper: Wrapper) { await wrapper .findAll("button") @@ -63,17 +95,17 @@ describe("NotificationChannelDialog", () => { beforeEach(() => { setActivePinia(createPinia()); vi.resetAllMocks(); + api.getAppriseServices.mockResolvedValue({ data: [makeAppriseService()] }); }); - it("creates a JSON webhook that forwards every topic", async () => { + it("creates a webhook that forwards every topic", async () => { api.create.mockResolvedValue({ data: channel() }); const wrapper = await open(); await wrapper.findAll("input.r-text-field__input")[0].setValue(" Hook "); - await input( - wrapper, - '[placeholder="https://example.com/hooks/romm"]', - ).setValue(" https://hooks.example.com/romm "); + await input(wrapper, WEBHOOK_PLACEHOLDER).setValue( + " https://hooks.example.com/romm ", + ); await input(wrapper, '[type="password"]').setValue("s3cret"); await save(wrapper); @@ -81,7 +113,6 @@ describe("NotificationChannelDialog", () => { type: "webhook", name: "Hook", url: "https://hooks.example.com/romm", - format: "json", secret: "s3cret", min_level: "info", topics: null, @@ -95,16 +126,68 @@ describe("NotificationChannelDialog", () => { const wrapper = await open(); await wrapper.findAll("input.r-text-field__input")[0].setValue("Hook"); - await input( - wrapper, - '[placeholder="https://example.com/hooks/romm"]', - ).setValue("ftp://example.com"); + await input(wrapper, WEBHOOK_PLACEHOLDER).setValue("ftp://example.com"); await save(wrapper); expect(api.create).not.toHaveBeenCalled(); wrapper.unmount(); }); + it("builds an admin's Apprise channel from the service's fields", async () => { + api.create.mockResolvedValue({ data: channel({ type: "apprise" }) }); + const wrapper = await open(null, { admin: true }); + + await pick(wrapper, "apprise:ntfy"); + await wrapper.findAll("input.r-text-field__input")[0].setValue("Phone"); + await textField(wrapper, "notifications.channel-field-host")?.setValue( + "ntfy.example.com", + ); + wrapper + .findComponent(RComboboxField) + .vm.$emit("update:modelValue", ["romm"]); + await save(wrapper); + + // The service's defaults (schema, image, priority) stay out of it. + expect(api.create).toHaveBeenCalledWith({ + type: "apprise", + name: "Phone", + service: "ntfy", + fields: { host: "ntfy.example.com", targets: ["romm"] }, + min_level: "info", + topics: null, + }); + wrapper.unmount(); + }); + + it("asks for a required list before saving", async () => { + const wrapper = await open(null, { admin: true }); + + await pick(wrapper, "apprise:ntfy"); + await wrapper.findAll("input.r-text-field__input")[0].setValue("Phone"); + await save(wrapper); + + expect(api.create).not.toHaveBeenCalled(); + expect(wrapper.findComponent(RComboboxField).props("errorMessages")).toBe( + "common.required", + ); + wrapper.unmount(); + }); + + it("offers Apprise's services to admins only", async () => { + const kinds = async (admin: boolean) => { + const wrapper = await open(null, { admin }); + const items = wrapper.findAllComponents(RSelect)[0].props("items") as { + value: string; + }[]; + wrapper.unmount(); + return items.map((item) => item.value); + }; + + expect(await kinds(false)).toEqual(["webhook", "email"]); + expect(await kinds(true)).toEqual(["webhook", "email", "apprise:ntfy"]); + expect(api.getAppriseServices).toHaveBeenCalledOnce(); + }); + it("keeps the URL and secret an edit leaves blank", async () => { api.update.mockResolvedValue({ data: channel() }); const wrapper = await open(channel()); @@ -115,7 +198,35 @@ describe("NotificationChannelDialog", () => { name: "Hook", min_level: "info", topics: ["scans"], - format: "json", + }); + wrapper.unmount(); + }); + + it("keeps the Apprise secrets an edit leaves blank", async () => { + api.update.mockResolvedValue({ data: channel({ type: "apprise" }) }); + const wrapper = await open( + channel({ + type: "apprise", + service: "ntfy", + service_name: "ntfy", + fields: { host: "ntfy.example.com", targets: ["romm"] }, + has_secret: false, + }), + { admin: true }, + ); + + expect( + textField(wrapper, "notifications.channel-field-token")?.attributes( + "type", + ), + ).toBe("password"); + await save(wrapper); + + expect(api.update).toHaveBeenCalledWith(4, { + name: "Hook", + min_level: "info", + topics: ["scans"], + fields: { host: "ntfy.example.com", targets: ["romm"] }, }); wrapper.unmount(); }); @@ -136,7 +247,6 @@ describe("NotificationChannelDialog", () => { const wrapper = await open( channel({ type: "email", - format: null, target: "a@example.com", has_secret: false, }), diff --git a/frontend/src/v2/components/Notifications/NotificationChannelDialog.vue b/frontend/src/v2/components/Notifications/NotificationChannelDialog.vue index cc4b0338a..3208cade8 100644 --- a/frontend/src/v2/components/Notifications/NotificationChannelDialog.vue +++ b/frontend/src/v2/components/Notifications/NotificationChannelDialog.vue @@ -1,6 +1,7 @@ + + diff --git a/frontend/src/v2/components/Notifications/AppriseServiceFields.vue b/frontend/src/v2/components/Notifications/AppriseServiceFields.vue index 8d156f976..50fe80b42 100644 --- a/frontend/src/v2/components/Notifications/AppriseServiceFields.vue +++ b/frontend/src/v2/components/Notifications/AppriseServiceFields.vue @@ -10,13 +10,16 @@ import type { AppriseFieldValue } from "@/v2/utils/notificationChannels"; const props = defineProps<{ service: AppriseServiceSchema; - editing: boolean; + // The secrets the channel already has. + stored: string[]; // Required lists left empty since the last save attempt. missing: string[]; }>(); const values = defineModel>({ required: true, }); +// The stored secrets to drop on save. +const removed = defineModel("removed", { default: () => [] }); const { t } = useI18n(); @@ -26,6 +29,12 @@ const advanced = computed(() => props.service.fields.filter((f) => f.advanced)); function set(key: string, value: AppriseFieldValue) { values.value = { ...values.value, [key]: value }; } + +function setRemoved(key: string, drop: boolean) { + removed.value = drop + ? [...removed.value, key] + : removed.value.filter((k) => k !== key); +}