Merge pull request #4769 from rommapp/claude/notifications-apprise-framework-e5dab1

feat: send notification channels through every Apprise service
This commit is contained in:
Zurdi
2026-09-25 12:23:24 +02:00
committed by GitHub
62 changed files with 3880 additions and 725 deletions

View File

@@ -1,11 +1,14 @@
from collections.abc import Awaitable
from functools import cache
from typing import TypeVar
from fastapi import HTTPException, Request, status
from decorators.auth import protected_route
from endpoints.responses.notification_channel import (
EmailChannelCreatePayload,
AppriseServiceSchema,
AppriseUrlFieldsSchema,
AppriseUrlPayload,
NotificationChannelCodePayload,
NotificationChannelCreatePayload,
NotificationChannelSchema,
@@ -13,9 +16,10 @@ from endpoints.responses.notification_channel import (
NotificationChannelUpdatePayload,
)
from handler.auth.constants import Scope
from handler.auth.dependencies import assert_admin
from handler.database import db_notification_channel_handler
from handler.email_handler import EmailError
from handler.notification_channels import channels
from handler.notification_channels import apprise_channel, channels
from handler.notification_channels.channels import ChannelError
from handler.notification_channels.confirmation import CodeCooldownError
from models.notification_channel import NotificationChannel, NotificationChannelType
@@ -67,31 +71,48 @@ 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."""
assert_admin(request)
return _apprise_catalog()
@protected_route(router.post, "/apprise-services/parse", [Scope.ME_READ])
def parse_apprise_url(
request: Request, payload: AppriseUrlPayload
) -> AppriseUrlFieldsSchema:
"""Read a service's own URL (a Discord webhook's) or an Apprise URL into its fields."""
assert_admin(request)
try:
service, fields = apprise_channel.fields_from_url(payload.url)
except ValueError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
) from exc
return AppriseUrlFieldsSchema(service=service.id, fields=fields)
@cache
def _apprise_catalog() -> list[AppriseServiceSchema]:
return [AppriseServiceSchema.from_service(s) for s in apprise_channel.services()]
@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,
)
# What each type sends it to: a URL and secret, an address, or a service's fields.
target = payload.model_dump(exclude={"type", "name", "min_level", "topics"})
created = channels.create_channel(
request.user,
NotificationChannelType(payload.type),
payload.name,
payload.min_level,
payload.topics,
**target,
)
return NotificationChannelSchema.from_channel(await _as_http(created))
@@ -116,10 +137,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)

View File

@@ -1,19 +1,27 @@
from typing import Annotated, Literal, Self
from typing import Annotated, Literal, Self, TypeAlias
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_MAX_LIST_ITEMS,
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 +30,22 @@ 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)]
_FieldList = Annotated[
list[_FieldText], Field(max_length=NOTIFICATION_CHANNEL_MAX_LIST_ITEMS)
]
AppriseFieldValue: TypeAlias = StrictBool | int | float | _FieldText | _FieldList
AppriseFields = Annotated[
dict[str, AppriseFieldValue], Field(max_length=NOTIFICATION_CHANNEL_MAX_FIELDS)
]
def _check_address(address: str | None) -> str | None:
@@ -43,9 +62,13 @@ 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; `fields` leaves its secrets out, `stored_secrets` names them.
service: str | None
service_name: str | None
fields: dict[str, AppriseFieldValue] | None
stored_secrets: list[str] | None
has_secret: bool
confirmed: bool
last_delivered_at: UTCDatetime | None
@@ -56,7 +79,19 @@ 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, stored_secrets = None, None, None
match channel.type:
case NotificationChannelType.APPRISE if service:
service_name, target = apprise_channel.describe(service, stored_fields)
fields, stored_secrets = apprise_channel.split_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 +103,11 @@ 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,
stored_secrets=stored_secrets,
has_secret=bool(config.get("secret")),
confirmed=channel.confirmed_at is not None,
last_delivered_at=channel.last_delivered_at,
@@ -88,12 +122,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 +146,9 @@ class EmailChannelCreatePayload(_ChannelFilters):
NotificationChannelCreatePayload = Annotated[
WebhookChannelCreatePayload | EmailChannelCreatePayload,
AppriseChannelCreatePayload
| WebhookChannelCreatePayload
| EmailChannelCreatePayload,
Field(discriminator="type"),
]
@@ -118,10 +160,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 value, an empty one goes.
fields: AppriseFields | None = None
check_address = field_validator("address")(_check_address)
@@ -130,6 +173,66 @@ 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
# The fields the URL a service gives out fills in; empty without one.
url_fields: list[str]
fields: list[AppriseFieldSchema]
@classmethod
def from_service(cls, service: AppriseService) -> Self:
return cls(
id=service.id,
name=service.name,
setup_url=service.setup_url,
url_fields=list(service.url_fields),
fields=[AppriseFieldSchema.from_field(field) for field in service.fields],
)
class AppriseUrlPayload(BaseModel):
url: ChannelUrl
class AppriseUrlFieldsSchema(BaseModel):
"""The service a pasted URL is for, and the fields it fills in."""
service: str
fields: dict[str, AppriseFieldValue]
class NotificationChannelTestResult(BaseModel):
ok: bool
error: str | None

View File

@@ -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."""

View File

@@ -0,0 +1,761 @@
"""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, cached_property
from typing import Any, Final, Literal, get_args
from urllib.parse import parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit
from apprise import (
Apprise,
AppriseAsset,
NotificationManager,
NotifyBase,
NotifyFormat,
NotifyType,
)
from apprise.utils.parse import parse_bool
from logger.logger import log
from models.notification import NotificationLevel
from .messages import OutboundMessage
from .webhook import ERROR_DETAIL_CHARS
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,
# and FCM, which opens its key file from a path or URL itself.
EXCLUDED_SCHEMAS: Final = frozenset(
{
"syslog",
"windows",
"macosx",
"dbus",
"gnome",
"kde",
"qt",
"glib",
"blink1",
"fcm",
}
)
# 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 are set here or don't apply.
MANAGED_OPTIONS: Final = frozenset(
{
"cto",
"rto",
"retry",
"wait",
"redirect",
"store",
"optional",
"overflow",
"format",
"emojis",
"tz",
}
)
# Where Apprise's setup guides live, one page per service.
WIKI_PAGE: Final = "https://github.com/caronc/apprise/wiki/Notify_{}"
# Services Apprise reads a URL of their own for (a Discord webhook's), whose
# native URL only covers a corner of what they do, so they keep their fields.
FIELD_SERVICES: Final = frozenset({"matrix", "lametric", "46elks", "wechat"})
# Where a URL points and whom it signs in as.
_URL_PARTS: Final = frozenset(
{"schema", "host", "port", "user", "password", "path", "fullpath"}
)
# Services that post to any path on their host, which no token names.
FREE_PATH_SERVICES: Final = frozenset({"json", "xml", "form"})
# Tokens Apprise doesn't mark private although they are credentials.
_SECRET_NAME: Final = re.compile(r"token|key|secret|pass|webhook|auth|sid", re.I)
# Chat services turn these into pings of a whole server or a role.
_MENTIONS: Final = re.compile(r"@(everyone|here)\b|<[@!]")
NOTIFY_TYPES: Final[dict[str, NotifyType]] = {
NotificationLevel.INFO: NotifyType.INFO,
NotificationLevel.SUCCESS: NotifyType.SUCCESS,
NotificationLevel.WARNING: NotifyType.WARNING,
NotificationLevel.ERROR: NotifyType.FAILURE,
}
# What a service shows as the sender's picture, such as Discord's avatar; it
# fetches it itself, so it has to be public.
ROMM_ICON_URL: Final = (
"https://raw.githubusercontent.com/rommapp/romm/master/"
"frontend/public/android-chrome-512x512.png"
)
_ASSET: Final = AppriseAsset(
app_id="RomM",
app_desc="RomM",
app_url="https://romm.app",
image_url_mask=ROMM_ICON_URL,
image_url_logo=ROMM_ICON_URL,
# 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,
)
_PLACEHOLDER: Final = re.compile(r"{(\w+)}")
# A hostname, an IPv4 address or a bracketed IPv6 one.
_HOST: Final = re.compile(r"\[[0-9a-f:.]+\]|[\w.-]+", re.I)
# 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]
# What Apprise logs about the send running in this context: its warnings, and
# the start of a refusal's reply, which says why (Discord's "Invalid Form Body").
_collected: ContextVar[list[str] | None] = ContextVar("apprise_log", default=None)
_REPLY: Final = "Response Details:"
class _Collector(logging.Handler):
def emit(self, record: logging.LogRecord) -> None:
collected = _collected.get()
if record.levelno >= logging.WARNING:
if collected is None:
# No send reports it, so it goes to the server log.
log.warning(f"Apprise: {record.getMessage()}")
else:
collected.append(record.getMessage())
elif collected is not None and str(record.msg).startswith(_REPLY):
reply = record.getMessage().removeprefix(_REPLY).strip()
# Apprise logs the body as a bytes repr, b'...'.
if reply[:2] in ("b'", 'b"'):
reply = reply[2:-1]
if reply:
collected.append(f"Reply: {reply[:ERROR_DETAIL_CHARS]}")
_apprise_log = logging.getLogger("apprise")
# Down to debug, where the replies are, and past the server log: a send's
# failure is logged once, as the delivery's error.
_apprise_log.setLevel(logging.DEBUG)
_apprise_log.propagate = False
_apprise_log.addHandler(_Collector())
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, ...]
# The fields the URL a service gives out (a Discord webhook's) fills in,
# when it's set up from that URL; empty for a service without one.
url_fields: tuple[str, ...] = ()
@cached_property
def _by_key(self) -> dict[str, AppriseField]:
return {field.key: field for field in self.fields}
@cached_property
def owners(self) -> dict[str, AppriseField]:
"""The list each singular token belongs to."""
return {member: field for field in self.fields for member in field.members}
@cached_property
def patterns(self) -> tuple[re.Pattern[str], ...]:
"""Each template as a pattern for the URL Apprise writes, fullest first."""
ordered = sorted(
self.templates, key=lambda t: len(_PLACEHOLDER.findall(t)), reverse=True
)
return tuple(_template_pattern(self, template) for template in ordered)
@cached_property
def secrets(self) -> frozenset[str]:
return frozenset(field.key for field in self.fields if field.private)
def field(self, key: str) -> AppriseField | None:
return self._by_key.get(key)
def _setup_url(url: str | None) -> str | None:
"""The service's guide on Apprise's wiki, when Apprise points at appriseit.com."""
parts = urlsplit(url or "")
if parts.hostname != "appriseit.com":
return url
slug = parts.path.rstrip("/").rsplit("/", 1)[-1]
return WIKI_PAGE.format(slug) if slug else None
def _field(
key: str, meta: dict[str, Any], *, advanced: bool, required: bool = False
) -> AppriseField | None:
# Apprise's `choice:string` or `list:int`, by the form control it needs.
kind = meta.get("type", "string").split(":", 1)[0]
if kind not in get_args(FieldType):
return None
values = meta.get("values")
private = bool(meta.get("private")) or (
not advanced and kind == "string" and bool(_SECRET_NAME.search(key))
)
return AppriseField(
key=key,
label=meta.get("name") or key,
type=kind,
required=required,
private=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 or EXCLUDED_SCHEMAS & set(protocols):
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:
# A webhook's path often carries its token.
fields.append(
AppriseField(
key=_PATH_TOKEN,
label="Path",
type="string",
required=False,
private=True,
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)
plugin = NotificationManager()[protocols[0]]
native = (
protocols[0] not in FIELD_SERVICES
and plugin.parse_native_url is not NotifyBase.parse_native_url
)
# Such a URL holds what the service needs, where and whom it signs in as;
# what it lacks (a Discord bot name) stays a field.
url_fields = tuple(
field.key
for field in fields
if native
and not field.advanced
and (field.required or field.private or field.key in _URL_PARTS)
)
return AppriseService(
url_fields=url_fields,
id=protocols[0],
name=entry.get("service_name") or protocols[0],
setup_url=_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()))
@cache
def _services_by_id() -> dict[str, AppriseService]:
return {service.id: service for service in services()}
def find_service(service_id: str) -> AppriseService:
"""Raises:
ValueError: RomM has no such Apprise service.
"""
service = _services_by_id().get(service_id)
if service is None:
raise ValueError("Apprise has no such service")
return service
def _blank(value: object) -> bool:
return value is None or value == "" or value == []
def known_fields(
service: AppriseService, fields: Mapping[str, FieldValue]
) -> dict[str, FieldValue]:
"""The fields the service takes that were filled in, defaults left out."""
return {
key: value
for key, value in fields.items()
if (field := service.field(key)) is not None
and not _blank(value)
and value != field.default
}
def _scrub(text: str, service: AppriseService, fields: Mapping[str, FieldValue]) -> str:
"""The text with the channel's secrets hidden, as Apprise may quote them."""
for key in service.secrets:
value = fields.get(key)
if value is None or _blank(value):
continue
for secret in value if isinstance(value, list) else [value]:
for form in {str(secret), quote(str(secret), safe="")}:
text = text.replace(form, "****")
return text
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(field: AppriseField, value: FieldValue) -> str:
"""A token's value as it sits in the URL."""
if field.key == "host":
text = str(value).strip()
if not _HOST.fullmatch(text):
raise ValueError(f"{field.label} isn't a hostname")
return text
if field.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):
return field.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."""
filled, used = template, set()
for key in _PLACEHOLDER.findall(template):
field = service.field(key)
if field is not None and key in tokens:
text = _segment(field, tokens[key])
used.add(key)
elif (owner := service.owners.get(key)) is not None:
# A singular token can come from its list when that holds one item.
items = tokens.get(owner.key)
if not isinstance(items, list) or len(items) != 1:
return None
text = quote(str(items[0]), safe="")
used.add(owner.key)
elif key == "schema":
continue
else:
return None
filled = filled.replace(f"{{{key}}}", text, 1)
return filled, used
def build_url(service: AppriseService, fields: Mapping[str, FieldValue]) -> str:
"""The Apprise URL for a service's fields.
Raises:
ValueError: With a reason fit to show the user.
"""
tokens: dict[str, FieldValue] = {}
options: dict[str, str] = {}
for key, value in known_fields(service, fields).items():
field = service.field(key)
if field is None or key == "schema":
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
)
fit = next(
(
filled
for template in service.templates
if (filled := _fill(service, template, tokens)) and filled[1] == set(tokens)
),
None,
)
if fit is None:
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 = fit[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(service: AppriseService, fields: Mapping[str, FieldValue]) -> NotifyBase:
"""Raises:
ValueError: With a reason fit to show the user, secrets hidden.
"""
try:
plugin = Apprise.instantiate(
build_url(service, fields), asset=_ASSET, suppress_exceptions=False
)
except Exception as exc: # noqa: BLE001 - a plugin says why it refused the URL
reason = str(exc) or "Apprise can't use these fields"
raise ValueError(_scrub(reason, service, fields)) from exc
if plugin is None:
raise ValueError("Apprise can't use these fields")
return plugin
def checked_fields(
service_id: str, fields: Mapping[str, FieldValue]
) -> dict[str, FieldValue]:
"""The fields to keep, once Apprise can deliver with them.
Raises:
ValueError: With a reason fit to show the user.
"""
service = find_service(service_id)
kept = known_fields(service, fields)
_plugin(service, kept)
return kept
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(service, fields)
except ValueError:
return None, ""
scheme, netloc, path, _, _ = urlsplit(plugin.url(privacy=True))
target = urlunsplit((scheme, netloc, path, "", ""))
return service.name, _scrub(target, service, fields)
def split_fields(
service_id: str, fields: Mapping[str, FieldValue]
) -> tuple[dict[str, FieldValue], list[str]]:
"""The fields that aren't secrets, for the owner's form, and which secrets are set."""
try:
service = find_service(service_id)
except ValueError:
return {}, []
kept = known_fields(service, fields)
public = {k: v for k, v in kept.items() if k not in service.secrets}
return public, [key for key in kept if key in service.secrets]
# What each kind of template token matches in the URL Apprise writes.
_TOKEN_PATTERNS: Final = {
"schema": r"[a-z0-9+.-]+",
"host": _HOST.pattern,
"port": r"\d+",
"user": r"[^/:@?#]+",
_PATH_TOKEN: r"/(?:[^?#]*/)?",
}
def _token_pattern(service: AppriseService, key: str) -> str:
if key in _TOKEN_PATTERNS:
return _TOKEN_PATTERNS[key]
field = service.field(key)
return r".+" if field is not None and field.type == "list" else r"[^/@?#]+"
def _template_pattern(service: AppriseService, template: str) -> re.Pattern[str]:
template = template.rstrip("/")
pattern, end = "", 0
for match in _PLACEHOLDER.finditer(template):
key = match.group(1)
pattern += re.escape(template[end : match.start()])
pattern += f"(?P<{key}>{_token_pattern(service, key)})"
end = match.end()
return re.compile(pattern + re.escape(template[end:]), re.I)
def _read(field: AppriseField, text: str, quoted: bool) -> FieldValue | None:
"""A value as it sits in the URL, back in the field's type."""
if field.type == "list":
items = re.split(rf"[{re.escape(field.delimiter)},\s]+", text)
return [unquote(item) if quoted else item for item in items if item]
text = unquote(text) if quoted else text
if field.type == "bool":
return parse_bool(text)
if field.type in ("int", "float"):
try:
return int(text) if field.type == "int" else float(text)
except ValueError:
return None
return text
def fields_from_url(url: str) -> tuple[AppriseService, dict[str, FieldValue]]:
"""The service and fields behind an Apprise URL or a service's own, such as
a Discord webhook's.
Raises:
ValueError: With a reason fit to show the user.
"""
url = url.strip()
if not url or any(char.isspace() for char in url):
raise ValueError("Paste one URL, without spaces")
pasted = urlsplit(url)
if pasted.scheme.lower() in EXCLUDED_SCHEMAS:
raise ValueError("RomM doesn't offer that service")
if {key.lower() for key, _ in parse_qsl(pasted.query)} & FILE_OPTIONS:
raise ValueError("RomM doesn't take the options that read local files")
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 read this URL") from exc
if plugin is None:
raise ValueError("Apprise can't read this URL")
parts = urlsplit(plugin.url(privacy=False))
service = next((s for s in services() if parts.scheme in s.schemas), None)
if service is None:
raise ValueError("RomM doesn't offer that service")
fields: dict[str, FieldValue] = {}
base = f"{parts.scheme}://{parts.netloc}{parts.path}".rstrip("/")
if service.id in FREE_PATH_SERVICES:
fields[_PATH_TOKEN] = unquote(parts.path.strip("/"))
base = f"{parts.scheme}://{parts.netloc}"
match = next((m for p in service.patterns if (m := p.fullmatch(base))), None)
if match is None:
raise ValueError(f"RomM can't read the {service.name} fields from this URL")
for key, text in match.groupdict().items():
field = service.owners.get(key) or service.field(key)
if field is None or key == "schema" or not text:
continue
if (value := _read(field, text, quoted=True)) is not None:
fields[field.key] = value
for key, text in parse_qsl(parts.query, keep_blank_values=True):
field = service.field(key)
if field is None or not field.advanced:
continue
if (value := _read(field, text, quoted=False)) is not None:
fields[key] = value
if len(service.schemas) > 1:
fields["schema"] = parts.scheme
fields = known_fields(service, fields)
# The fields must make the same URL again, or a token was misread.
if _address(_plugin(service, fields).url(privacy=False)) != _address(
plugin.url(privacy=False)
):
raise ValueError(f"RomM can't read the {service.name} fields from this URL")
return service, fields
def _address(url: str) -> tuple[str, str, str]:
"""A URL's scheme, authority and path, as Apprise writes it."""
parts = urlsplit(url)
return parts.scheme.lower(), parts.netloc, unquote(parts.path).rstrip("/")
def _destination(service: AppriseService, fields: Mapping[str, FieldValue]) -> Any:
"""Where the fields send to, as Apprise tells its URLs apart, or None."""
try:
return _plugin(service, fields).url_identifier or None
except ValueError:
return None
def merge_fields(
service_id: str,
stored: Mapping[str, FieldValue],
given: Mapping[str, FieldValue],
) -> dict[str, FieldValue]:
"""The fields after an edit: a secret left out keeps its value, an empty one goes.
Raises:
ValueError: A secret would stay while the address it goes to changes.
"""
service = find_service(service_id)
merged = known_fields(service, given)
kept = {
key: value
for key, value in stored.items()
if key in service.secrets and key not in given
}
if kept:
secrets = {k: v for k, v in stored.items() if k in service.secrets}
before = {k: v for k, v in stored.items() if k not in service.secrets}
after = {k: v for k, v in merged.items() if k not in service.secrets}
# The same secrets on both sides, so only a new address counts.
was = _destination(service, {**before, **secrets})
now = _destination(service, {**after, **secrets})
moved = was != now if was is not None and now is not None else before != after
if moved:
labels = ", ".join(
field.label for field in service.fields if field.key in kept
)
raise ValueError(
f"Enter {labels} again for the new address, "
f"or remove {'it' if len(kept) == 1 else 'them'}"
)
return {**merged, **kept}
def _defuse_mentions(text: str) -> str:
"""The text with its mentions broken by a zero-width space, so they ping nobody."""
return _MENTIONS.sub(lambda m: m.group(0)[0] + "\u200b" + m.group(0)[1:], text)
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.
"""
service = find_service(service_id)
plugin = _bounded(_plugin(service, fields))
apprise = Apprise(asset=_ASSET)
apprise.add(plugin)
collected: list[str] = []
token = _collected.set(collected)
try:
sent = apprise.notify(
body=_defuse_mentions(message.text),
title=_defuse_mentions(message.title),
notify_type=NOTIFY_TYPES.get(message.notification.level, NotifyType.INFO),
body_format=NotifyFormat.TEXT,
)
finally:
_collected.reset(token)
if not sent:
reason = " ".join(dict.fromkeys(collected))
raise AppriseError(
_scrub(reason, service, fields)
or f"{plugin.service_name} did not take the notification"
)

View File

@@ -1,6 +1,7 @@
"""Adding, changing, testing and confirming a user's notification channels."""
from collections.abc import Sequence
import asyncio
from collections.abc import Mapping, Sequence
from datetime import datetime, timezone
from typing import Any
@@ -12,13 +13,22 @@ 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 FieldValue
from .config import (
AppriseConfig,
EmailConfig,
WebhookConfig,
origin,
read_config,
seal_config,
)
from .confirmation import check_code, issue_code
from .delivery import (
DELIVERY_TIMEOUT_SECONDS,
describe_error,
may_reach_private_network,
sample_message,
@@ -31,16 +41,30 @@ 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))
kept = apprise_channel.checked_fields(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=kept)
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 +80,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 +92,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 +144,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 +167,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
@@ -181,11 +217,12 @@ async def send_sample(channel: NotificationChannel, user: User) -> str | None:
if channel.confirmed_at is None:
raise ChannelError("Confirm the email address first")
try:
await send_to_channel(
channel,
sample_message(),
allow_private=may_reach_private_network(user.role),
)
async with asyncio.timeout(DELIVERY_TIMEOUT_SECONDS):
await send_to_channel(
channel,
sample_message(),
allow_private=may_reach_private_network(user.role),
)
except Exception as exc: # noqa: BLE001 - the error goes back to the user
error = describe_error(exc)
db_notification_channel_handler.record_failure(channel.id, error, counts=False)

View File

@@ -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))

View File

@@ -30,7 +30,8 @@ _LEVEL_RANK: Final[dict[str, int]] = {
NotificationLevel.ERROR: 2,
}
_RETRY: Final = Retry(max=3, interval=[30, 120, 600])
_JOB_TIMEOUT_SECONDS: Final = 60
# A delivery, queued or tried from the channel's test button, gets this long.
DELIVERY_TIMEOUT_SECONDS: Final = 60
def may_reach_private_network(role: str) -> bool:
@@ -39,6 +40,8 @@ def may_reach_private_network(role: str) -> bool:
def describe_error(exc: Exception) -> str:
if isinstance(exc, TimeoutError):
return f"No answer within {DELIVERY_TIMEOUT_SECONDS} seconds"
return str(exc) or type(exc).__name__
@@ -74,7 +77,7 @@ def enqueue_channel_deliveries(
deliver_to_channel,
kwargs={"channel_id": channel.id, "notification": payload},
retry=_RETRY,
job_timeout=_JOB_TIMEOUT_SECONDS,
job_timeout=DELIVERY_TIMEOUT_SECONDS,
result_ttl=0,
meta={"task_name": "Notification delivery"},
)
@@ -89,26 +92,30 @@ 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:
# Here, so jobs for other channels don't load Apprise's plugins.
from . import apprise_channel
# Apprise opens its own connections, past the SSRF guard.
if not allow_private:
raise apprise_channel.AppriseError(apprise_channel.ADMINS_ONLY)
await asyncio.to_thread(
apprise_channel.send, config["service"], config["fields"], message
)
case NotificationChannelType.EMAIL:
await asyncio.to_thread(
send_email, config["address"], f"[RomM] {message.title}", message.text
)
case _:
await webhook.send(
WebhookConfig(url=config["url"], secret=config.get("secret")),
message,
allow_private=allow_private,
)
def sample_message() -> OutboundMessage:

View File

@@ -16,6 +16,11 @@ class OutboundMessage:
# Absolute, or None when ROMM_BASE_URL doesn't point anywhere shareable.
url: str | None
@property
def text(self) -> str:
"""The body and link as plain text, or the title when there are neither."""
return "\n\n".join(part for part in (self.body, self.url) if part) or self.title
def _text(value: Any) -> str | None:
return value if isinstance(value, str) and value else None

View File

@@ -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 (

View File

@@ -12,16 +12,13 @@ from utils.database import CustomJSON
class NotificationChannelType(enum.StrEnum):
# Any service Apprise reaches, set up through that service's own fields.
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,10 @@ 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
NOTIFICATION_CHANNEL_MAX_FIELDS: Final = 64
# Each target of a list is its own request to the service.
NOTIFICATION_CHANNEL_MAX_LIST_ITEMS: Final = 20
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 +52,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.

View File

@@ -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,38 @@ 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 body["stored_secrets"] == ["webhook_id", "webhook_token"]
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 +127,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 +163,55 @@ 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_an_admin_pastes_a_discord_webhook(self, client, access_token):
response = client.post(
f"{API}/apprise-services/parse",
json={
"url": "https://discord.com/api/webhooks/1234567890/abcdefghijklmnop"
},
headers=_auth(access_token),
)
assert response.status_code == status.HTTP_200_OK
assert response.json() == {"service": "discord", "fields": _DISCORD}
def test_a_url_it_cant_read_is_refused(self, client, access_token):
response = client.post(
f"{API}/apprise-services/parse",
json={"url": "nowhere://romm"},
headers=_auth(access_token),
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
def test_a_user_gets_none(self, client, viewer_access_token):
listed = client.get(
f"{API}/apprise-services", headers=_auth(viewer_access_token)
)
parsed = client.post(
f"{API}/apprise-services/parse",
json={"url": "ntfys://ntfy.sh/romm"},
headers=_auth(viewer_access_token),
)
assert listed.status_code == status.HTTP_403_FORBIDDEN
assert parsed.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 +309,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)

View File

@@ -0,0 +1,481 @@
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,
checked_fields,
describe,
fields_from_url,
find_service,
merge_fields,
send,
services,
split_fields,
)
from handler.notification_channels.messages import OutboundMessage
from handler.notification_channels.webhook import ERROR_DETAIL_CHARS
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)
# Local schemas, and FCM whose key file Apprise opens itself.
assert not {"syslog", "fcm"} & set(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")
@pytest.mark.parametrize(
"service,url_fields",
[
("discord", ("webhook_id", "webhook_token")),
(
"ntfy",
("schema", "host", "port", "user", "password", "token", "targets"),
),
("pover", ()),
("matrix", ()),
],
)
def test_knows_what_a_services_own_url_fills_in(self, service, url_fields):
assert find_service(service).url_fields == url_fields
def test_points_at_the_setup_guide_on_apprises_wiki(self):
assert find_service("discord").setup_url == (
"https://github.com/caronc/apprise/wiki/Notify_discord"
)
@pytest.mark.parametrize(
"service,key", [("mastodon", "token"), ("rocket", "webhook"), ("json", "path")]
)
def test_treats_credentials_as_secrets_even_unflagged(self, service, key):
field = find_service(service).field(key)
assert field is not None
assert field.private
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(find_service(service), fields) == url
checked_fields(service, fields)
def test_says_what_is_missing(self):
with pytest.raises(ValueError, match="^Discord needs Webhook Token$"):
build_url(find_service("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(find_service("ntfy"), {**fields, "password": "p"})
@pytest.mark.parametrize(
"host", ["example.com/hook?x=1", "{port}.example.com", "example.com:8080"]
)
def test_a_host_is_only_a_host(self, host):
with pytest.raises(ValueError, match="isn't a hostname"):
build_url(find_service("json"), {"host": host, "port": 80})
@pytest.mark.parametrize("host", ["ntfy.example.com", "192.168.1.5", "[::1]"])
def test_takes_names_and_addresses_as_hosts(self, host):
assert build_url(
find_service("ntfy"), {"host": host, "targets": ["romm"]}
).startswith(f"ntfys://{host}/")
def test_ignores_fields_the_form_never_offered(self):
url = build_url(
find_service("discord"), {**_DISCORD, "template": "/etc/passwd"}
)
assert "template" not in url
@pytest.mark.parametrize("service", ["syslog", "fcm", "nowhere"])
def test_knows_only_the_services_it_lists(self, service):
with pytest.raises(ValueError, match="no such service"):
find_service(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_hides_secrets_apprise_would_show(self):
_, target = describe("json", {"host": "hooks.example.com", "path": "t0ken"})
assert target == "jsons://hooks.example.com/****"
def test_hands_the_form_what_isnt_secret_and_names_the_secrets(self):
assert split_fields("discord", {**_DISCORD, "botname": "RomM"}) == (
{"botname": "RomM"},
["webhook_id", "webhook_token"],
)
def test_check_keeps_only_the_fields_the_service_takes(self):
assert (
checked_fields("discord", {**_DISCORD, "junk": "x", "botname": ""})
== _DISCORD
)
def test_a_refusal_hides_the_secret_it_quotes(self):
with pytest.raises(ValueError, match=r"Token \(\*\*\*\*\)"):
checked_fields("slack", {"access_token": "nope-abc"})
class TestFieldsFromUrl:
@pytest.mark.parametrize(
"url,service,fields",
[
(
"https://discord.com/api/webhooks/1234567890/abcdefghijklmnop",
"discord",
_DISCORD,
),
(
"discord://RomM@1234567890/abcdefghijklmnop?image=yes&cto=99",
"discord",
{"botname": "RomM", **_DISCORD, "image": True},
),
(
"ntfy://me:p%40ss@192.168.1.5:8080/a/b",
"ntfy",
{
"schema": "ntfy",
"user": "me",
"password": "p@ss",
"host": "192.168.1.5",
"port": 8080,
"targets": ["a", "b"],
},
),
(
"jsons://hooks.example.com/api/romm",
"json",
{"host": "hooks.example.com", "path": "api/romm"},
),
],
)
def test_reads_a_url_back_into_its_service_and_fields(self, url, service, fields):
found, read = fields_from_url(url)
assert (found.id, read) == (service, fields)
checked_fields(service, read)
@pytest.mark.parametrize(
"url,reason",
[
("syslog://", "doesn't offer"),
("FCM://project/device", "doesn't offer"),
("fcm://project/device", "doesn't offer|can't read"),
(
"discord://1234567890/abcdefghijklmnop?template=/etc/passwd",
"local files",
),
("nowhere://romm", "can't read"),
("https://discord.com/api/webhooks/1 2", "without spaces"),
],
)
def test_says_why_it_cant_read_a_url(self, url, reason):
with pytest.raises(ValueError, match=reason):
fields_from_url(url)
class TestMergeFields:
_NTFY: dict[str, FieldValue] = {
"host": "ntfy.example.com",
"targets": ["romm"],
"token": "tk_1",
}
def test_a_secret_left_out_stays(self):
merged = merge_fields("discord", _DISCORD, {"webhook_id": "1234567890"})
assert merged == _DISCORD
def test_an_empty_secret_goes(self):
given: dict[str, FieldValue] = {
**self._NTFY,
"token": "",
"user": "me",
"password": "pw",
}
assert merge_fields("ntfy", self._NTFY, given) == {
"host": "ntfy.example.com",
"targets": ["romm"],
"user": "me",
"password": "pw",
}
@pytest.mark.parametrize(
"change",
[{"host": "elsewhere.example.com"}, {"port": 8443}, {"schema": "ntfy"}],
)
def test_a_kept_secret_does_not_follow_the_channel_elsewhere(self, change):
given: dict[str, FieldValue] = {
"host": "ntfy.example.com",
"targets": ["romm"],
**change,
}
with pytest.raises(ValueError, match="Enter Token again"):
merge_fields("ntfy", self._NTFY, given)
def test_a_secret_given_again_goes_to_the_new_address(self):
given: dict[str, FieldValue] = {
"host": "elsewhere.example.com",
"targets": ["romm"],
"token": "tk_2",
}
assert merge_fields("ntfy", self._NTFY, given) == given
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_mentions_ping_nobody(self, notify):
calls = notify()
send("json", _JSON, _message(title="@everyone look", body="<@123> and @here"))
[(_, kwargs)] = calls
assert kwargs["title"] == "@\u200beveryone look"
assert kwargs["body"].startswith("<\u200b@123> and @\u200bhere")
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_sends_as_romm_with_its_icon(self, notify):
calls = notify()
send("discord", _DISCORD, _message())
[(apprise, _)] = calls
plugin = apprise[0]
assert plugin.app_id == "RomM"
assert plugin.image_url(NotifyType.INFO) == apprise_channel.ROMM_ICON_URL
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_and_the_start_of_the_reply(
self, notify
):
reply = b'{"message": "Invalid Form Body", "code": 50035}' + b"x" * 500
def log():
logger = logging.getLogger("apprise")
logger.warning("Failed to send Discord notification: error=400.")
logger.debug("Response Details:\r\n%r", reply)
logger.debug("Sent nothing else worth keeping")
notify(result=False, log=log)
with pytest.raises(AppriseError) as caught:
send("json", _JSON, _message())
warning, answered = str(caught.value).split(" Reply: ")
assert warning == "Failed to send Discord notification: error=400."
assert answered.startswith('{"message": "Invalid Form Body", "code": 50035}')
assert len(answered) == ERROR_DETAIL_CHARS
def test_an_empty_reply_adds_nothing(self, notify):
def log():
logger = logging.getLogger("apprise")
logger.warning("Failed to send JSON POST notification: error=500.")
logger.debug("Response Details:\r\n%r", b"")
notify(result=False, log=log)
with pytest.raises(AppriseError, match=r"error=500\.$"):
send("json", _JSON, _message())
def test_a_warning_outside_a_send_goes_to_the_server_log(self, mocker):
server_log = mocker.patch.object(apprise_channel, "log")
logging.getLogger("apprise").warning("A plugin failed to load")
server_log.warning.assert_called_once_with("Apprise: A plugin failed to load")
def test_keeps_no_warning_logged_outside_a_send(self, notify, mocker):
mocker.patch.object(apprise_channel, "log")
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(),
)

View File

@@ -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,71 @@ 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_kept_apprise_secret_does_not_follow_a_new_host(self, db):
stored = _stored(
NotificationChannelType.APPRISE,
service="ntfy",
fields={"host": "ntfy.example.com", "targets": ["a"], "token": "tk_1"},
)
with pytest.raises(ChannelError, match="Enter Token again"):
await update_channel(
stored, ADMIN, {}, fields={"host": "evil.example.com", "targets": ["a"]}
)
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})

View File

@@ -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):

View File

@@ -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(

View File

@@ -1096,19 +1096,29 @@ 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 | `/apprise-services/parse` | ME_READ | Read a pasted URL (Discord's own, or an Apprise one) into its service and fields (admins only) |
| 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 Apprise catalog comes from Apprise's own plugin details: URL tokens become fields, options become advanced fields, and a field is required only when every URL template of its service needs it. A token is a secret when Apprise marks it so or its name is a credential's (`token`, `key`, `webhook`…). A channel stores its service and fields, sealed, and each delivery builds the URL from the template those fields fill. Not offered: schemas that act on the host (`syslog`, `dbus`, `windows`…), FCM (it opens its key file itself), the options Apprise reads from a local file (`template`, `keyfile`, `subfile`, `pgp*`) and the ones RomM sets. Apprise follows no redirects and doesn't retry, its timeouts are capped at 10 s to connect and 15 s to read, a list takes at most 20 items, and `@everyone`, `@here` and `<@…>` ping nobody. A failure's error carries Apprise's warning and the start of the service's reply. Each service links its setup guide on Apprise's wiki. A pasted URL is read back into fields by matching the URL Apprise writes for it against the service's templates. The API returns the fields that aren't secret and names the secrets; on edit, a secret left out stays and an empty one goes, but a kept secret never follows the channel to another destination, as Apprise's `url_identifier` tells them apart. A test gets 60 s, like a queued delivery.
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. 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 +1135,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=<hex HMAC-SHA256 of the body>`. 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=<hex HMAC-SHA256 of the body>`. 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 and secrets again.
### 6.17 Audit Events (`/api/audit-events`)

View File

@@ -10,6 +10,11 @@ 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 { AppriseUrlFieldsSchema } from './models/AppriseUrlFieldsSchema';
export type { AppriseUrlPayload } from './models/AppriseUrlPayload';
export type { AuditAction } from './models/AuditAction';
export type { AuditActorKind } from './models/AuditActorKind';
export type { AuditCategory } from './models/AuditCategory';
@@ -304,7 +309,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';

View File

@@ -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<NotificationTopic> | null);
type: string;
name: string;
service: string;
fields: Record<string, (boolean | number | string | Array<string>)>;
};

View File

@@ -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<string> | null);
values: (Array<string> | null);
min: (number | null);
max: (number | null);
};

View File

@@ -0,0 +1,13 @@
/* 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);
url_fields: Array<string>;
fields: Array<AppriseFieldSchema>;
};

View File

@@ -0,0 +1,12 @@
/* generated using openapi-typescript-codegen -- do not edit */
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
/**
* The service a pasted URL is for, and the fields it fills in.
*/
export type AppriseUrlFieldsSchema = {
service: string;
fields: Record<string, (boolean | number | string | Array<string>)>;
};

View File

@@ -2,4 +2,7 @@
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type WebhookFormat = 'json' | 'discord' | 'ntfy';
export type AppriseUrlPayload = {
url: string;
};

View File

@@ -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,10 @@ export type NotificationChannelSchema = {
min_level: NotificationChannelMinLevel;
topics: (Array<NotificationTopic> | null);
target: string;
format: (WebhookFormat | null);
service: (string | null);
service_name: (string | null);
fields: (Record<string, (boolean | number | string | Array<string>)> | null);
stored_secrets: (Array<string> | null);
has_secret: boolean;
confirmed: boolean;
last_delivered_at: (string | null);

View File

@@ -2,4 +2,4 @@
/* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
export type NotificationChannelType = 'webhook' | 'email';
export type NotificationChannelType = 'apprise' | 'webhook' | 'email';

View File

@@ -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<NotificationTopic> | null);
url?: (string | null);
format?: (WebhookFormat | null);
secret?: (string | null);
address?: (string | null);
fields?: (Record<string, (boolean | number | string | Array<string>)> | null);
};

View File

@@ -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<NotificationTopic> | null);
type: string;
name: string;
url: string;
format?: WebhookFormat;
secret?: (string | null);
};

View File

@@ -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,16 @@
"channel-edit": "Редактирай канала",
"channel-email-unavailable": "Имейлът не е настроен на този сървър",
"channel-enabled": "Изпращай известия тук",
"channel-format": "Формат",
"channel-format-discord": "Discord",
"channel-format-json": "JSON на RomM",
"channel-format-ntfy": "ntfy",
"channel-field-botname": "Име на бота",
"channel-field-host": "Хост",
"channel-field-list-hint": "Натиснете Enter след всеки",
"channel-field-number": "Трябва да е число от {min} до {max}",
"channel-field-path": "Път",
"channel-field-port": "Порт",
"channel-field-schema": "Протокол",
"channel-field-targets": "Получатели",
"channel-field-token": "Токен",
"channel-field-verify": "Проверка на SSL сертификата",
"channel-last-error": "Последна грешка: {error}",
"channel-last-sent": "Последно изпратено: {when}",
"channel-level-error": "Само грешки",
@@ -27,14 +34,23 @@
"channel-min-level": "Изпращай",
"channel-name": "Име",
"channel-new": "Нов канал",
"channel-paste-failed": "Този URL адрес не можа да се прочете",
"channel-paste-filled": "Прочетено от URL адреса: {fields}",
"channel-paste-other-service": "Този URL адрес е за {service}",
"channel-paste-url": "Поставете URL адрес",
"channel-paste-url-hint": "URL адрес на Apprise попълва полетата",
"channel-resend": "Изпрати нов код",
"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-service-url": "URL адрес на {service}",
"channel-service-url-hint": "URL адресът, който ви дава {service}, или URL адрес на Apprise",
"channel-services-failed": "Услугите на Apprise не можаха да се заредят",
"channel-setup-guide": "Как да настроите {service}",
"channel-test": "Изпрати тест",
"channel-test-failed": "Тестът е неуспешен: {error}",
"channel-test-ok": "Тестът е изпратен",
@@ -42,14 +58,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": "Всички известия ще бъдат премахнати.",

View File

@@ -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,16 @@
"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-botname": "Jméno bota",
"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-path": "Cesta",
"channel-field-port": "Port",
"channel-field-schema": "Protokol",
"channel-field-targets": "Cíle",
"channel-field-token": "Token",
"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",
@@ -27,14 +34,23 @@
"channel-min-level": "Posílat",
"channel-name": "Název",
"channel-new": "Nový kanál",
"channel-paste-failed": "Tuto URL se nepodařilo přečíst",
"channel-paste-filled": "Načteno z URL: {fields}",
"channel-paste-other-service": "Tato URL patří službě {service}",
"channel-paste-url": "Vložit URL",
"channel-paste-url-hint": "URL Apprise vyplní pole",
"channel-resend": "Poslat nový kód",
"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-service-url": "URL {service}",
"channel-service-url-hint": "URL, kterou vám dá {service}, nebo URL Apprise",
"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 +58,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.",

View File

@@ -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,16 @@
"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-botname": "Bot-Name",
"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-path": "Pfad",
"channel-field-port": "Port",
"channel-field-schema": "Protokoll",
"channel-field-targets": "Ziele",
"channel-field-token": "Token",
"channel-field-verify": "SSL-Zertifikat prüfen",
"channel-last-error": "Letzter Fehler: {error}",
"channel-last-sent": "Zuletzt gesendet: {when}",
"channel-level-error": "Nur Fehler",
@@ -27,14 +34,23 @@
"channel-min-level": "Senden",
"channel-name": "Name",
"channel-new": "Neuer Kanal",
"channel-paste-failed": "Diese URL konnte nicht gelesen werden",
"channel-paste-filled": "Aus der URL gelesen: {fields}",
"channel-paste-other-service": "Diese URL gehört zu {service}",
"channel-paste-url": "URL einfügen",
"channel-paste-url-hint": "Eine Apprise-URL füllt die Felder aus",
"channel-resend": "Neuen Code senden",
"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-service-url": "{service}-URL",
"channel-service-url-hint": "Die URL, die dir {service} gibt, oder eine Apprise-URL",
"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 +58,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.",

View File

@@ -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,16 @@
"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-botname": "Bot name",
"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-path": "Path",
"channel-field-port": "Port",
"channel-field-schema": "Protocol",
"channel-field-targets": "Targets",
"channel-field-token": "Token",
"channel-field-verify": "Verify the SSL certificate",
"channel-last-error": "Last error: {error}",
"channel-last-sent": "Last sent {when}",
"channel-level-error": "Errors only",
@@ -27,14 +34,23 @@
"channel-min-level": "Send",
"channel-name": "Name",
"channel-new": "New channel",
"channel-paste-failed": "Could not read that URL",
"channel-paste-filled": "Read from the URL: {fields}",
"channel-paste-other-service": "That URL is for {service}",
"channel-paste-url": "Paste a URL",
"channel-paste-url-hint": "An Apprise URL fills in the fields",
"channel-resend": "Send a new code",
"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-service-url": "{service} URL",
"channel-service-url-hint": "The URL {service} gives you, or an Apprise URL",
"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 +58,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.",

View File

@@ -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,16 @@
"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-botname": "Bot name",
"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-path": "Path",
"channel-field-port": "Port",
"channel-field-schema": "Protocol",
"channel-field-targets": "Targets",
"channel-field-token": "Token",
"channel-field-verify": "Verify the SSL certificate",
"channel-last-error": "Last error: {error}",
"channel-last-sent": "Last sent {when}",
"channel-level-error": "Errors only",
@@ -27,14 +34,23 @@
"channel-min-level": "Send",
"channel-name": "Name",
"channel-new": "New channel",
"channel-paste-failed": "Could not read that URL",
"channel-paste-filled": "Read from the URL: {fields}",
"channel-paste-other-service": "That URL is for {service}",
"channel-paste-url": "Paste a URL",
"channel-paste-url-hint": "An Apprise URL fills in the fields",
"channel-resend": "Send a new code",
"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-service-url": "{service} URL",
"channel-service-url-hint": "The URL {service} gives you, or an Apprise URL",
"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 +58,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.",

View File

@@ -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,16 @@
"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-botname": "Nombre del bot",
"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-path": "Ruta",
"channel-field-port": "Puerto",
"channel-field-schema": "Protocolo",
"channel-field-targets": "Destinos",
"channel-field-token": "Token",
"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",
@@ -27,14 +34,23 @@
"channel-min-level": "Enviar",
"channel-name": "Nombre",
"channel-new": "Nuevo canal",
"channel-paste-failed": "No se pudo leer esa URL",
"channel-paste-filled": "Leído de la URL: {fields}",
"channel-paste-other-service": "Esa URL es de {service}",
"channel-paste-url": "Pegar una URL",
"channel-paste-url-hint": "Una URL de Apprise rellena los campos",
"channel-resend": "Enviar otro código",
"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-service-url": "URL de {service}",
"channel-service-url-hint": "La URL que te da {service}, o una URL de Apprise",
"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 +58,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.",

View File

@@ -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,16 @@
"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-botname": "Nom du bot",
"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-path": "Chemin",
"channel-field-port": "Port",
"channel-field-schema": "Protocole",
"channel-field-targets": "Destinataires",
"channel-field-token": "Jeton",
"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",
@@ -27,14 +34,23 @@
"channel-min-level": "Envoyer",
"channel-name": "Nom",
"channel-new": "Nouveau canal",
"channel-paste-failed": "Impossible de lire cette URL",
"channel-paste-filled": "Lu depuis l'URL : {fields}",
"channel-paste-other-service": "Cette URL est pour {service}",
"channel-paste-url": "Coller une URL",
"channel-paste-url-hint": "Une URL Apprise remplit les champs",
"channel-resend": "Envoyer un nouveau code",
"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-service-url": "URL {service}",
"channel-service-url-hint": "L'URL que vous donne {service}, ou une URL Apprise",
"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 +58,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.",

View File

@@ -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,16 @@
"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-botname": "Bot neve",
"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-path": "Útvonal",
"channel-field-port": "Port",
"channel-field-schema": "Protokoll",
"channel-field-targets": "Címzettek",
"channel-field-token": "Token",
"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",
@@ -27,14 +34,23 @@
"channel-min-level": "Küldés",
"channel-name": "Név",
"channel-new": "Új csatorna",
"channel-paste-failed": "Ezt az URL-t nem sikerült beolvasni",
"channel-paste-filled": "Az URL-ből beolvasva: {fields}",
"channel-paste-other-service": "Ez az URL a(z) {service} szolgáltatáshoz tartozik",
"channel-paste-url": "URL beillesztése",
"channel-paste-url-hint": "Egy Apprise-URL kitölti a mezőket",
"channel-resend": "Új kód küldése",
"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-service-url": "{service} URL",
"channel-service-url-hint": "A(z) {service} által adott URL vagy egy Apprise-URL",
"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 +58,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.",

View File

@@ -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,16 @@
"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-botname": "Nome del bot",
"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-path": "Percorso",
"channel-field-port": "Porta",
"channel-field-schema": "Protocollo",
"channel-field-targets": "Destinatari",
"channel-field-token": "Token",
"channel-field-verify": "Verifica il certificato SSL",
"channel-last-error": "Ultimo errore: {error}",
"channel-last-sent": "Ultimo invio: {when}",
"channel-level-error": "Solo errori",
@@ -27,14 +34,23 @@
"channel-min-level": "Invia",
"channel-name": "Nome",
"channel-new": "Nuovo canale",
"channel-paste-failed": "Impossibile leggere questo URL",
"channel-paste-filled": "Letto dall'URL: {fields}",
"channel-paste-other-service": "Questo URL è per {service}",
"channel-paste-url": "Incolla un URL",
"channel-paste-url-hint": "Un URL Apprise compila i campi",
"channel-resend": "Invia un nuovo codice",
"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-service-url": "URL di {service}",
"channel-service-url-hint": "L'URL che ti fornisce {service}, o un URL Apprise",
"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 +58,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.",

View File

@@ -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,16 @@
"channel-edit": "チャンネルを編集",
"channel-email-unavailable": "このサーバーではメールが設定されていません",
"channel-enabled": "ここに通知を送る",
"channel-format": "形式",
"channel-format-discord": "Discord",
"channel-format-json": "RomM JSON",
"channel-format-ntfy": "ntfy",
"channel-field-botname": "ボット名",
"channel-field-host": "ホスト",
"channel-field-list-hint": "1 件ごとに Enter を押してください",
"channel-field-number": "{min} から {max} までの数値を入力してください",
"channel-field-path": "パス",
"channel-field-port": "ポート",
"channel-field-schema": "プロトコル",
"channel-field-targets": "送信先",
"channel-field-token": "トークン",
"channel-field-verify": "SSL 証明書を検証する",
"channel-last-error": "最後のエラー: {error}",
"channel-last-sent": "最終送信: {when}",
"channel-level-error": "エラーのみ",
@@ -27,14 +34,23 @@
"channel-min-level": "送信対象",
"channel-name": "名前",
"channel-new": "新しいチャンネル",
"channel-paste-failed": "その URL を読み取れませんでした",
"channel-paste-filled": "URL から読み取りました: {fields}",
"channel-paste-other-service": "その URL は {service} のものです",
"channel-paste-url": "URL を貼り付け",
"channel-paste-url-hint": "Apprise の URL で各項目を入力できます",
"channel-resend": "新しいコードを送信",
"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-service-url": "{service} の URL",
"channel-service-url-hint": "{service} が発行する URL、または Apprise の URL",
"channel-services-failed": "Apprise のサービスを読み込めませんでした",
"channel-setup-guide": "{service} の設定方法",
"channel-test": "テストを送信",
"channel-test-failed": "テストに失敗しました: {error}",
"channel-test-ok": "テストを送信しました",
@@ -42,14 +58,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": "すべての通知が削除されます。",

View File

@@ -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,16 @@
"channel-edit": "채널 편집",
"channel-email-unavailable": "이 서버에는 이메일이 설정되어 있지 않습니다",
"channel-enabled": "여기로 알림 보내기",
"channel-format": "형식",
"channel-format-discord": "Discord",
"channel-format-json": "RomM JSON",
"channel-format-ntfy": "ntfy",
"channel-field-botname": "봇 이름",
"channel-field-host": "호스트",
"channel-field-list-hint": "항목마다 Enter를 누르세요",
"channel-field-number": "{min}에서 {max} 사이의 숫자여야 합니다",
"channel-field-path": "경로",
"channel-field-port": "포트",
"channel-field-schema": "프로토콜",
"channel-field-targets": "대상",
"channel-field-token": "토큰",
"channel-field-verify": "SSL 인증서 확인",
"channel-last-error": "마지막 오류: {error}",
"channel-last-sent": "마지막 전송: {when}",
"channel-level-error": "오류만",
@@ -27,14 +34,23 @@
"channel-min-level": "보낼 알림",
"channel-name": "이름",
"channel-new": "새 채널",
"channel-paste-failed": "URL을 읽을 수 없습니다",
"channel-paste-filled": "URL에서 읽었습니다: {fields}",
"channel-paste-other-service": "이 URL은 {service}용입니다",
"channel-paste-url": "URL 붙여넣기",
"channel-paste-url-hint": "Apprise URL로 항목을 채웁니다",
"channel-resend": "새 코드 보내기",
"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-service-url": "{service} URL",
"channel-service-url-hint": "{service}에서 받은 URL 또는 Apprise URL",
"channel-services-failed": "Apprise 서비스를 불러오지 못했습니다",
"channel-setup-guide": "{service} 설정 방법",
"channel-test": "테스트 보내기",
"channel-test-failed": "테스트 실패: {error}",
"channel-test-ok": "테스트를 보냈습니다",
@@ -42,14 +58,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": "모든 알림이 삭제됩니다.",

View File

@@ -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,16 @@
"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-botname": "Nazwa bota",
"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-path": "Ścieżka",
"channel-field-port": "Port",
"channel-field-schema": "Protokół",
"channel-field-targets": "Odbiorcy",
"channel-field-token": "Token",
"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",
@@ -27,14 +34,23 @@
"channel-min-level": "Wysyłaj",
"channel-name": "Nazwa",
"channel-new": "Nowy kanał",
"channel-paste-failed": "Nie udało się odczytać tego adresu URL",
"channel-paste-filled": "Odczytano z adresu URL: {fields}",
"channel-paste-other-service": "Ten adres URL jest dla {service}",
"channel-paste-url": "Wklej URL",
"channel-paste-url-hint": "Adres URL Apprise wypełnia pola",
"channel-resend": "Wyślij nowy kod",
"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-service-url": "Adres URL {service}",
"channel-service-url-hint": "Adres URL, który daje {service}, lub adres URL Apprise",
"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 +58,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.",

View File

@@ -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,16 @@
"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-botname": "Nome do bot",
"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-path": "Caminho",
"channel-field-port": "Porta",
"channel-field-schema": "Protocolo",
"channel-field-targets": "Destinos",
"channel-field-token": "Token",
"channel-field-verify": "Verificar o certificado SSL",
"channel-last-error": "Último erro: {error}",
"channel-last-sent": "Último envio: {when}",
"channel-level-error": "Somente erros",
@@ -27,14 +34,23 @@
"channel-min-level": "Enviar",
"channel-name": "Nome",
"channel-new": "Novo canal",
"channel-paste-failed": "Não foi possível ler essa URL",
"channel-paste-filled": "Lido da URL: {fields}",
"channel-paste-other-service": "Essa URL é do {service}",
"channel-paste-url": "Colar uma URL",
"channel-paste-url-hint": "Uma URL do Apprise preenche os campos",
"channel-resend": "Enviar um novo código",
"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-service-url": "URL do {service}",
"channel-service-url-hint": "A URL que o {service} fornece, ou uma URL do Apprise",
"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 +58,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.",

View File

@@ -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,16 @@
"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-botname": "Numele botului",
"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-path": "Cale",
"channel-field-port": "Port",
"channel-field-schema": "Protocol",
"channel-field-targets": "Destinatari",
"channel-field-token": "Token",
"channel-field-verify": "Verifică certificatul SSL",
"channel-last-error": "Ultima eroare: {error}",
"channel-last-sent": "Ultima trimitere: {when}",
"channel-level-error": "Doar erori",
@@ -27,14 +34,23 @@
"channel-min-level": "Trimite",
"channel-name": "Nume",
"channel-new": "Canal nou",
"channel-paste-failed": "URL-ul nu a putut fi citit",
"channel-paste-filled": "Citit din URL: {fields}",
"channel-paste-other-service": "Acest URL este pentru {service}",
"channel-paste-url": "Lipește un URL",
"channel-paste-url-hint": "Un URL Apprise completează câmpurile",
"channel-resend": "Trimite un cod nou",
"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-service-url": "URL {service}",
"channel-service-url-hint": "URL-ul pe care ți-l dă {service} sau un URL Apprise",
"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 +58,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.",

View File

@@ -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,16 @@
"channel-edit": "Изменить канал",
"channel-email-unavailable": "Эл. почта на этом сервере не настроена",
"channel-enabled": "Отправлять уведомления сюда",
"channel-format": "Формат",
"channel-format-discord": "Discord",
"channel-format-json": "JSON RomM",
"channel-format-ntfy": "ntfy",
"channel-field-botname": "Имя бота",
"channel-field-host": "Хост",
"channel-field-list-hint": "Нажимайте Enter после каждого",
"channel-field-number": "Должно быть числом от {min} до {max}",
"channel-field-path": "Путь",
"channel-field-port": "Порт",
"channel-field-schema": "Протокол",
"channel-field-targets": "Получатели",
"channel-field-token": "Токен",
"channel-field-verify": "Проверять SSL-сертификат",
"channel-last-error": "Последняя ошибка: {error}",
"channel-last-sent": "Последняя отправка: {when}",
"channel-level-error": "Только ошибки",
@@ -27,14 +34,23 @@
"channel-min-level": "Отправлять",
"channel-name": "Название",
"channel-new": "Новый канал",
"channel-paste-failed": "Не удалось прочитать этот URL",
"channel-paste-filled": "Прочитано из URL: {fields}",
"channel-paste-other-service": "Этот URL для {service}",
"channel-paste-url": "Вставить URL",
"channel-paste-url-hint": "URL Apprise заполняет поля",
"channel-resend": "Отправить новый код",
"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-service-url": "URL {service}",
"channel-service-url-hint": "URL, который выдаёт {service}, или URL Apprise",
"channel-services-failed": "Не удалось загрузить сервисы Apprise",
"channel-setup-guide": "Как настроить {service}",
"channel-test": "Отправить тест",
"channel-test-failed": "Тест не прошёл: {error}",
"channel-test-ok": "Тест отправлен",
@@ -42,14 +58,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": "Все уведомления будут удалены.",

View File

@@ -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,16 @@
"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-botname": "Bot adı",
"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-path": "Yol",
"channel-field-port": "Port",
"channel-field-schema": "Protokol",
"channel-field-targets": "Hedefler",
"channel-field-token": "Token",
"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",
@@ -27,14 +34,23 @@
"channel-min-level": "Gönder",
"channel-name": "Ad",
"channel-new": "Yeni kanal",
"channel-paste-failed": "Bu URL okunamadı",
"channel-paste-filled": "URL'den okundu: {fields}",
"channel-paste-other-service": "Bu URL {service} için",
"channel-paste-url": "URL yapıştır",
"channel-paste-url-hint": "Bir Apprise URL'si alanları doldurur",
"channel-resend": "Yeni kod gönder",
"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-service-url": "{service} URL'si",
"channel-service-url-hint": "{service} tarafından verilen URL veya bir Apprise URL'si",
"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 +58,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.",

View File

@@ -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,16 @@
"channel-edit": "编辑渠道",
"channel-email-unavailable": "此服务器未配置电子邮件",
"channel-enabled": "向这里发送通知",
"channel-format": "格式",
"channel-format-discord": "Discord",
"channel-format-json": "RomM JSON",
"channel-format-ntfy": "ntfy",
"channel-field-botname": "机器人名称",
"channel-field-host": "主机",
"channel-field-list-hint": "每输入一项后按回车",
"channel-field-number": "必须是 {min} 到 {max} 之间的数字",
"channel-field-path": "路径",
"channel-field-port": "端口",
"channel-field-schema": "协议",
"channel-field-targets": "目标",
"channel-field-token": "令牌",
"channel-field-verify": "验证 SSL 证书",
"channel-last-error": "最近的错误:{error}",
"channel-last-sent": "最近发送:{when}",
"channel-level-error": "仅错误",
@@ -27,14 +34,23 @@
"channel-min-level": "发送",
"channel-name": "名称",
"channel-new": "新建渠道",
"channel-paste-failed": "无法读取该 URL",
"channel-paste-filled": "已从 URL 读取:{fields}",
"channel-paste-other-service": "该 URL 属于 {service}",
"channel-paste-url": "粘贴 URL",
"channel-paste-url-hint": "Apprise URL 会填写各字段",
"channel-resend": "发送新验证码",
"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-service-url": "{service} URL",
"channel-service-url-hint": "{service} 提供的 URL,或 Apprise URL",
"channel-services-failed": "无法加载 Apprise 服务",
"channel-setup-guide": "如何设置 {service}",
"channel-test": "发送测试",
"channel-test-failed": "测试失败:{error}",
"channel-test-ok": "测试已发送",
@@ -42,14 +58,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": "所有通知都将被移除。",

View File

@@ -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,16 @@
"channel-edit": "編輯管道",
"channel-email-unavailable": "此伺服器未設定電子郵件",
"channel-enabled": "將通知傳送到這裡",
"channel-format": "格式",
"channel-format-discord": "Discord",
"channel-format-json": "RomM JSON",
"channel-format-ntfy": "ntfy",
"channel-field-botname": "機器人名稱",
"channel-field-host": "主機",
"channel-field-list-hint": "每輸入一項後按 Enter",
"channel-field-number": "必須是 {min} 到 {max} 之間的數字",
"channel-field-path": "路徑",
"channel-field-port": "連接埠",
"channel-field-schema": "通訊協定",
"channel-field-targets": "目標",
"channel-field-token": "權杖",
"channel-field-verify": "驗證 SSL 憑證",
"channel-last-error": "最近的錯誤:{error}",
"channel-last-sent": "最近傳送:{when}",
"channel-level-error": "僅錯誤",
@@ -27,14 +34,23 @@
"channel-min-level": "傳送",
"channel-name": "名稱",
"channel-new": "新增管道",
"channel-paste-failed": "無法讀取此 URL",
"channel-paste-filled": "已從 URL 讀取:{fields}",
"channel-paste-other-service": "此 URL 屬於 {service}",
"channel-paste-url": "貼上 URL",
"channel-paste-url-hint": "Apprise URL 會填入各欄位",
"channel-resend": "寄送新驗證碼",
"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-service-url": "{service} URL",
"channel-service-url-hint": "{service} 提供的 URL,或 Apprise URL",
"channel-services-failed": "無法載入 Apprise 服務",
"channel-setup-guide": "如何設定 {service}",
"channel-test": "傳送測試",
"channel-test-failed": "測試失敗:{error}",
"channel-test-ok": "測試已傳送",
@@ -42,14 +58,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": "所有通知都將被移除。",

View File

@@ -1,4 +1,7 @@
import type {
AppriseChannelCreatePayload,
AppriseServiceSchema,
AppriseUrlFieldsSchema,
EmailChannelCreatePayload,
NotificationChannelSchema,
NotificationChannelTestResult,
@@ -7,13 +10,29 @@ import type {
} from "@/__generated__";
import api from "@/services/api";
export type NotificationChannelCreatePayload =
| AppriseChannelCreatePayload
| WebhookChannelCreatePayload
| EmailChannelCreatePayload;
async function getChannels() {
return api.get<NotificationChannelSchema[]>("/notification-channels");
}
async function create(
payload: WebhookChannelCreatePayload | EmailChannelCreatePayload,
) {
async function getAppriseServices() {
return api.get<AppriseServiceSchema[]>(
"/notification-channels/apprise-services",
);
}
async function parseAppriseUrl(url: string) {
return api.post<AppriseUrlFieldsSchema>(
"/notification-channels/apprise-services/parse",
{ url },
);
}
async function create(payload: NotificationChannelCreatePayload) {
return api.post<NotificationChannelSchema>("/notification-channels", payload);
}
@@ -47,6 +66,8 @@ async function resendCode(id: number) {
export default {
getChannels,
getAppriseServices,
parseAppriseUrl,
create,
update,
remove,

View File

@@ -176,6 +176,19 @@ async function onLogout() {
<div class="r-v2-user-menu__group-label">
{{ t("settings.group-account") }}
</div>
<RMenuItem
v-if="canSeeProfile"
:to="{ name: ROUTES.USER_PROFILE, params: { user: user?.id } }"
icon="mdi-account-outline"
:label="t('common.profile')"
@click="open = false"
/>
<RMenuItem
:to="{ name: ROUTES.USER_INTERFACE }"
icon="mdi-palette-outline"
:label="t('common.user-interface')"
@click="open = false"
/>
<RMenuItem
:to="{ name: ROUTES.NOTIFICATIONS }"
icon="mdi-bell-outline"
@@ -190,19 +203,6 @@ async function onLogout() {
/>
</template>
</RMenuItem>
<RMenuItem
v-if="canSeeProfile"
:to="{ name: ROUTES.USER_PROFILE, params: { user: user?.id } }"
icon="mdi-account-outline"
:label="t('common.profile')"
@click="open = false"
/>
<RMenuItem
:to="{ name: ROUTES.USER_INTERFACE }"
icon="mdi-palette-outline"
:label="t('common.user-interface')"
@click="open = false"
/>
</div>
<!-- Library -->

View File

@@ -0,0 +1,101 @@
import { RTooltip } from "@v2/lib";
import { mount } from "@vue/test-utils";
import mitt from "mitt";
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { defineComponent, nextTick } from "vue";
import storeHeartbeat from "@/stores/heartbeat";
import type { Events } from "@/types/emitter";
import AboutDialog from "./AboutDialog.vue";
vi.mock("vue-i18n", () => ({
useI18n: () => ({ t: (key: string) => key }),
}));
// happy-dom has no ResizeObserver that fires, so the test lays the grid out.
const resize = vi.hoisted(() => ({ layout: () => {} }));
vi.mock("@vueuse/core", async (importOriginal) => ({
...(await importOriginal<typeof import("@vueuse/core")>()),
useResizeObserver: (_target: unknown, callback: () => void) => {
resize.layout = callback;
},
}));
async function open() {
const emitter = mitt<Events>();
const wrapper = mount(AboutDialog, {
global: {
provide: { emitter },
stubs: {
RDialog: defineComponent({
props: { modelValue: { type: Boolean, default: false } },
template: `<div v-if="modelValue"><slot name="content" /></div>`,
}),
},
},
});
emitter.emit("showAboutDialog", null);
await nextTick();
return wrapper;
}
function size(wrapper: Awaited<ReturnType<typeof open>>, content: number) {
const value = wrapper.find(".r-v2-about__value").element;
Object.defineProperty(value, "scrollWidth", {
value: content,
configurable: true,
});
Object.defineProperty(value, "clientWidth", {
value: 120,
configurable: true,
});
}
async function layOut(
wrapper: Awaited<ReturnType<typeof open>>,
content: number,
) {
size(wrapper, content);
resize.layout();
await nextTick();
}
describe("AboutDialog", () => {
beforeEach(() => setActivePinia(createPinia()));
// Ready before any hover, as RTooltip decides on the pointer's arrival.
it("shows a value cut off by its tile in a tooltip", async () => {
const wrapper = await open();
await layOut(wrapper, 480);
expect(wrapper.findComponent(RTooltip).props("disabled")).toBe(false);
});
it("measures a value that changes without the grid resizing", async () => {
const wrapper = await open();
await layOut(wrapper, 60);
size(wrapper, 480);
const heartbeat = storeHeartbeat();
heartbeat.value = {
...heartbeat.value,
SYSTEM: {
...heartbeat.value.SYSTEM,
VERSION: "development",
GIT_BRANCH: "claude/a-branch-name-too-long-for-its-tile",
},
};
await nextTick();
expect(wrapper.findComponent(RTooltip).props("disabled")).toBe(false);
});
it("keeps quiet about a value that fits", async () => {
const wrapper = await open();
await layOut(wrapper, 60);
expect(wrapper.findComponent(RTooltip).props("disabled")).toBe(true);
});
});

View File

@@ -2,9 +2,10 @@
// v2 AboutDialog — emitter-driven. Replaces the v1 AboutDialog in the v2
// GlobalDialogs stack so the "About" entry in UserMenu renders the v2 glass
// panel instead of the legacy card.
import { RDialog, RIcon, RImg } from "@v2/lib";
import { RDialog, RIcon, RImg, RTooltip } from "@v2/lib";
import { useResizeObserver } from "@vueuse/core";
import type { Emitter } from "mitt";
import { computed, inject, onBeforeUnmount, ref } from "vue";
import { computed, inject, onBeforeUnmount, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import type { Events } from "@/types/emitter";
import { useVersionDisplay } from "@/v2/composables/useVersionDisplay";
@@ -60,6 +61,21 @@ const links = computed<Link[]>(() => [
href: "https://discord.com/invite/P5HtHnhUDH",
},
]);
// Which tiles cut their value off, and then show it in full. Measured whenever
// the grid lays out or a value changes, as RTooltip decides on the pointer's arrival.
const grid = ref<HTMLElement | null>(null);
const truncated = ref<boolean[]>([]);
function measure() {
truncated.value = Array.from(
grid.value?.querySelectorAll(".r-v2-about__value") ?? [],
(value) => value.scrollWidth > value.clientWidth,
);
}
useResizeObserver(grid, measure);
watch(() => links.value.map((link) => link.value), measure, { flush: "post" });
</script>
<template>
@@ -73,9 +89,9 @@ const links = computed<Link[]>(() => [
<span>{{ t("common.about-romm") }}</span>
</template>
<template #content>
<div class="r-v2-about">
<div ref="grid" class="r-v2-about">
<a
v-for="link in links"
v-for="(link, index) in links"
:key="link.label"
:href="link.href"
target="_blank"
@@ -98,6 +114,11 @@ const links = computed<Link[]>(() => [
<span class="r-v2-about__value">{{ link.value }}</span>
</div>
<RIcon icon="mdi-open-in-new" size="14" class="r-v2-about__chev" />
<RTooltip
activator="parent"
:text="link.value"
:disabled="!truncated[index]"
/>
</a>
</div>
</template>
@@ -107,7 +128,9 @@ const links = computed<Link[]>(() => [
<style scoped>
.r-v2-about {
display: grid;
grid-template-columns: 1fr 1fr;
/* A 0 minimum, so a long value (a branch name) truncates instead of
widening its column past the dialog. */
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
}
@@ -174,6 +197,6 @@ const links = computed<Link[]>(() => [
}
html[data-bp~="xs"] .r-v2-about {
grid-template-columns: 1fr;
grid-template-columns: minmax(0, 1fr);
}
</style>

View File

@@ -0,0 +1,146 @@
<script setup lang="ts">
// AppriseFieldInput: one field of an Apprise service, in the control its type
// calls for.
import { RCheckbox, RComboboxField, RSelect, RTextField } from "@v2/lib";
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import type { AppriseFieldSchema } from "@/__generated__";
import {
type AppriseFieldValue,
NOTIFICATION_CHANNEL_URL_MAX_LENGTH,
appriseFieldLabel,
} from "@/v2/utils/notificationChannels";
import { notBlank } from "@/v2/utils/validation";
const props = defineProps<{
field: AppriseFieldSchema;
// A secret the channel already has, which stays when left empty.
stored: boolean;
// Just filled in from a pasted URL.
highlight: boolean;
}>();
const value = defineModel<AppriseFieldValue>({ required: true });
const removed = defineModel<boolean>("removed", { default: false });
const { t } = useI18n();
const label = computed(() => appriseFieldLabel(props.field, t));
const required = computed(() => props.field.required && !props.stored);
const hint = computed(() =>
props.stored ? t("notifications.channel-secret-keep") : undefined,
);
const isNumber = computed(
() => props.field.type === "int" || props.field.type === "float",
);
function inRange(text: string): true | string {
const { min, max, type } = props.field;
const n = Number(text);
const fits =
text === "" ||
(!Number.isNaN(n) &&
(type === "float" || Number.isInteger(n)) &&
(min === null || n >= min) &&
(max === null || n <= max));
return (
fits ||
t("notifications.channel-field-number", {
min: min ?? "−∞",
max: max ?? "∞",
})
);
}
const rules = computed(() => [
...(required.value ? [notBlank()] : []),
...(isNumber.value ? [inRange] : []),
]);
const listRules = computed(() =>
required.value
? [(items: string[]) => items.length > 0 || t("common.required")]
: [],
);
</script>
<template>
<div
class="r-v2-apprise-field"
:class="{ 'r-v2-apprise-field--filled': highlight }"
>
<RCheckbox
v-if="field.type === 'bool'"
:model-value="value === true"
:label="label"
@update:model-value="value = $event === true"
/>
<RSelect
v-else-if="field.type === 'choice'"
:model-value="value"
:items="field.values ?? []"
:label="label"
prefix-label="stacked"
hide-details
@update:model-value="value = String($event)"
/>
<RComboboxField
v-else-if="field.type === 'list'"
:model-value="Array.isArray(value) ? value : []"
:label="label"
:hint="hint ?? t('notifications.channel-field-list-hint')"
:rules="listRules"
:disabled="removed"
prefix-label="stacked"
no-suggestions
@update:model-value="value = $event"
/>
<RTextField
v-else
:model-value="String(value)"
:label="label"
:type="field.private ? 'password' : isNumber ? 'number' : 'text'"
:rules="rules"
:required="required"
:hint="hint"
:disabled="removed"
:maxlength="NOTIFICATION_CHANNEL_URL_MAX_LENGTH"
:autocomplete="field.private ? 'new-password' : 'off'"
prefix-label="stacked"
@update:model-value="value = String($event ?? '')"
/>
<RCheckbox
v-if="stored && !field.required"
v-model="removed"
:label="t('notifications.channel-secret-remove')"
/>
</div>
</template>
<style scoped>
.r-v2-apprise-field {
display: flex;
flex-direction: column;
gap: var(--r-space-1);
min-width: 0;
border-radius: var(--r-radius-md);
}
.r-v2-apprise-field--filled {
animation: r-v2-apprise-field-filled 1.6s var(--r-motion-ease-out);
}
@keyframes r-v2-apprise-field-filled {
from {
box-shadow: 0 0 0 3px
color-mix(in srgb, var(--r-color-brand-primary) 55%, transparent);
}
to {
box-shadow: 0 0 0 3px transparent;
}
}
@media (prefers-reduced-motion: reduce) {
.r-v2-apprise-field--filled {
animation: none;
}
}
</style>

View File

@@ -0,0 +1,110 @@
<script setup lang="ts">
// AppriseServiceFields: the fields an Apprise service takes, as the backend
// lists them, with its options folded under "Advanced options".
import { RBtn, RCollapsible } from "@v2/lib";
import { computed, ref } from "vue";
import { useI18n } from "vue-i18n";
import type { AppriseFieldSchema, AppriseServiceSchema } from "@/__generated__";
import AppriseFieldInput from "@/v2/components/Notifications/AppriseFieldInput.vue";
import type { AppriseFieldValue } from "@/v2/utils/notificationChannels";
const props = defineProps<{
service: AppriseServiceSchema;
// The secrets the channel already has.
stored: string[];
// The fields a pasted URL just filled in.
highlighted: string[];
}>();
const values = defineModel<Record<string, AppriseFieldValue>>({
required: true,
});
// The stored secrets to drop on save.
const removed = defineModel<string[]>("removed", { default: () => [] });
const { t } = useI18n();
// A service set up from its own URL shows only what that URL lacks.
const basic = computed(() =>
props.service.fields.filter(
(f) => !f.advanced && !props.service.url_fields.includes(f.key),
),
);
const advanced = computed(() => props.service.fields.filter((f) => f.advanced));
const showAdvanced = ref(false);
function set(key: string, value: AppriseFieldValue) {
values.value = { ...values.value, [key]: value };
}
function inputProps(field: AppriseFieldSchema) {
return {
field,
modelValue: values.value[field.key],
stored: props.stored.includes(field.key),
highlight: props.highlighted.includes(field.key),
removed: removed.value.includes(field.key),
};
}
function setRemoved(key: string, drop: boolean) {
removed.value = drop
? [...removed.value, key]
: removed.value.filter((k) => k !== key);
}
</script>
<template>
<div v-if="basic.length > 0" class="r-v2-apprise-fields">
<AppriseFieldInput
v-for="field in basic"
:key="field.key"
v-bind="inputProps(field)"
@update:model-value="set(field.key, $event)"
@update:removed="setRemoved(field.key, $event)"
/>
</div>
<template v-if="advanced.length > 0">
<RBtn
class="r-v2-apprise-fields__toggle"
variant="text"
size="small"
:prepend-icon="showAdvanced ? 'mdi-chevron-down' : 'mdi-chevron-right'"
:aria-expanded="showAdvanced"
@click="showAdvanced = !showAdvanced"
>
{{ t("notifications.channel-advanced") }}
</RBtn>
<RCollapsible v-model="showAdvanced">
<div class="r-v2-apprise-fields r-v2-apprise-fields--inset">
<AppriseFieldInput
v-for="field in advanced"
:key="field.key"
v-bind="inputProps(field)"
@update:model-value="set(field.key, $event)"
@update:removed="setRemoved(field.key, $event)"
/>
</div>
</RCollapsible>
</template>
</template>
<style scoped>
.r-v2-apprise-fields {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
align-items: start;
gap: var(--r-space-3);
}
.r-v2-apprise-fields__toggle {
align-self: flex-start;
}
.r-v2-apprise-fields--inset {
padding: var(--r-space-3);
}
html[data-bp~="xs"] .r-v2-apprise-fields {
grid-template-columns: minmax(0, 1fr);
}
</style>

View File

@@ -1,16 +1,26 @@
import { RCheckbox, 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(),
parseAppriseUrl: vi.fn(),
}));
vi.mock("@/services/api/notificationChannel", () => ({ default: api }));
vi.mock("vue-i18n", () => ({
useI18n: () => ({ t: (key: string) => key }),
useI18n: () => ({ t: (key: string) => key, locale: { value: "en_US" } }),
}));
function channel(
@@ -18,16 +28,28 @@ 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,
stored_secrets: 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 +63,7 @@ async function open(existing: NotificationChannelSchema | null = null) {
},
});
await wrapper.setProps({ modelValue: true });
await nextTick();
await flushPromises();
return wrapper;
}
@@ -51,6 +73,18 @@ function input(wrapper: Wrapper, selector: string) {
return wrapper.find<HTMLInputElement>(`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<HTMLInputElement>("input");
}
async function save(wrapper: Wrapper) {
await wrapper
.findAll("button")
@@ -63,17 +97,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 +115,6 @@ describe("NotificationChannelDialog", () => {
type: "webhook",
name: "Hook",
url: "https://hooks.example.com/romm",
format: "json",
secret: "s3cret",
min_level: "info",
topics: null,
@@ -95,16 +128,287 @@ 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 nextTick();
await save(wrapper);
expect(api.create).toHaveBeenCalledWith({
type: "apprise",
name: "Phone",
service: "ntfy",
fields: {
schema: "ntfys",
host: "ntfy.example.com",
targets: ["romm"],
image: true,
priority: "default",
},
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.find(".r-combobox-field").text()).toContain(
"common.required",
);
wrapper.unmount();
});
const ntfyChannel = () =>
channel({
type: "apprise",
service: "ntfy",
service_name: "ntfy",
fields: { host: "ntfy.example.com", targets: ["romm"] },
stored_secrets: ["token"],
has_secret: false,
});
async function paste(wrapper: Wrapper, url: string) {
await textField(wrapper, "notifications.channel-paste-url")?.setValue(url);
// Past the field's debounce.
await new Promise((resolve) => setTimeout(resolve, 450));
await flushPromises();
}
it("fills the fields in as soon as a URL is pasted", async () => {
api.create.mockResolvedValue({ data: channel({ type: "apprise" }) });
api.parseAppriseUrl.mockResolvedValue({
data: {
service: "ntfy",
fields: { host: "ntfy.example.com", port: 8080, targets: ["romm"] },
},
});
const wrapper = await open(null, { admin: true });
await pick(wrapper, "apprise:ntfy");
await wrapper.findAll("input.r-text-field__input")[0].setValue("Phone");
await paste(wrapper, "ntfys://ntfy.example.com:8080/romm");
const pasted = textField(wrapper, "notifications.channel-paste-url");
expect(pasted?.element.value).toBe("ntfys://ntfy.example.com:8080/romm");
expect(wrapper.text()).toContain("notifications.channel-paste-filled");
expect(wrapper.findAll(".r-v2-apprise-field--filled")).toHaveLength(3);
await save(wrapper);
expect(api.parseAppriseUrl).toHaveBeenCalledWith(
"ntfys://ntfy.example.com:8080/romm",
);
expect(api.create.mock.calls[0][0].fields).toMatchObject({
host: "ntfy.example.com",
port: 8080,
targets: ["romm"],
});
wrapper.unmount();
});
it("says why it can't read a pasted URL", async () => {
api.parseAppriseUrl.mockRejectedValue({
isAxiosError: true,
response: { data: { detail: "Apprise can't read this URL" } },
});
const wrapper = await open(null, { admin: true });
await pick(wrapper, "apprise:ntfy");
await paste(wrapper, "nowhere://romm");
expect(wrapper.text()).toContain("Apprise can't read this URL");
wrapper.unmount();
});
it("moves a new channel to the service a pasted URL is for", async () => {
const discord = makeAppriseService({
id: "discord",
name: "Discord",
fields: [],
});
api.getAppriseServices.mockResolvedValue({
data: [makeAppriseService(), discord],
});
api.parseAppriseUrl.mockResolvedValue({
data: { service: "discord", fields: {} },
});
const wrapper = await open(null, { admin: true });
await pick(wrapper, "apprise:ntfy");
await paste(wrapper, "https://discord.com/api/webhooks/1/token");
expect(wrapper.findAllComponents(RSelect)[0].props("modelValue")).toBe(
"apprise:discord",
);
wrapper.unmount();
});
it("keeps an edited channel on its service whatever URL is pasted", async () => {
api.parseAppriseUrl.mockResolvedValue({
data: { service: "discord", fields: {} },
});
api.getAppriseServices.mockResolvedValue({
data: [
makeAppriseService(),
makeAppriseService({ id: "discord", name: "Discord", fields: [] }),
],
});
const wrapper = await open(ntfyChannel(), { admin: true });
await paste(wrapper, "https://discord.com/api/webhooks/1/token");
expect(wrapper.text()).toContain(
"notifications.channel-paste-other-service",
);
wrapper.unmount();
});
const discord = () => {
const secret = {
type: "string" as const,
required: true,
private: true,
advanced: false,
default: null,
values: null,
min: null,
max: null,
};
return makeAppriseService({
id: "discord",
name: "Discord",
url_fields: ["webhook_id", "webhook_token"],
fields: [
{
...secret,
key: "botname",
label: "Bot Name",
required: false,
private: false,
},
{ ...secret, key: "webhook_id", label: "Webhook ID" },
{ ...secret, key: "webhook_token", label: "Webhook Token" },
],
});
};
it("sets a service with its own URL up from that URL alone", async () => {
api.getAppriseServices.mockResolvedValue({
data: [makeAppriseService(), discord()],
});
api.parseAppriseUrl.mockResolvedValue({
data: {
service: "discord",
fields: { webhook_id: "1", webhook_token: "t" },
},
});
api.create.mockResolvedValue({ data: channel({ type: "apprise" }) });
const wrapper = await open(null, { admin: true });
await pick(wrapper, "apprise:discord");
expect(textField(wrapper, "Webhook ID")).toBeUndefined();
await wrapper.findAll("input.r-text-field__input")[0].setValue("Alerts");
await textField(wrapper, "notifications.channel-field-botname")?.setValue(
"RomM",
);
// Saved before the pause that would read it.
await textField(wrapper, "notifications.channel-service-url")?.setValue(
"https://discord.com/api/webhooks/1/t",
);
await save(wrapper);
expect(api.parseAppriseUrl).toHaveBeenCalledWith(
"https://discord.com/api/webhooks/1/t",
);
expect(api.create.mock.calls[0][0]).toMatchObject({
service: "discord",
fields: { botname: "RomM", webhook_id: "1", webhook_token: "t" },
});
wrapper.unmount();
});
it("saves what a URL read during the save's wait fills in", async () => {
api.getAppriseServices.mockResolvedValue({ data: [discord()] });
let answer: (value: unknown) => void = () => {};
api.parseAppriseUrl.mockImplementation(
() => new Promise((resolve) => (answer = resolve)),
);
api.create.mockResolvedValue({ data: channel({ type: "apprise" }) });
const wrapper = await open(null, { admin: true });
await pick(wrapper, "apprise:discord");
await wrapper.findAll("input.r-text-field__input")[0].setValue("Alerts");
await textField(wrapper, "notifications.channel-service-url")?.setValue(
"https://discord.com/api/webhooks/1/t",
);
await save(wrapper);
// The field's own read comes due while the save waits on its read.
await new Promise((resolve) => setTimeout(resolve, 450));
answer({
data: {
service: "discord",
fields: { webhook_id: "1", webhook_token: "t" },
},
});
await flushPromises();
expect(api.parseAppriseUrl).toHaveBeenCalledTimes(1);
expect(api.create.mock.calls[0][0].fields).toMatchObject({
webhook_id: "1",
webhook_token: "t",
});
wrapper.unmount();
});
it("needs the URL of a service set up from one", async () => {
api.getAppriseServices.mockResolvedValue({ data: [discord()] });
const wrapper = await open(null, { admin: true });
await pick(wrapper, "apprise:discord");
await wrapper.findAll("input.r-text-field__input")[0].setValue("Alerts");
await save(wrapper);
expect(api.create).not.toHaveBeenCalled();
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,11 +419,53 @@ 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(ntfyChannel(), { admin: true });
expect(
textField(wrapper, "notifications.channel-field-token")?.attributes(
"type",
),
).toBe("password");
await save(wrapper);
// The token is left out, so the channel keeps it.
expect(api.update).toHaveBeenCalledWith(4, {
name: "Hook",
min_level: "info",
topics: ["scans"],
fields: {
schema: "ntfys",
host: "ntfy.example.com",
targets: ["romm"],
image: true,
priority: "default",
},
});
wrapper.unmount();
});
it("removes a stored Apprise secret when asked to", async () => {
api.update.mockResolvedValue({ data: channel({ type: "apprise" }) });
const wrapper = await open(ntfyChannel(), { admin: true });
wrapper
.findAllComponents(RCheckbox)
.find(
(box) => box.props("label") === "notifications.channel-secret-remove",
)
?.vm.$emit("update:modelValue", true);
await save(wrapper);
expect(api.update.mock.calls[0][1].fields).toMatchObject({ token: "" });
wrapper.unmount();
});
it("drops the secret when asked to", async () => {
api.update.mockResolvedValue({ data: channel({ has_secret: false }) });
const wrapper = await open(channel());
@@ -136,7 +482,6 @@ describe("NotificationChannelDialog", () => {
const wrapper = await open(
channel({
type: "email",
format: null,
target: "a@example.com",
has_secret: false,
}),

View File

@@ -1,6 +1,6 @@
<script setup lang="ts">
// NotificationChannelDialog: adds a channel, or edits one, where a blank URL
// or secret keeps what the channel already has.
// NotificationChannelDialog: adds or edits a channel, where a blank URL or secret
// keeps the current one. Admins also get every Apprise service and its fields.
import {
RAlert,
RBtn,
@@ -11,29 +11,38 @@ import {
RSelect,
RTextField,
} from "@v2/lib";
import { watchDebounced } from "@vueuse/core";
import { computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import type {
AppriseServiceSchema,
NotificationChannelMinLevel,
NotificationChannelSchema,
NotificationChannelType,
NotificationChannelUpdatePayload,
NotificationTopic,
WebhookFormat,
} from "@/__generated__";
import notificationChannelApi from "@/services/api/notificationChannel";
import notificationChannelApi, {
type NotificationChannelCreatePayload,
} from "@/services/api/notificationChannel";
import storeAuth from "@/stores/auth";
import storeHeartbeat from "@/stores/heartbeat";
import AppriseServiceFields from "@/v2/components/Notifications/AppriseServiceFields.vue";
import { useCan } from "@/v2/composables/useCan";
import { errorMessage } from "@/v2/utils/errorMessage";
import { joinNames } from "@/v2/utils/lists";
import {
type AppriseFieldValue,
CHANNEL_ICONS,
CHANNEL_LEVELS,
CHANNEL_TOPICS,
EMAIL_ICON,
FORMAT_ICONS,
NOTIFICATION_CHANNEL_ADDRESS_MAX_LENGTH,
NOTIFICATION_CHANNEL_NAME_MAX_LENGTH,
NOTIFICATION_CHANNEL_SECRET_MAX_LENGTH,
NOTIFICATION_CHANNEL_URL_MAX_LENGTH,
appriseFieldLabel,
appriseFieldsPayload,
initialAppriseValues,
} from "@/v2/utils/notificationChannels";
import { email as emailRule, notBlank } from "@/v2/utils/validation";
@@ -43,13 +52,16 @@ const emit = defineEmits<{
saved: [channel: NotificationChannelSchema];
}>();
const { t } = useI18n();
// The picker holds "webhook", "email", or an Apprise service as "apprise:<id>".
const APPRISE_PREFIX = "apprise:";
const { t, locale } = useI18n();
const auth = storeAuth();
const heartbeat = storeHeartbeat();
const isAdmin = useCan("app.admin");
const formRef = ref<InstanceType<typeof RForm> | null>(null);
const type = ref<NotificationChannelType>("webhook");
const format = ref<WebhookFormat>("json");
const kind = ref("webhook");
const name = ref("");
const url = ref("");
const secret = ref("");
@@ -57,6 +69,15 @@ const removeSecret = ref(false);
const address = ref("");
const minLevel = ref<NotificationChannelMinLevel>("info");
const topics = ref<NotificationTopic[]>([]);
const services = ref<AppriseServiceSchema[] | null>(null);
const loadingServices = ref(false);
const appriseValues = ref<Record<string, AppriseFieldValue>>({});
const removedSecrets = ref<string[]>([]);
const pastedUrl = ref("");
const pasteError = ref<string | null>(null);
const filling = ref(false);
// The fields the last pasted URL filled in, so the form can show it did.
const filledFields = ref<string[]>([]);
const saving = ref(false);
const error = ref<string | null>(null);
@@ -65,6 +86,17 @@ const emailEnabled = computed(
() => heartbeat.value.NOTIFICATIONS.EMAIL_ENABLED,
);
const keepsSecret = computed(() => !!props.channel?.has_secret);
const storedSecrets = computed(() => props.channel?.stored_secrets ?? []);
const type = computed<NotificationChannelType>(() =>
kind.value.startsWith(APPRISE_PREFIX)
? "apprise"
: (kind.value as NotificationChannelType),
);
const service = computed(() => {
if (type.value !== "apprise") return null;
const id = kind.value.slice(APPRISE_PREFIX.length);
return services.value?.find((s) => s.id === id) ?? null;
});
const typeItems = computed(() => [
{ title: t("notifications.channel-type-webhook"), value: "webhook" },
@@ -73,14 +105,11 @@ const typeItems = computed(() => [
value: "email",
disabled: !emailEnabled.value,
},
]);
const formatItems = computed(() =>
(Object.keys(FORMAT_ICONS) as WebhookFormat[]).map((value) => ({
title: t(`notifications.channel-format-${value}`),
value,
...(services.value ?? []).map((s) => ({
title: s.name,
value: `${APPRISE_PREFIX}${s.id}`,
})),
);
]);
const levelItems = computed(() =>
CHANNEL_LEVELS.map((value) => ({
@@ -96,12 +125,6 @@ const topicItems = computed(() =>
})),
);
const URL_PLACEHOLDERS: Record<WebhookFormat, string> = {
json: "https://example.com/hooks/romm",
discord: "https://discord.com/api/webhooks/…",
ntfy: "https://ntfy.sh/your-topic",
};
const isHttpUrl = (value: string) => /^https?:\/\/\S+$/i.test(value.trim());
const nameRules = [notBlank()];
const urlRules = computed(() => [
@@ -112,11 +135,63 @@ const urlRules = computed(() => [
]);
const addressRules = [notBlank(), emailRule];
async function loadServices() {
if (!isAdmin.value || services.value || loadingServices.value) return;
if (props.channel && props.channel.type !== "apprise") return;
loadingServices.value = true;
try {
const { data } = await notificationChannelApi.getAppriseServices();
services.value = data;
// An Apprise channel being edited gets its fields once its service is known.
resetAppriseValues();
} catch (err) {
console.error("Could not load the Apprise services:", err);
error.value = errorMessage(err, t("notifications.channel-services-failed"));
} finally {
loadingServices.value = false;
}
}
// A service's fields start from its defaults, or from the channel being edited.
function resetAppriseValues() {
appriseValues.value = service.value
? initialAppriseValues(service.value, props.channel?.fields ?? null)
: {};
removedSecrets.value = [];
}
// A pasted URL, the service's own (a Discord webhook's) or an Apprise one, fills
// the form in; only the latest paste counts.
let pasteRequest = 0;
// The read in flight, which the field and a save share rather than race.
let reading: { url: string; done: Promise<void> } | null = null;
const parsedUrl = ref("");
const URL_LIKE = /^[a-z][\w+.-]*:\/\/\S+$/i;
function clearPaste() {
pasteRequest++;
reading = null;
pastedUrl.value = "";
parsedUrl.value = "";
pasteError.value = null;
filling.value = false;
filledFields.value = [];
}
// Picking another service by hand starts its form afresh.
function pickKind(value: string) {
kind.value = value;
resetAppriseValues();
clearPaste();
}
watch(show, (open) => {
if (!open) return;
const channel = props.channel;
type.value = channel?.type ?? "webhook";
format.value = channel?.format ?? "json";
kind.value =
channel?.type === "apprise"
? `${APPRISE_PREFIX}${channel.service}`
: (channel?.type ?? "webhook");
name.value = channel?.name ?? "";
url.value = "";
secret.value = "";
@@ -126,53 +201,178 @@ watch(show, (open) => {
minLevel.value = channel?.min_level ?? "info";
topics.value = channel?.topics ? [...channel.topics] : [];
error.value = null;
resetAppriseValues();
clearPaste();
formRef.value?.resetValidation();
void loadServices();
});
function webhookChanges(): NotificationChannelUpdatePayload {
const changes: NotificationChannelUpdatePayload = { format: format.value };
const nativeUrl = computed(() => !!service.value?.url_fields.length);
const pasteLabel = computed(() =>
nativeUrl.value && service.value
? t("notifications.channel-service-url", { service: service.value.name })
: t("notifications.channel-paste-url"),
);
const pasteHint = computed(() => {
if (!service.value) return undefined;
const filled = service.value.fields.filter((f) =>
filledFields.value.includes(f.key),
);
if (filled.length > 0) {
const names = filled.map((field) => appriseFieldLabel(field, t));
return t("notifications.channel-paste-filled", {
fields: joinNames(names, locale.value),
});
}
if (!nativeUrl.value) return t("notifications.channel-paste-url-hint");
return editing.value
? t("notifications.channel-secret-keep")
: t("notifications.channel-service-url-hint", {
service: service.value.name,
});
});
// A service set up from its own URL needs one when it's added.
const pasteRules = computed(() =>
nativeUrl.value && !editing.value ? [notBlank()] : [],
);
function fillFromUrl(url: string): Promise<void> {
if (reading?.url !== url) reading = { url, done: readUrl(url) };
return reading.done;
}
async function readUrl(url: string) {
const request = ++pasteRequest;
filling.value = true;
pasteError.value = null;
filledFields.value = [];
try {
const { data } = await notificationChannelApi.parseAppriseUrl(url);
if (request !== pasteRequest) return;
const found = services.value?.find((s) => s.id === data.service);
if (!found) {
pasteError.value = t("notifications.channel-paste-failed");
return;
}
if (editing.value && found.id !== service.value?.id) {
pasteError.value = t("notifications.channel-paste-other-service", {
service: found.name,
});
return;
}
// What's typed beside a service's own URL (a Discord bot name) stays.
const typed =
found.id === service.value?.id && found.url_fields.length > 0
? Object.fromEntries(
Object.entries(appriseValues.value).filter(
([key]) => !found.url_fields.includes(key),
),
)
: {};
kind.value = `${APPRISE_PREFIX}${found.id}`;
appriseValues.value = initialAppriseValues(found, {
...typed,
...data.fields,
});
removedSecrets.value = [];
filledFields.value = Object.keys(data.fields);
parsedUrl.value = url;
} catch (err) {
if (request !== pasteRequest) return;
// A save tries it again.
reading = null;
pasteError.value = errorMessage(
err,
t("notifications.channel-paste-failed"),
);
} finally {
if (request === pasteRequest) filling.value = false;
}
}
watchDebounced(
pastedUrl,
(url) => {
const pasted = url.trim();
if (!pasted) clearPaste();
else if (URL_LIKE.test(pasted) && pasted !== parsedUrl.value) {
void fillFromUrl(pasted);
}
},
{ debounce: 400 },
);
function targetChanges(): NotificationChannelUpdatePayload {
switch (type.value) {
case "email":
return { address: address.value.trim() };
case "apprise":
return service.value
? {
fields: appriseFieldsPayload(
service.value,
appriseValues.value,
removedSecrets.value,
),
}
: {};
}
const changes: NotificationChannelUpdatePayload = {};
if (url.value.trim()) changes.url = url.value.trim();
if (removeSecret.value) changes.secret = "";
else if (secret.value) changes.secret = secret.value;
return changes;
}
async function request() {
const filters = {
function commonFields() {
return {
name: name.value.trim(),
min_level: minLevel.value,
topics: topics.value.length > 0 ? topics.value : null,
};
if (props.channel) {
return notificationChannelApi.update(props.channel.id, {
name: name.value.trim(),
...filters,
...(props.channel.type === "webhook"
? webhookChanges()
: { address: address.value.trim() }),
});
}
function createPayload(): NotificationChannelCreatePayload {
const fields = commonFields();
if (type.value === "email") {
return { type: "email", address: address.value.trim(), ...fields };
}
return notificationChannelApi.create(
type.value === "email"
? {
type: "email",
name: name.value.trim(),
address: address.value.trim(),
...filters,
}
: {
type: "webhook",
name: name.value.trim(),
url: url.value.trim(),
format: format.value,
secret: format.value === "discord" ? null : secret.value || null,
...filters,
},
);
if (service.value) {
return {
type: "apprise",
service: service.value.id,
fields: appriseFieldsPayload(service.value, appriseValues.value),
...fields,
};
}
return {
type: "webhook",
url: url.value.trim(),
secret: secret.value || null,
...fields,
};
}
async function request() {
if (!props.channel) return notificationChannelApi.create(createPayload());
return notificationChannelApi.update(props.channel.id, {
...commonFields(),
...targetChanges(),
});
}
async function save() {
// A URL typed without a pause to read it is read now, and saved only once read.
const pasted = pastedUrl.value.trim();
if (service.value && pasted && pasted !== parsedUrl.value) {
await fillFromUrl(pasted);
if (parsedUrl.value !== pasted) return;
}
const result = await formRef.value?.validate();
if (!result?.valid) return;
if (!result?.valid || pasteError.value) return;
saving.value = true;
error.value = null;
try {
@@ -211,60 +411,50 @@ async function save() {
<RForm ref="formRef" class="r-v2-channel-dialog" @submit="save">
<RAlert v-if="error" type="error" density="compact" :text="error" />
<div class="r-v2-channel-dialog__pair">
<div :class="{ 'r-v2-channel-dialog__pair': !editing }">
<RSelect
v-if="!editing"
v-model="type"
:model-value="kind"
:items="typeItems"
:prepend-inner-icon="
type === 'email' ? EMAIL_ICON : FORMAT_ICONS.json
"
:prepend-inner-icon="CHANNEL_ICONS[type]"
:loading="loadingServices"
:searchable="isAdmin"
:search-placeholder="t('notifications.channel-search-services')"
:hint="
emailEnabled
? undefined
: t('notifications.channel-email-unavailable')
"
prefix-label="stacked"
@update:model-value="pickKind(String($event))"
>
<template #prefix-label>
<RIcon icon="mdi-shape-outline" size="14" />
{{ t("notifications.channel-type") }}
</template>
</RSelect>
<RSelect
v-if="type === 'webhook'"
v-model="format"
:items="formatItems"
:prepend-inner-icon="FORMAT_ICONS[format]"
<RTextField
v-model="name"
:rules="nameRules"
:maxlength="NOTIFICATION_CHANNEL_NAME_MAX_LENGTH"
prefix-label="stacked"
hide-details
required
>
<template #prefix-label>
<RIcon icon="mdi-code-json" size="14" />
{{ t("notifications.channel-format") }}
<RIcon icon="mdi-tag-outline" size="14" />
{{ t("notifications.channel-name") }}
</template>
</RSelect>
</RTextField>
</div>
<RTextField
v-model="name"
:rules="nameRules"
:maxlength="NOTIFICATION_CHANNEL_NAME_MAX_LENGTH"
prefix-label="stacked"
required
>
<template #prefix-label>
<RIcon icon="mdi-tag-outline" size="14" />
{{ t("notifications.channel-name") }}
</template>
</RTextField>
<template v-if="type === 'webhook'">
<RTextField
v-model="url"
:rules="urlRules"
:maxlength="NOTIFICATION_CHANNEL_URL_MAX_LENGTH"
:placeholder="editing ? channel?.target : URL_PLACEHOLDERS[format]"
:placeholder="
editing ? channel?.target : 'https://example.com/hooks/romm'
"
:hint="editing ? t('notifications.channel-url-keep') : undefined"
autocomplete="off"
prefix-label="stacked"
@@ -276,29 +466,69 @@ async function save() {
{{ t("notifications.channel-url") }}
</template>
</RTextField>
<RTextField
v-model="secret"
type="password"
:maxlength="NOTIFICATION_CHANNEL_SECRET_MAX_LENGTH"
:disabled="removeSecret"
:hint="
keepsSecret ? t('notifications.channel-secret-keep') : undefined
"
autocomplete="new-password"
prefix-label="stacked"
>
<template #prefix-label>
<RIcon icon="mdi-key-outline" size="14" />
{{ t("notifications.channel-secret") }}
</template>
</RTextField>
<RCheckbox
v-if="keepsSecret"
v-model="removeSecret"
:label="t('notifications.channel-secret-remove')"
/>
</template>
<template v-if="format !== 'discord'">
<template v-else-if="type === 'apprise'">
<template v-if="service">
<RTextField
v-model="secret"
type="password"
:maxlength="NOTIFICATION_CHANNEL_SECRET_MAX_LENGTH"
:disabled="removeSecret"
:hint="
keepsSecret ? t('notifications.channel-secret-keep') : undefined
"
autocomplete="new-password"
v-model="pastedUrl"
:label="pasteLabel"
:hint="pasteHint"
:placeholder="nativeUrl && editing ? channel?.target : undefined"
:rules="pasteRules"
:required="nativeUrl && !editing"
:error-messages="pasteError ?? undefined"
:maxlength="NOTIFICATION_CHANNEL_URL_MAX_LENGTH"
:loading="filling"
autocomplete="off"
prefix-label="stacked"
>
<template #prefix-label>
<RIcon icon="mdi-key-outline" size="14" />
{{ t(`notifications.channel-secret-${format}`) }}
</template>
</RTextField>
<RCheckbox
v-if="keepsSecret"
v-model="removeSecret"
:label="t('notifications.channel-secret-remove')"
mono
@keydown.enter.prevent.stop
/>
<AppriseServiceFields
v-model="appriseValues"
v-model:removed="removedSecrets"
:service="service"
:stored="storedSecrets"
:highlighted="filledFields"
/>
<RBtn
v-if="service.setup_url"
class="r-v2-channel-dialog__guide"
variant="text"
size="small"
prepend-icon="mdi-open-in-new"
:href="service.setup_url"
target="_blank"
rel="noopener noreferrer"
>
{{
t("notifications.channel-setup-guide", {
service: service.name,
})
}}
</RBtn>
</template>
</template>
@@ -314,7 +544,7 @@ async function save() {
required
>
<template #prefix-label>
<RIcon :icon="EMAIL_ICON" size="14" />
<RIcon :icon="CHANNEL_ICONS.email" size="14" />
{{ t("notifications.channel-address") }}
</template>
</RTextField>
@@ -380,4 +610,8 @@ async function save() {
html[data-bp~="xs"] .r-v2-channel-dialog__pair {
grid-template-columns: minmax(0, 1fr);
}
.r-v2-channel-dialog__guide {
align-self: flex-start;
}
</style>

View File

@@ -60,17 +60,18 @@ describe("NotificationChannelsSection", () => {
expect(wrapper.text()).toContain("notifications.channels-empty");
});
it("lists each channel with its filters and last error", async () => {
it("lists each channel with its service, filters and last error", async () => {
const wrapper = await mountWith([
channel({
min_level: "warning",
topics: ["scans", "tasks"],
last_error: "discord.com answered 404",
last_error: "Failed to send Discord notification: error=404.",
}),
]);
const text = wrapper.find(".r-v2-channel").text();
expect(text).toContain("https://discord.com/…oken");
expect(wrapper.find(".r-v2-channel .r-tag").text()).toBe("Discord");
expect(text).toContain("discord://1...0/a...p/");
expect(text).toContain(
"notifications.channel-level-warning · notifications.topic-scans, notifications.topic-tasks",
);
@@ -80,7 +81,7 @@ describe("NotificationChannelsSection", () => {
it("says a code went out only for an address new to the channel", async () => {
const waiting = channel({
type: "email",
format: null,
service: null,
target: "a@example.com",
confirmed: false,
});
@@ -164,7 +165,7 @@ describe("NotificationChannelsSection", () => {
data: channel({ type: "email", confirmed: true }),
});
const wrapper = await mountWith([
channel({ type: "email", format: null, confirmed: false }),
channel({ type: "email", service: null, confirmed: false }),
]);
await wrapper.find(".r-v2-channel__code input").setValue(" 123456 ");

View File

@@ -1,6 +1,6 @@
<script setup lang="ts">
// NotificationChannelsSection: the user's webhooks and email addresses, each
// forwarding the notifications its filters let through.
// NotificationChannelsSection: the user's channels (Apprise services, webhooks
// and email addresses), each forwarding the notifications its filters let through.
import {
RAvatar,
RBtn,
@@ -8,6 +8,7 @@ import {
RIcon,
RSkeletonBlock,
RSwitch,
RTag,
RTextField,
} from "@v2/lib";
import { onMounted, reactive, ref } from "vue";
@@ -22,8 +23,8 @@ import { useIsAlive } from "@/v2/composables/useIsAlive";
import { useSnackbar } from "@/v2/composables/useSnackbar";
import { errorMessage } from "@/v2/utils/errorMessage";
import {
CHANNEL_ICONS,
NOTIFICATION_CHANNEL_CODE_MAX_LENGTH,
channelIcon,
} from "@/v2/utils/notificationChannels";
const { t } = useI18n();
@@ -241,13 +242,20 @@ async function remove(channel: NotificationChannelSchema) {
>
<div class="r-v2-channel__main">
<RAvatar
:icon="channelIcon(channel)"
:icon="CHANNEL_ICONS[channel.type]"
variant="translucent"
size="36"
class="r-v2-channel__icon"
/>
<span class="r-v2-channel__text">
<span class="r-v2-channel__name">{{ channel.name }}</span>
<span class="r-v2-channel__heading">
<span class="r-v2-channel__name">{{ channel.name }}</span>
<RTag
v-if="channel.service_name"
size="x-small"
:text="channel.service_name"
/>
</span>
<span class="r-v2-channel__target">{{ channel.target }}</span>
<span class="r-v2-channel__meta">
{{ filtersLabel(channel) }}
@@ -419,6 +427,13 @@ async function remove(channel: NotificationChannelSchema) {
gap: 2px;
}
.r-v2-channel__heading {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--r-space-2);
}
.r-v2-channel__name {
font-size: var(--r-font-size-md);
font-weight: var(--r-font-weight-semibold);

View File

@@ -4,7 +4,7 @@
//
// Groups mirror the v2 user-menu IA so the dropdown and the in-page
// navigator share the same mental model:
// • Account: notifications, profile + UI prefs
// • Account: profile, UI prefs, notifications
// • Library: folder mappings, providers, paired devices
// • System: admin + server stats
// • Tools: jukebox, controller debug (developer-leaning, kept here so
@@ -56,13 +56,6 @@ const groups = computed<Group[]>(() => {
key: "account",
label: t("settings.group-account"),
entries: [
{
icon: "mdi-bell-outline",
label: t("notifications.notifications"),
to: { name: ROUTES.NOTIFICATIONS },
visible: true,
count: unreadCount.value,
},
{
icon: "mdi-account-outline",
label: t("common.profile"),
@@ -78,6 +71,13 @@ const groups = computed<Group[]>(() => {
to: { name: ROUTES.USER_INTERFACE },
visible: true,
},
{
icon: "mdi-bell-outline",
label: t("notifications.notifications"),
to: { name: ROUTES.NOTIFICATIONS },
visible: true,
count: unreadCount.value,
},
],
},
{

View File

@@ -1,4 +1,6 @@
import type { Meta, StoryObj } from "@storybook/vue3-vite";
import { RBtn, RForm } from "@v2/lib";
import { expect, userEvent } from "storybook/test";
import { ref } from "vue";
import RComboboxField from "./RComboboxField.vue";
@@ -149,6 +151,54 @@ export const WithError: Story = {
}),
};
// ── Rules, checked through an enclosing RForm ─────────────────
export const Required: Story = {
name: "Required (rules in a form)",
render: () => ({
components: { RComboboxField, RForm, RBtn },
setup() {
const value = ref<string[]>([]);
const formRef = ref<{ validate: () => Promise<unknown> } | null>(null);
const rules = [
(items: string[]) => items.length > 0 || "Add at least one tag.",
];
return { value, formRef, rules };
},
template: `
<RForm ref="formRef" style="width:320px;padding:24px;display:flex;flex-direction:column;gap:12px">
<RComboboxField
v-model="value"
label="Tags"
prefix-label="stacked"
:rules="rules"
no-suggestions
/>
<RBtn @click="formRef?.validate()">Validate</RBtn>
</RForm>
`,
}),
play: async ({ canvasElement, step }) => {
const input = canvasElement.querySelector(
".r-combobox-field input",
) as HTMLInputElement;
const validate = canvasElement.querySelector("button") as HTMLElement;
await step("an empty list fails", async () => {
await userEvent.click(validate);
await expect(canvasElement.textContent).toContain(
"Add at least one tag.",
);
});
await step("a committed chip clears the error", async () => {
await userEvent.type(input, "rpg{enter}");
await expect(canvasElement.textContent).not.toContain(
"Add at least one tag.",
);
});
},
};
// ── Disabled ─────────────────────────────────────────────────
export const Disabled: Story = {

View File

@@ -40,9 +40,12 @@ import {
import { useChromeLabels } from "@/v2/lib/a11y/chromeLabels";
import RIcon from "@/v2/lib/primitives/RIcon/RIcon.vue";
import RTag from "@/v2/lib/primitives/RTag/RTag.vue";
import { useRFormRegistration } from "../RForm/context";
defineOptions({ inheritAttrs: false });
type Rule = (value: string[]) => true | string;
interface Props {
modelValue?: string[];
/** Optional suggestion list. Typed values that don't match are still
@@ -58,6 +61,9 @@ interface Props {
hideDetails?: boolean;
hint?: string;
errorMessages?: string | string[];
/** Checked against the committed chips, like RSelect's rules; the field
* reports to an enclosing RForm. */
rules?: Rule[];
disabled?: boolean;
/** Render an X button on each chip to remove it (default true). */
closableChips?: boolean;
@@ -80,6 +86,7 @@ const props = withDefaults(defineProps<Props>(), {
hideDetails: false,
hint: undefined,
errorMessages: undefined,
rules: () => [],
disabled: false,
closableChips: true,
noSuggestions: false,
@@ -308,12 +315,49 @@ const showClear = computed(
(chips.value.length > 0 || query.value.length > 0),
);
const errorList = computed<string[]>(() => {
if (!props.errorMessages) return [];
return Array.isArray(props.errorMessages)
? props.errorMessages
: [props.errorMessages];
// ── Validation (mirrors RSelect) ────────────────────────────────
const dirty = ref(false);
const internalErrors = ref<string[]>([]);
function runRules() {
const failed = props.rules
.map((rule) => rule(props.modelValue))
.find((result) => result !== true);
internalErrors.value = failed ? [failed] : [];
}
function validate(): boolean {
dirty.value = true;
runRules();
return internalErrors.value.length === 0;
}
function reset() {
dirty.value = false;
internalErrors.value = [];
}
defineExpose({ validate, reset });
useRFormRegistration({
validate,
reset,
el: () => inputRef.value,
validity: () => !hasError.value,
});
watch(
() => props.modelValue,
() => {
if (dirty.value) runRules();
},
);
const errorList = computed<string[]>(() => [
...(Array.isArray(props.errorMessages)
? props.errorMessages
: props.errorMessages
? [props.errorMessages]
: []),
...internalErrors.value,
]);
const hasError = computed(() => errorList.value.length > 0);
const showDetails = computed(
() => !props.hideDetails && (hasError.value || !!props.hint),

View File

@@ -1,17 +1,23 @@
import type { NotificationChannelSchema } from "@/__generated__";
import type {
AppriseServiceSchema,
NotificationChannelSchema,
} from "@/__generated__";
export function makeChannel(
overrides: Partial<NotificationChannelSchema> = {},
): NotificationChannelSchema {
return {
id: 1,
type: "webhook",
type: "apprise",
name: "Discord",
enabled: true,
min_level: "info",
topics: null,
target: "https://discord.com/…oken",
format: "discord",
target: "discord://1...0/a...p/",
service: "discord",
service_name: "Discord",
fields: {},
stored_secrets: ["webhook_id", "webhook_token"],
has_secret: false,
confirmed: true,
last_delivered_at: null,
@@ -21,3 +27,75 @@ export function makeChannel(
...overrides,
};
}
export function makeAppriseService(
overrides: Partial<AppriseServiceSchema> = {},
): AppriseServiceSchema {
const field = {
required: false,
private: false,
advanced: false,
default: null,
values: null,
min: null,
max: null,
};
return {
id: "ntfy",
name: "ntfy",
setup_url: "https://github.com/caronc/apprise/wiki/Notify_ntfy",
url_fields: [],
fields: [
{
...field,
key: "schema",
label: "Schema",
type: "choice",
required: true,
default: "ntfys",
values: ["ntfy", "ntfys"],
},
{ ...field, key: "host", label: "Hostname", type: "string" },
{
...field,
key: "port",
label: "Port",
type: "int",
min: 1,
max: 65535,
},
{
...field,
key: "token",
label: "Token",
type: "string",
private: true,
},
{
...field,
key: "targets",
label: "Targets",
type: "list",
required: true,
},
{
...field,
key: "image",
label: "Include Image",
type: "bool",
advanced: true,
default: true,
},
{
...field,
key: "priority",
label: "Priority",
type: "choice",
advanced: true,
default: "default",
values: ["max", "high", "default", "low", "min"],
},
],
...overrides,
};
}

View File

@@ -0,0 +1,56 @@
import { describe, expect, it } from "vitest";
import {
appriseFieldsPayload,
initialAppriseValues,
} from "./notificationChannels";
import { makeAppriseService } from "./notificationChannels.fixtures";
const service = makeAppriseService();
describe("initialAppriseValues", () => {
it("starts from the service's defaults", () => {
expect(initialAppriseValues(service)).toEqual({
schema: "ntfys",
host: "",
port: "",
token: "",
targets: [],
image: true,
priority: "default",
});
});
it("puts in what the channel already has, numbers as text", () => {
const values = initialAppriseValues(service, { port: 8080, image: false });
expect(values).toMatchObject({ port: "8080", image: false });
});
});
describe("appriseFieldsPayload", () => {
it("sends what was filled in, numbers as numbers", () => {
const values = {
...initialAppriseValues(service),
host: "ntfy.example.com",
port: "8080",
targets: ["romm"],
};
expect(appriseFieldsPayload(service, values)).toEqual({
schema: "ntfys",
host: "ntfy.example.com",
port: 8080,
targets: ["romm"],
image: true,
priority: "default",
});
});
it("sends a secret the form removes as empty", () => {
const values = initialAppriseValues(service);
expect(appriseFieldsPayload(service, values, ["token"])).toMatchObject({
token: "",
});
});
});

View File

@@ -1,9 +1,11 @@
// What a notification channel can pick from, shared by its list and its dialog.
import type {
AppriseChannelCreatePayload,
AppriseFieldSchema,
AppriseServiceSchema,
NotificationChannelMinLevel,
NotificationChannelSchema,
NotificationChannelType,
NotificationTopic,
WebhookFormat,
} from "@/__generated__";
export const CHANNEL_TOPICS: NotificationTopic[] = [
@@ -27,18 +29,80 @@ export const NOTIFICATION_CHANNEL_SECRET_MAX_LENGTH = 255;
export const NOTIFICATION_CHANNEL_ADDRESS_MAX_LENGTH = 320;
export const NOTIFICATION_CHANNEL_CODE_MAX_LENGTH = 16;
export const FORMAT_ICONS: Record<WebhookFormat, string> = {
json: "mdi-webhook",
discord: "mdi-forum-outline",
ntfy: "mdi-bell-ring-outline",
export const CHANNEL_ICONS: Record<NotificationChannelType, string> = {
apprise: "mdi-bell-ring-outline",
webhook: "mdi-webhook",
email: "mdi-email-outline",
};
export const EMAIL_ICON = "mdi-email-outline";
export type AppriseFieldValue = AppriseChannelCreatePayload["fields"][string];
export function channelIcon(
channel: Pick<NotificationChannelSchema, "type" | "format">,
// Fields most services share get a translated label; the rest keep Apprise's.
const APPRISE_FIELD_LABELS: Record<string, string> = {
schema: "notifications.channel-field-schema",
botname: "notifications.channel-field-botname",
host: "notifications.channel-field-host",
port: "notifications.channel-field-port",
user: "settings.username",
password: "settings.password",
token: "notifications.channel-field-token",
targets: "notifications.channel-field-targets",
path: "notifications.channel-field-path",
verify: "notifications.channel-field-verify",
};
/** A field's label: translated when most services share it, Apprise's otherwise. */
export function appriseFieldLabel(
field: AppriseFieldSchema,
t: (key: string) => string,
): string {
return channel.type === "email"
? EMAIL_ICON
: FORMAT_ICONS[channel.format ?? "json"];
const key = APPRISE_FIELD_LABELS[field.key];
return key ? t(key) : field.label;
}
function isBlank(value: AppriseFieldValue | undefined): boolean {
return (
value === undefined ||
value === "" ||
(Array.isArray(value) && value.length === 0)
);
}
function emptyValue(field: AppriseFieldSchema): AppriseFieldValue {
if (field.type === "list") return [];
if (field.type === "bool") return field.default === true;
if (field.type === "choice") return String(field.default ?? "");
return "";
}
/** The form's starting values: the service's defaults, then what the channel has. */
export function initialAppriseValues(
service: AppriseServiceSchema,
stored: Record<string, AppriseFieldValue> | null = null,
): Record<string, AppriseFieldValue> {
return Object.fromEntries(
service.fields.map((field) => {
const kept = stored?.[field.key];
if (kept === undefined) return [field.key, emptyValue(field)];
return [field.key, typeof kept === "number" ? String(kept) : kept];
}),
);
}
/** The filled-in fields as the backend takes them, with a removed secret as "". */
export function appriseFieldsPayload(
service: AppriseServiceSchema,
values: Record<string, AppriseFieldValue>,
removed: string[] = [],
): Record<string, AppriseFieldValue> {
const payload: Record<string, AppriseFieldValue> = {};
for (const field of service.fields) {
const value = values[field.key];
if (removed.includes(field.key)) payload[field.key] = "";
else if (isBlank(value)) continue;
else if (field.type === "int" || field.type === "float") {
payload[field.key] = Number(value);
} else payload[field.key] = value;
}
return payload;
}

View File

@@ -18,6 +18,7 @@ dependencies = [
"asyncssh ~= 2.23",
"alembic ~= 1.16",
"anyio ~= 4.4",
"apprise ~= 1.13",
"authlib ~= 1.6.12",
"colorama ~= 0.4",
"cryptography>=49,<51",

51
uv.lock generated
View File

@@ -142,6 +142,24 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/81/29/5ecc3a15d5a33e31b26c11426c45c501e439cb865d0bff96315d86443b78/appnope-0.1.4-py2.py3-none-any.whl", hash = "sha256:502575ee11cd7a28c0205f379b525beefebab9d161b7c964670864014ed7213c", size = 4321, upload-time = "2024-02-06T09:43:09.663Z" },
]
[[package]]
name = "apprise"
version = "1.13.1"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "certifi" },
{ name = "click" },
{ name = "markdown" },
{ name = "pyyaml" },
{ name = "requests" },
{ name = "requests-oauthlib" },
{ name = "tzdata", marker = "sys_platform == 'win32'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/81/44/5965c245998c72022297e2b515d9594281a97ed1442b3fa022c2c2324102/apprise-1.13.1.tar.gz", hash = "sha256:e7689dda71aaf739244d6c8690de13cb1361b8d0a79980fb48bb397455ca0bdd", size = 2520230, upload-time = "2026-08-31T02:12:01.472Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/45/7d/6852bd3fc2eb48fa432cb22f5df11d1c902137dcecab93e0d8319b8c8e16/apprise-1.13.1-py3-none-any.whl", hash = "sha256:2ded6d00562dd2ae9eb6f1e6cc8d3fb66e06f7ede6efac0ad029031b633780f4", size = 1826431, upload-time = "2026-08-31T02:11:58.263Z" },
]
[[package]]
name = "asgiref"
version = "3.9.1"
@@ -1133,6 +1151,15 @@ dependencies = [
]
sdist = { url = "https://files.pythonhosted.org/packages/17/bb/4bbc803fbdafedbfba015f7cc1ab1e87a6d1de36725ba058c53e2f8a45ad/mariadb-1.1.12.tar.gz", hash = "sha256:50b02ff2c78b1b4f4628a054e3c8c7dd92972137727a5cc309a64c9ed20c878c", size = 85934, upload-time = "2025-02-13T13:11:48.642Z" }
[[package]]
name = "markdown"
version = "3.10.3"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/29/6f/da4c6aea59b3001f2e8c0ec7497475aadaf3b021c10cab5b2858f0f32b26/markdown-3.10.3.tar.gz", hash = "sha256:3589362618f743188b4d955b874402bc814f4f83f544dc207719f4baa7d9c45f", size = 372596, upload-time = "2026-07-30T19:05:29.005Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/64/69/4a5af2bc115a9a33fefe51709749de8262be3f9ba063d1753a837cdbc49c/markdown-3.10.3-py3-none-any.whl", hash = "sha256:fa6c92a00a4a3c98b22728c64a935ae1928250ae65058a6ded814d2cc29a4cea", size = 110757, upload-time = "2026-07-30T19:05:27.883Z" },
]
[[package]]
name = "markdown-it-py"
version = "3.0.0"
@@ -1369,6 +1396,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/a0/c4/c2971a3ba4c6103a3d10c4b0f24f461ddc027f0f09763220cf35ca1401b3/nest_asyncio-1.6.0-py3-none-any.whl", hash = "sha256:87af6efd6b5e897c81050477ef65c62e2b2f35d51703cae01aff2905b1852e1c", size = 5195, upload-time = "2024-01-21T14:25:17.223Z" },
]
[[package]]
name = "oauthlib"
version = "3.3.1"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/0b/5f/19930f824ffeb0ad4372da4812c50edbd1434f678c90c2733e1188edfc63/oauthlib-3.3.1.tar.gz", hash = "sha256:0f0f8aa759826a193cf66c12ea1af1637f87b9b4622d46e866952bb022e538c9", size = 185918, upload-time = "2025-06-19T22:48:08.269Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/be/9c/92789c596b8df838baa98fa71844d84283302f7604ed565dafe5a6b5041a/oauthlib-3.3.1-py3-none-any.whl", hash = "sha256:88119c938d2b8fb88561af5f6ee0eec8cc8d552b7bb1f712743136eb7523b7a1", size = 160065, upload-time = "2025-06-19T22:48:06.508Z" },
]
[[package]]
name = "opentelemetry-api"
version = "1.44.0"
@@ -2238,6 +2274,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/1e/db/4254e3eabe8020b458f1a747140d32277ec7a271daf1d235b70dc0b4e6e3/requests-2.32.5-py3-none-any.whl", hash = "sha256:2462f94637a34fd532264295e186976db0f5d453d1cdd31473c85a6a161affb6", size = 64738, upload-time = "2025-08-18T20:46:00.542Z" },
]
[[package]]
name = "requests-oauthlib"
version = "2.0.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "oauthlib" },
{ name = "requests" },
]
sdist = { url = "https://files.pythonhosted.org/packages/42/f2/05f29bc3913aea15eb670be136045bf5c5bbf4b99ecb839da9b422bb2c85/requests-oauthlib-2.0.0.tar.gz", hash = "sha256:b3dffaebd884d8cd778494369603a9e7b58d29111bf6b41bdc2dcd87203af4e9", size = 55650, upload-time = "2024-03-22T20:32:29.939Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/3b/5d/63d4ae3b9daea098d5d6f5da83984853c1bbacd5dc826764b249fe119d24/requests_oauthlib-2.0.0-py2.py3-none-any.whl", hash = "sha256:7dd8a5c40426b779b0868c404bdef9768deccf22749cde15852df527e6269b36", size = 24179, upload-time = "2024-03-22T20:32:28.055Z" },
]
[[package]]
name = "rich"
version = "14.0.0"
@@ -2273,6 +2322,7 @@ dependencies = [
{ name = "aiohttp" },
{ name = "alembic" },
{ name = "anyio" },
{ name = "apprise" },
{ name = "asyncssh" },
{ name = "authlib" },
{ name = "bcrypt" },
@@ -2347,6 +2397,7 @@ requires-dist = [
{ name = "aiohttp", specifier = "~=3.14" },
{ name = "alembic", specifier = "~=1.16" },
{ name = "anyio", specifier = "~=4.4" },
{ name = "apprise", specifier = "~=1.13" },
{ name = "asyncssh", specifier = "~=2.23" },
{ name = "authlib", specifier = "~=1.6.12" },
{ name = "bcrypt", specifier = "<5" },