Skip to content

Modern Docker Management, Designed for Everyone

feat: use shoutrrr for notifications (apprise deprecated) (#1424)

Kyle Mendell098cd7384ef4
diff --git a/backend/go.mod b/backend/go.mod
index 1c196d43f..15ae915b5 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -12,8 +12,6 @@ require (
github.com/docker/distribution v2.8.3+incompatible
github.com/docker/docker v28.5.2+incompatible
github.com/docker/go-connections v0.6.0
- github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6
- github.com/emersion/go-smtp v0.24.0
github.com/fsnotify/fsnotify v1.9.0
github.com/getarcaneapp/arcane/types v0.0.0-20260107215709-10ac44bcce4a
github.com/gin-contrib/cors v1.7.6
@@ -31,6 +29,7 @@ require (
github.com/jinzhu/copier v0.4.0
github.com/joho/godotenv v1.5.1
github.com/lmittmann/tint v1.1.2
+ github.com/nicholas-fedor/shoutrrr v0.13.1
github.com/orandin/slog-gorm v1.4.0
github.com/samber/slog-gin v1.19.1
github.com/shirou/gopsutil/v4 v4.25.12
@@ -132,6 +131,7 @@ require (
github.com/leodido/go-urn v1.4.0 // indirect
github.com/lib/pq v1.10.9 // indirect
github.com/lufia/plan9stats v0.0.0-20250827001030-24949be3fa54 // indirect
+ github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.19 // indirect
github.com/mattn/go-shellwords v1.0.12 // indirect
diff --git a/backend/go.sum b/backend/go.sum
index 4b5601c13..998a82843 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -5,10 +5,10 @@ github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
-github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
-github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/DefangLabs/secret-detector v0.0.0-20250811234530-d4b4214cd679 h1:qNT7R4qrN+5u5ajSbqSW1opHP4LA8lzA+ASyw5MQZjs=
github.com/DefangLabs/secret-detector v0.0.0-20250811234530-d4b4214cd679/go.mod h1:blbwPQh4DTlCZEfk1BLU4oMIhLda2U+A840Uag9DsZw=
+github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=
+github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
@@ -156,10 +156,6 @@ github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203 h1:XBBHcIb256gUJ
github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203/go.mod h1:E1jcSv8FaEny+OP/5k9UxZVw9YFWGj7eI4KR/iOBqCg=
github.com/elazarl/goproxy v1.7.2 h1:Y2o6urb7Eule09PjlhQRGNsqRfPmYI3KKQLFpCAV3+o=
github.com/elazarl/goproxy v1.7.2/go.mod h1:82vkLNir0ALaW14Rc399OTTjyNREgmdL2cVoIbS6XaE=
-github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 h1:oP4q0fw+fOSWn3DfFi4EXdT+B+gTtzx8GC9xsc26Znk=
-github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6/go.mod h1:iL2twTeMvZnrg54ZoPDNfJaJaqy0xIQFuBdrLsmspwQ=
-github.com/emersion/go-smtp v0.24.0 h1:g6AfoF140mvW0vLNPD/LuCBLEAdlxOjIXqbIkJIS6Wk=
-github.com/emersion/go-smtp v0.24.0/go.mod h1:ZtRRkbTyp2XTHCA+BmyTFTrj8xY4I+b4McvHxCU2gsQ=
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0=
@@ -223,6 +219,8 @@ github.com/go-sql-driver/mysql v1.3.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
+github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=
+github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
@@ -254,8 +252,8 @@ github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
-github.com/google/pprof v0.0.0-20250820193118-f64d9cf942d6 h1:EEHtgt9IwisQ2AZ4pIsMjahcegHh6rmhqxzIRQIyepY=
-github.com/google/pprof v0.0.0-20250820193118-f64d9cf942d6/go.mod h1:I6V7YzU0XDpsHqbsyrghnFZLO1gwK6NPTNvmetQIk9U=
+github.com/google/pprof v0.0.0-20251114195745-4902fdda35c8 h1:3DsUAV+VNEQa2CUVLxCY3f87278uWfIDhJnbdvDjvmE=
+github.com/google/pprof v0.0.0-20251114195745-4902fdda35c8/go.mod h1:I6V7YzU0XDpsHqbsyrghnFZLO1gwK6NPTNvmetQIk9U=
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4=
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@@ -294,6 +292,8 @@ github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk=
github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
+github.com/jarcoal/httpmock v1.4.1 h1:0Ju+VCFuARfFlhVXFc2HxlcQkfB+Xq12/EotHko+x2A=
+github.com/jarcoal/httpmock v1.4.1/go.mod h1:ftW1xULwo+j0R0JJkJIIi7UKigZUXCLLanykgjwBXL0=
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A=
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=
github.com/jinzhu/copier v0.4.0 h1:w3ciUoD19shMCRargcpm0cm91ytaBhDvuRpz1ODO/U8=
@@ -346,8 +346,8 @@ github.com/lmittmann/tint v1.1.2/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ
github.com/lufia/plan9stats v0.0.0-20250827001030-24949be3fa54 h1:mFWunSatvkQQDhpdyuFAYwyAan3hzCuma+Pz8sqvOfg=
github.com/lufia/plan9stats v0.0.0-20250827001030-24949be3fa54/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=
github.com/magiconair/properties v1.5.3/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
-github.com/magiconair/properties v1.8.9 h1:nWcCbLq1N2v/cpNsy5WvQ37Fb+YElfq20WJ/a8RkpQM=
-github.com/magiconair/properties v1.8.9/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
+github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
+github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
@@ -364,8 +364,6 @@ github.com/miekg/pkcs11 v1.1.1/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WT
github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4=
github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE=
github.com/mitchellh/mapstructure v0.0.0-20150613213606-2caf8efc9366/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
-github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
-github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/moby/buildkit v0.26.3 h1:D+ruZVAk/3ipRq5XRxBH9/DIFpRjSlTtMbghT5gQP9g=
github.com/moby/buildkit v0.26.3/go.mod h1:4T4wJzQS4kYWIfFRjsbJry4QoxDBjK+UGOEOs1izL7w=
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
@@ -409,13 +407,18 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8m
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
+github.com/nicholas-fedor/shoutrrr v0.13.1 h1:llEoHNbnMM4GfQ9+2Ns3n6ssvNfi3NPWluM0AQiicoY=
+github.com/nicholas-fedor/shoutrrr v0.13.1/go.mod h1:kU4cFJpEAtTzl3iV0l+XUXmM90OlC5T01b7roM4/pYM=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg=
+github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc=
+github.com/onsi/ginkgo/v2 v2.27.3 h1:ICsZJ8JoYafeXFFlFAG75a7CxMsJHwgKwtO+82SE9L8=
+github.com/onsi/ginkgo/v2 v2.27.3/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.9.0/go.mod h1:Ho0h+IUsWyvy1OpqCwxlQ/21gkhVunqlU8fDGcoTdcA=
-github.com/onsi/gomega v1.34.1 h1:EUMJIKUjM8sKjYbtxQI9A4z2o+rruxnzNvpknOXie6k=
-github.com/onsi/gomega v1.34.1/go.mod h1:kU1QgUvBDLXBJq618Xvm2LUX6rSAfRaFRTcdOeDLwwY=
+github.com/onsi/gomega v1.38.3 h1:eTX+W6dobAYfFeGC2PV6RwXRu/MyT+cQguijutvkpSM=
+github.com/onsi/gomega v1.38.3/go.mod h1:ZCU1pkQcXDO5Sl9/VVEGlDyp+zm0m1cmeG5TOzLgdh4=
github.com/opencontainers/go-digest v0.0.0-20170106003457-a6d0ee40d420/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
@@ -480,6 +483,8 @@ github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzG
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
+github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4=
+github.com/sagikazarmark/locafero v0.12.0/go.mod h1:sZh36u/YSZ918v0Io+U9ogLYQJ9tLLBmM4eneO6WwsI=
github.com/samber/slog-gin v1.19.1 h1:sp5CwWsETlvw1/ad9gGwdUoMMta1vY+/K/Zgy1Gd+6o=
github.com/samber/slog-gin v1.19.1/go.mod h1:7R4VMQGENllRLLnwGyoB5nUSB+qzxThpGe5G02xla6o=
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ=
@@ -504,19 +509,22 @@ github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 h1:JIAuq3EE
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog=
github.com/spdx/tools-golang v0.5.5 h1:61c0KLfAcNqAjlg6UNMdkwpMernhw3zVRwDZ2x9XOmk=
github.com/spdx/tools-golang v0.5.5/go.mod h1:MVIsXx8ZZzaRWNQpUDhC4Dud34edUYJYecciXgrw5vE=
-github.com/spf13/cast v0.0.0-20150508191742-4d07383ffe94 h1:JmfC365KywYwHB946TTiQWEb8kqPY+pybPLoGE9GgVk=
+github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
+github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
github.com/spf13/cast v0.0.0-20150508191742-4d07383ffe94/go.mod h1:r2rcYCSwa1IExKTDiTfzaxqT2FNHs8hODu4LnUfgKEg=
+github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
+github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/spf13/cobra v0.0.1/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
-github.com/spf13/jwalterweatherman v0.0.0-20141219030609-3d60171a6431 h1:XTHrT015sxHyJ5FnQ0AeemSspZWaDq7DoTRW0EVsDCE=
github.com/spf13/jwalterweatherman v0.0.0-20141219030609-3d60171a6431/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
github.com/spf13/pflag v1.0.0/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
-github.com/spf13/viper v0.0.0-20150530192845-be5ff3e4840c h1:2EejZtjFjKJGk71ANb+wtFK5EjUzUkEM3R0xnp559xg=
github.com/spf13/viper v0.0.0-20150530192845-be5ff3e4840c/go.mod h1:A8kyI5cUJhb8N+3pkfONlcEcZbueH6nhAm0Fq7SrnBM=
+github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
+github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
@@ -532,6 +540,8 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
+github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
+github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/theupdateframework/notary v0.7.0 h1:QyagRZ7wlSpjT5N2qQAh/pN+DVqgekv4DzbAiAiEL3c=
github.com/theupdateframework/notary v0.7.0/go.mod h1:c9DRxcmhHmVLDay4/2fUYdISnHqbFDGRSlXPO0AhYWw=
github.com/tilt-dev/fsnotify v1.4.8-0.20220602155310-fff9c274a375 h1:QB54BJwA6x8QU9nHY3xJSZR2kX9bgpZekRKGkLTmEXA=
@@ -606,6 +616,7 @@ go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
+go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
go.yaml.in/yaml/v4 v4.0.0-rc.3 h1:3h1fjsh1CTAPjW7q/EMe+C8shx5d8ctzZTrLcs/j8Go=
go.yaml.in/yaml/v4 v4.0.0-rc.3/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=
@@ -724,7 +735,6 @@ gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
-gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.go
index d2c4356d2..f21d41176 100644
--- a/backend/internal/bootstrap/bootstrap.go
+++ b/backend/internal/bootstrap/bootstrap.go
@@ -76,7 +76,8 @@ func Bootstrap(ctx context.Context) error {
utils.InitializeNonAgentFeatures(appCtx, cfg,
appServices.User.CreateDefaultAdmin,
- appServices.Settings.MigrateOidcConfigToFields)
+ appServices.Settings.MigrateOidcConfigToFields,
+ appServices.Notification.MigrateDiscordWebhookUrlToFields)
// Handle agent auto-pairing with API key
if cfg.AgentMode && cfg.AgentToken != "" && cfg.ManagerApiUrl != "" {
diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.go
index a31be52b8..35690025d 100644
--- a/backend/internal/bootstrap/services_bootstrap.go
+++ b/backend/internal/bootstrap/services_bootstrap.go
@@ -36,7 +36,7 @@ type Services struct {
Event *services.EventService
Version *services.VersionService
Notification *services.NotificationService
- Apprise *services.AppriseService
+ Apprise *services.AppriseService //nolint:staticcheck // Apprise still functional, deprecated in favor of Shoutrrr
ApiKey *services.ApiKeyService
GitRepository *services.GitRepositoryService
GitOpsSync *services.GitOpsSyncService
diff --git a/backend/internal/huma/handlers/notifications.go b/backend/internal/huma/handlers/notifications.go
index c9b04b8a2..acf8d8360 100644
--- a/backend/internal/huma/handlers/notifications.go
+++ b/backend/internal/huma/handlers/notifications.go
@@ -14,7 +14,7 @@ import (
type NotificationHandler struct {
notificationService *services.NotificationService
- appriseService *services.AppriseService
+ appriseService *services.AppriseService //nolint:staticcheck // Apprise still functional, deprecated in favor of Shoutrrr
}
type GetAllNotificationSettingsInput struct {
@@ -88,6 +88,8 @@ type TestAppriseNotificationOutput struct {
}
// RegisterNotifications registers notification endpoints.
+//
+//nolint:staticcheck // AppriseService still functional, deprecated in favor of Shoutrrr
func RegisterNotifications(api huma.API, notificationSvc *services.NotificationService, appriseSvc *services.AppriseService) {
h := &NotificationHandler{
notificationService: notificationSvc,
@@ -215,7 +217,13 @@ func (h *NotificationHandler) CreateOrUpdateNotificationSettings(ctx context.Con
return nil, err
}
provider := models.NotificationProvider(input.Body.Provider)
- if provider != models.NotificationProviderDiscord && provider != models.NotificationProviderEmail {
+ if provider != models.NotificationProviderDiscord &&
+ provider != models.NotificationProviderEmail &&
+ provider != models.NotificationProviderTelegram &&
+ provider != models.NotificationProviderSignal &&
+ provider != models.NotificationProviderSlack &&
+ provider != models.NotificationProviderNtfy &&
+ provider != models.NotificationProviderGeneric {
return nil, huma.Error400BadRequest((&common.InvalidNotificationProviderError{}).Error())
}
@@ -281,6 +289,9 @@ func (h *NotificationHandler) GetAppriseSettings(ctx context.Context, input *Get
}
settings, err := h.appriseService.GetSettings(ctx)
if err != nil {
+ return nil, huma.Error500InternalServerError("Failed to retrieve Apprise settings", err)
+ }
+ if settings == nil {
return nil, huma.Error404NotFound((&common.AppriseSettingsNotFoundError{}).Error())
}
diff --git a/backend/internal/huma/huma.go b/backend/internal/huma/huma.go
index 11b3619dd..1dbc1c135 100644
--- a/backend/internal/huma/huma.go
+++ b/backend/internal/huma/huma.go
@@ -136,7 +136,7 @@ type Services struct {
Container *services.ContainerService
Network *services.NetworkService
Notification *services.NotificationService
- Apprise *services.AppriseService
+ Apprise *services.AppriseService //nolint:staticcheck // Apprise still functional, deprecated in favor of Shoutrrr
Updater *services.UpdaterService
CustomizeSearch *services.CustomizeSearchService
System *services.SystemService
@@ -294,7 +294,7 @@ func registerHandlers(api huma.API, svc *Services) {
var containerSvc *services.ContainerService
var networkSvc *services.NetworkService
var notificationSvc *services.NotificationService
- var appriseSvc *services.AppriseService
+ var appriseSvc *services.AppriseService //nolint:staticcheck // Apprise still functional, deprecated in favor of Shoutrrr
var updaterSvc *services.UpdaterService
var customizeSearchSvc *services.CustomizeSearchService
var systemSvc *services.SystemService
diff --git a/backend/internal/models/notification.go b/backend/internal/models/notification.go
index 1f428e035..f46c3e48e 100644
--- a/backend/internal/models/notification.go
+++ b/backend/internal/models/notification.go
@@ -7,8 +7,13 @@ import (
type NotificationProvider string
const (
- NotificationProviderDiscord NotificationProvider = "discord"
- NotificationProviderEmail NotificationProvider = "email"
+ NotificationProviderDiscord NotificationProvider = "discord"
+ NotificationProviderEmail NotificationProvider = "email"
+ NotificationProviderTelegram NotificationProvider = "telegram"
+ NotificationProviderSignal NotificationProvider = "signal"
+ NotificationProviderSlack NotificationProvider = "slack"
+ NotificationProviderNtfy NotificationProvider = "ntfy"
+ NotificationProviderGeneric NotificationProvider = "generic"
)
type NotificationEventType string
@@ -56,10 +61,11 @@ func (NotificationLog) TableName() string {
}
type DiscordConfig struct {
- WebhookURL string `json:"webhookUrl"`
- Username string `json:"username,omitempty"`
- AvatarURL string `json:"avatarUrl,omitempty"`
- Events map[NotificationEventType]bool `json:"events,omitempty"`
+ WebhookID string `json:"webhookId"`
+ Token string `json:"token"`
+ Username string `json:"username,omitempty"`
+ AvatarURL string `json:"avatarUrl,omitempty"`
+ Events map[NotificationEventType]bool `json:"events,omitempty"`
}
type EmailConfig struct {
@@ -73,6 +79,65 @@ type EmailConfig struct {
Events map[NotificationEventType]bool `json:"events,omitempty"`
}
+type TelegramConfig struct {
+ BotToken string `json:"botToken"`
+ ChatIDs []string `json:"chatIds"`
+ Preview bool `json:"preview"`
+ Notification bool `json:"notification"`
+ ParseMode string `json:"parseMode,omitempty"`
+ Title string `json:"title,omitempty"`
+ Events map[NotificationEventType]bool `json:"events,omitempty"`
+}
+
+type SignalConfig struct {
+ Host string `json:"host"`
+ Port int `json:"port"`
+ User string `json:"user,omitempty"`
+ Password string `json:"password,omitempty"`
+ Token string `json:"token,omitempty"`
+ Source string `json:"source"`
+ Recipients []string `json:"recipients"`
+ DisableTLS bool `json:"disableTls"`
+ Events map[NotificationEventType]bool `json:"events,omitempty"`
+}
+
+type SlackConfig struct {
+ Token string `json:"token"`
+ BotName string `json:"botName,omitempty"`
+ Icon string `json:"icon,omitempty"`
+ Color string `json:"color,omitempty"`
+ Title string `json:"title,omitempty"`
+ Channel string `json:"channel,omitempty"`
+ ThreadTS string `json:"threadTs,omitempty"`
+ Events map[NotificationEventType]bool `json:"events,omitempty"`
+}
+
+type NtfyConfig struct {
+ Host string `json:"host"`
+ Port int `json:"port"`
+ Topic string `json:"topic"`
+ Username string `json:"username,omitempty"`
+ Password string `json:"password,omitempty"`
+ Priority string `json:"priority,omitempty"`
+ Tags []string `json:"tags,omitempty"`
+ Icon string `json:"icon,omitempty"`
+ Cache bool `json:"cache"`
+ Firebase bool `json:"firebase"`
+ DisableTLSVerification bool `json:"disableTlsVerification"`
+ Events map[NotificationEventType]bool `json:"events,omitempty"`
+}
+
+type GenericConfig struct {
+ WebhookURL string `json:"webhookUrl"`
+ Method string `json:"method,omitempty"`
+ ContentType string `json:"contentType,omitempty"`
+ TitleKey string `json:"titleKey,omitempty"`
+ MessageKey string `json:"messageKey,omitempty"`
+ CustomHeaders map[string]string `json:"customHeaders,omitempty"`
+ DisableTLS bool `json:"disableTls"`
+ Events map[NotificationEventType]bool `json:"events,omitempty"`
+}
+
type AppriseSettings struct {
ID uint `json:"id" gorm:"primaryKey"`
APIURL string `json:"apiUrl" gorm:"not null"`
diff --git a/backend/internal/services/apprise_service.go b/backend/internal/services/apprise_service.go
index 377a17e5a..0c09e26a4 100644
--- a/backend/internal/services/apprise_service.go
+++ b/backend/internal/services/apprise_service.go
@@ -18,6 +18,9 @@ import (
"gorm.io/gorm"
)
+// AppriseService handles sending notifications through Apprise API
+//
+// Deprecated: Built-in providers (e.g., SMTP via Shoutrrr) are preferred.
type AppriseService struct {
db *database.DB
config *config.Config
@@ -153,8 +156,8 @@ func (s *AppriseService) SendImageUpdateNotification(ctx context.Context, imageR
"Image: %s\nUpdate Type: %s\nCurrent Digest: %s\nLatest Digest: %s",
imageRef,
updateInfo.UpdateType,
- truncateDigest(updateInfo.CurrentDigest),
- truncateDigest(updateInfo.LatestDigest),
+ updateInfo.CurrentDigest,
+ updateInfo.LatestDigest,
)
return s.SendNotification(ctx, title, body, "text", models.NotificationEventImageUpdate)
}
@@ -165,8 +168,8 @@ func (s *AppriseService) SendContainerUpdateNotification(ctx context.Context, co
"Container: %s\nImage: %s\nPrevious Version: %s\nCurrent Version: %s\nStatus: Updated Successfully",
containerName,
imageRef,
- truncateDigest(oldDigest),
- truncateDigest(newDigest),
+ oldDigest,
+ newDigest,
)
return s.SendNotification(ctx, title, body, "text", models.NotificationEventContainerUpdate)
}
@@ -194,8 +197,8 @@ func (s *AppriseService) SendBatchImageUpdateNotification(ctx context.Context, u
body += fmt.Sprintf("• %s\n Type: %s\n Current: %s\n Latest: %s\n\n",
imageRef,
update.UpdateType,
- truncateDigest(update.CurrentDigest),
- truncateDigest(update.LatestDigest),
+ update.CurrentDigest,
+ update.LatestDigest,
)
}
diff --git a/backend/internal/services/notification_service.go b/backend/internal/services/notification_service.go
index 671fbde9d..a45051327 100644
--- a/backend/internal/services/notification_service.go
+++ b/backend/internal/services/notification_service.go
@@ -4,16 +4,16 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
- "io"
"log/slog"
- "net/http"
"net/mail"
- "net/url"
"strings"
"text/template"
"time"
+ "gorm.io/gorm"
+
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/database"
"github.com/getarcaneapp/arcane/backend/internal/models"
@@ -119,6 +119,16 @@ func (s *NotificationService) SendImageUpdateNotification(ctx context.Context, i
sendErr = s.sendDiscordNotification(ctx, imageRef, updateInfo, setting.Config)
case models.NotificationProviderEmail:
sendErr = s.sendEmailNotification(ctx, imageRef, updateInfo, setting.Config)
+ case models.NotificationProviderTelegram:
+ sendErr = s.sendTelegramNotification(ctx, imageRef, updateInfo, setting.Config)
+ case models.NotificationProviderSignal:
+ sendErr = s.sendSignalNotification(ctx, imageRef, updateInfo, setting.Config)
+ case models.NotificationProviderSlack:
+ sendErr = s.sendSlackNotification(ctx, imageRef, updateInfo, setting.Config)
+ case models.NotificationProviderNtfy:
+ sendErr = s.sendNtfyNotification(ctx, imageRef, updateInfo, setting.Config)
+ case models.NotificationProviderGeneric:
+ sendErr = s.sendGenericNotification(ctx, imageRef, updateInfo, setting.Config)
default:
slog.WarnContext(ctx, "Unknown notification provider", "provider", setting.Provider)
continue
@@ -202,6 +212,16 @@ func (s *NotificationService) SendContainerUpdateNotification(ctx context.Contex
sendErr = s.sendDiscordContainerUpdateNotification(ctx, containerName, imageRef, oldDigest, newDigest, setting.Config)
case models.NotificationProviderEmail:
sendErr = s.sendEmailContainerUpdateNotification(ctx, containerName, imageRef, oldDigest, newDigest, setting.Config)
+ case models.NotificationProviderTelegram:
+ sendErr = s.sendTelegramContainerUpdateNotification(ctx, containerName, imageRef, oldDigest, newDigest, setting.Config)
+ case models.NotificationProviderSignal:
+ sendErr = s.sendSignalContainerUpdateNotification(ctx, containerName, imageRef, oldDigest, newDigest, setting.Config)
+ case models.NotificationProviderSlack:
+ sendErr = s.sendSlackContainerUpdateNotification(ctx, containerName, imageRef, oldDigest, newDigest, setting.Config)
+ case models.NotificationProviderNtfy:
+ sendErr = s.sendNtfyContainerUpdateNotification(ctx, containerName, imageRef, oldDigest, newDigest, setting.Config)
+ case models.NotificationProviderGeneric:
+ sendErr = s.sendGenericContainerUpdateNotification(ctx, containerName, imageRef, oldDigest, newDigest, setting.Config)
default:
slog.WarnContext(ctx, "Unknown notification provider", "provider", setting.Provider)
continue
@@ -241,101 +261,99 @@ func (s *NotificationService) sendDiscordNotification(ctx context.Context, image
return fmt.Errorf("failed to unmarshal Discord config: %w", err)
}
- if discordConfig.WebhookURL == "" {
- return fmt.Errorf("discord webhook URL not configured")
+ if discordConfig.WebhookID == "" || discordConfig.Token == "" {
+ return fmt.Errorf("discord webhook ID or token not configured")
}
- // Decrypt webhook URL if encrypted
- webhookURL := discordConfig.WebhookURL
- if decrypted, err := crypto.Decrypt(webhookURL); err == nil {
- webhookURL = decrypted
+ // Decrypt token if encrypted
+ if discordConfig.Token != "" {
+ if decrypted, err := crypto.Decrypt(discordConfig.Token); err == nil {
+ discordConfig.Token = decrypted
+ } else {
+ slog.Warn("Failed to decrypt Discord token, using raw value (may be unencrypted legacy value)", "error", err)
+ }
}
- // Validate webhook URL to prevent SSRF
- if err := validateWebhookURL(webhookURL); err != nil {
- return fmt.Errorf("invalid webhook URL: %w", err)
+ // Build message content - Discord embeds via Shoutrrr are sent as formatted markdown
+ updateStatus := "No Update"
+ if updateInfo.HasUpdate {
+ updateStatus = "⚠️ Update Available"
}
- username := discordConfig.Username
- if username == "" {
- username = "Arcane"
+ message := fmt.Sprintf("**🔔 Container Image Update Notification**\n\n"+
+ "**Image:** %s\n"+
+ "**Status:** %s\n"+
+ "**Update Type:** %s\n",
+ imageRef, updateStatus, updateInfo.UpdateType)
+
+ if updateInfo.CurrentDigest != "" {
+ message += fmt.Sprintf("**Current Digest:** `%s`\n", updateInfo.CurrentDigest)
+ }
+ if updateInfo.LatestDigest != "" {
+ message += fmt.Sprintf("**Latest Digest:** `%s`\n", updateInfo.LatestDigest)
}
- color := 3447003 // Blue
- if updateInfo.HasUpdate {
- color = 15844367 // Gold for updates
- }
-
- fields := []map[string]interface{}{
- {
- "name": "Image",
- "value": imageRef,
- "inline": false,
- },
- {
- "name": "Update Available",
- "value": fmt.Sprintf("%t", updateInfo.HasUpdate),
- "inline": true,
- },
- {
- "name": "Update Type",
- "value": updateInfo.UpdateType,
- "inline": true,
- },
+ if err := notifications.SendDiscord(ctx, discordConfig, message); err != nil {
+ return fmt.Errorf("failed to send Discord notification: %w", err)
}
- if updateInfo.CurrentDigest != "" {
- fields = append(fields, map[string]interface{}{
- "name": "Current Digest",
- "value": truncateDigest(updateInfo.CurrentDigest),
- "inline": true,
- })
+ return nil
+}
+
+func (s *NotificationService) sendTelegramNotification(ctx context.Context, imageRef string, updateInfo *imageupdate.Response, config models.JSON) error {
+ var telegramConfig models.TelegramConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Telegram config: %w", err)
}
- if updateInfo.LatestDigest != "" {
- fields = append(fields, map[string]interface{}{
- "name": "Latest Digest",
- "value": truncateDigest(updateInfo.LatestDigest),
- "inline": true,
- })
+ if err := json.Unmarshal(configBytes, &telegramConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Telegram config: %w", err)
}
- payload := map[string]interface{}{
- "username": username,
- "embeds": []map[string]interface{}{
- {
- "title": "🔔 Container Image Update Available",
- "description": fmt.Sprintf("A new update has been detected for **%s**", imageRef),
- "color": color,
- "fields": fields,
- "timestamp": time.Now().Format(time.RFC3339),
- },
- },
+ if telegramConfig.BotToken == "" {
+ return fmt.Errorf("telegram bot token not configured")
+ }
+ if len(telegramConfig.ChatIDs) == 0 {
+ return fmt.Errorf("no telegram chat IDs configured")
}
- if discordConfig.AvatarURL != "" {
- payload["avatar_url"] = discordConfig.AvatarURL
+ // Decrypt bot token if encrypted
+ if telegramConfig.BotToken != "" {
+ if decrypted, err := crypto.Decrypt(telegramConfig.BotToken); err == nil {
+ telegramConfig.BotToken = decrypted
+ } else {
+ slog.Warn("Failed to decrypt Telegram bot token, using raw value (may be unencrypted legacy value)", "error", err)
+ }
}
- payloadBytes, err := json.Marshal(payload)
- if err != nil {
- return fmt.Errorf("failed to marshal Discord payload: %w", err)
+ // Build message content using HTML formatting
+ // HTML is easier to escape than Markdown and better supported
+ updateStatus := "No Update"
+ if updateInfo.HasUpdate {
+ updateStatus = "⚠️ Update Available"
}
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, webhookURL, bytes.NewBuffer(payloadBytes))
- if err != nil {
- return fmt.Errorf("failed to create Discord request: %w", err)
+ // Use HTML formatting - it's more reliable than Markdown
+ message := fmt.Sprintf("🔔 <b>Container Image Update Notification</b>\n\n"+
+ "<b>Image:</b> %s\n"+
+ "<b>Status:</b> %s\n"+
+ "<b>Update Type:</b> %s\n",
+ imageRef, updateStatus, updateInfo.UpdateType)
+
+ if updateInfo.CurrentDigest != "" {
+ message += fmt.Sprintf("<b>Current Digest:</b> <code>%s</code>\n", updateInfo.CurrentDigest)
+ }
+ if updateInfo.LatestDigest != "" {
+ message += fmt.Sprintf("<b>Latest Digest:</b> <code>%s</code>\n", updateInfo.LatestDigest)
}
- req.Header.Set("Content-Type", "application/json")
- client := &http.Client{Timeout: 10 * time.Second}
- resp, err := client.Do(req)
- if err != nil {
- return fmt.Errorf("failed to send Discord notification: %w", err)
+ // Set parse mode to HTML if not already set
+ if telegramConfig.ParseMode == "" {
+ telegramConfig.ParseMode = "HTML"
}
- defer resp.Body.Close()
- if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- return fmt.Errorf("discord webhook returned status %d", resp.StatusCode)
+ if err := notifications.SendTelegram(ctx, telegramConfig, message); err != nil {
+ return fmt.Errorf("failed to send Telegram notification: %w", err)
}
return nil
@@ -370,27 +388,18 @@ func (s *NotificationService) sendEmailNotification(ctx context.Context, imageRe
if emailConfig.SMTPPassword != "" {
if decrypted, err := crypto.Decrypt(emailConfig.SMTPPassword); err == nil {
emailConfig.SMTPPassword = decrypted
+ } else {
+ slog.Warn("Failed to decrypt email SMTP password, using raw value (may be unencrypted legacy value)", "error", err)
}
}
- htmlBody, textBody, err := s.renderEmailTemplate(imageRef, updateInfo)
+ htmlBody, _, err := s.renderEmailTemplate(imageRef, updateInfo)
if err != nil {
return fmt.Errorf("failed to render email template: %w", err)
}
subject := fmt.Sprintf("Container Update Available: %s", notifications.SanitizeForEmail(imageRef))
- message, err := notifications.BuildMultipartMessage(emailConfig.FromAddress, emailConfig.ToAddresses, subject, htmlBody, textBody)
- if err != nil {
- return fmt.Errorf("failed to build email message: %w", err)
- }
-
- client, err := notifications.ConnectSMTP(ctx, emailConfig)
- if err != nil {
- return fmt.Errorf("failed to connect to SMTP server: %w", err)
- }
- defer client.Close()
-
- if err := client.SendMessage(emailConfig.FromAddress, emailConfig.ToAddresses, message); err != nil {
+ if err := notifications.SendEmail(ctx, emailConfig, subject, htmlBody); err != nil {
return fmt.Errorf("failed to send email: %w", err)
}
@@ -407,8 +416,8 @@ func (s *NotificationService) renderEmailTemplate(imageRef string, updateInfo *i
"ImageRef": imageRef,
"HasUpdate": updateInfo.HasUpdate,
"UpdateType": updateInfo.UpdateType,
- "CurrentDigest": truncateDigest(updateInfo.CurrentDigest),
- "LatestDigest": truncateDigest(updateInfo.LatestDigest),
+ "CurrentDigest": updateInfo.CurrentDigest,
+ "LatestDigest": updateInfo.LatestDigest,
"CheckTime": updateInfo.CheckTime.Format(time.RFC1123),
}
@@ -455,95 +464,89 @@ func (s *NotificationService) sendDiscordContainerUpdateNotification(ctx context
return fmt.Errorf("failed to unmarshal Discord config: %w", err)
}
- if discordConfig.WebhookURL == "" {
- return fmt.Errorf("discord webhook URL not configured")
- }
-
- webhookURL := discordConfig.WebhookURL
- if decrypted, err := crypto.Decrypt(webhookURL); err == nil {
- webhookURL = decrypted
- }
-
- if err := validateWebhookURL(webhookURL); err != nil {
- return fmt.Errorf("invalid webhook URL: %w", err)
+ if discordConfig.WebhookID == "" || discordConfig.Token == "" {
+ return fmt.Errorf("discord webhook ID or token not configured")
}
- username := discordConfig.Username
- if username == "" {
- username = "Arcane"
+ // Decrypt token if encrypted
+ if discordConfig.Token != "" {
+ if decrypted, err := crypto.Decrypt(discordConfig.Token); err == nil {
+ discordConfig.Token = decrypted
+ } else {
+ slog.Warn("Failed to decrypt Discord token, using raw value (may be unencrypted legacy value)", "error", err)
+ }
}
- fields := []map[string]interface{}{
- {
- "name": "Container",
- "value": containerName,
- "inline": false,
- },
- {
- "name": "Image",
- "value": imageRef,
- "inline": false,
- },
- {
- "name": "Status",
- "value": "✅ Updated Successfully",
- "inline": false,
- },
- }
+ // Build message content
+ message := fmt.Sprintf("**✅ Container Successfully Updated**\n\n"+
+ "Your container has been updated with the latest image version.\n\n"+
+ "**Container:** %s\n"+
+ "**Image:** %s\n"+
+ "**Status:** ✅ Updated Successfully\n",
+ containerName, imageRef)
if oldDigest != "" {
- fields = append(fields, map[string]interface{}{
- "name": "Previous Version",
- "value": truncateDigest(oldDigest),
- "inline": true,
- })
+ message += fmt.Sprintf("**Previous Version:** `%s`\n", oldDigest)
}
if newDigest != "" {
- fields = append(fields, map[string]interface{}{
- "name": "Current Version",
- "value": truncateDigest(newDigest),
- "inline": true,
- })
+ message += fmt.Sprintf("**Current Version:** `%s`\n", newDigest)
}
- embed := map[string]interface{}{
- "title": "Container Successfully Updated",
- "description": "Your container has been updated with the latest image version.",
- "color": 5025616, // Green color for success
- "fields": fields,
- "timestamp": time.Now().Format(time.RFC3339),
+ if err := notifications.SendDiscord(ctx, discordConfig, message); err != nil {
+ return fmt.Errorf("failed to send Discord notification: %w", err)
}
- payload := map[string]interface{}{
- "username": username,
- "embeds": []map[string]interface{}{embed},
+ return nil
+}
+
+func (s *NotificationService) sendTelegramContainerUpdateNotification(ctx context.Context, containerName, imageRef, oldDigest, newDigest string, config models.JSON) error {
+ var telegramConfig models.TelegramConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Telegram config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &telegramConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Telegram config: %w", err)
}
- if discordConfig.AvatarURL != "" {
- payload["avatar_url"] = discordConfig.AvatarURL
+ if telegramConfig.BotToken == "" {
+ return fmt.Errorf("telegram bot token not configured")
+ }
+ if len(telegramConfig.ChatIDs) == 0 {
+ return fmt.Errorf("no telegram chat IDs configured")
}
- payloadBytes, err := json.Marshal(payload)
- if err != nil {
- return fmt.Errorf("failed to marshal Discord payload: %w", err)
+ // Decrypt bot token if encrypted
+ if telegramConfig.BotToken != "" {
+ if decrypted, err := crypto.Decrypt(telegramConfig.BotToken); err == nil {
+ telegramConfig.BotToken = decrypted
+ } else {
+ slog.Warn("Failed to decrypt Telegram bot token, using raw value (may be unencrypted legacy value)", "error", err)
+ }
}
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, webhookURL, bytes.NewBuffer(payloadBytes))
- if err != nil {
- return fmt.Errorf("failed to create request: %w", err)
+ // Build message content using HTML formatting
+ message := fmt.Sprintf("✅ <b>Container Successfully Updated</b>\n\n"+
+ "Your container has been updated with the latest image version.\n\n"+
+ "<b>Container:</b> %s\n"+
+ "<b>Image:</b> %s\n"+
+ "<b>Status:</b> ✅ Updated Successfully\n",
+ containerName, imageRef)
+
+ if oldDigest != "" {
+ message += fmt.Sprintf("<b>Previous Version:</b> <code>%s</code>\n", oldDigest)
+ }
+ if newDigest != "" {
+ message += fmt.Sprintf("<b>Current Version:</b> <code>%s</code>\n", newDigest)
}
- req.Header.Set("Content-Type", "application/json")
- client := &http.Client{Timeout: 10 * time.Second}
- resp, err := client.Do(req)
- if err != nil {
- return fmt.Errorf("failed to send webhook: %w", err)
+ // Set parse mode to HTML if not already set
+ if telegramConfig.ParseMode == "" {
+ telegramConfig.ParseMode = "HTML"
}
- defer resp.Body.Close()
- if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- bodyBytes, _ := io.ReadAll(resp.Body)
- return fmt.Errorf("webhook returned status %d: %s", resp.StatusCode, string(bodyBytes))
+ if err := notifications.SendTelegram(ctx, telegramConfig, message); err != nil {
+ return fmt.Errorf("failed to send Telegram notification: %w", err)
}
return nil
@@ -578,27 +581,18 @@ func (s *NotificationService) sendEmailContainerUpdateNotification(ctx context.C
if emailConfig.SMTPPassword != "" {
if decrypted, err := crypto.Decrypt(emailConfig.SMTPPassword); err == nil {
emailConfig.SMTPPassword = decrypted
+ } else {
+ slog.Warn("Failed to decrypt email SMTP password, using raw value (may be unencrypted legacy value)", "error", err)
}
}
- htmlBody, textBody, err := s.renderContainerUpdateEmailTemplate(containerName, imageRef, oldDigest, newDigest)
+ htmlBody, _, err := s.renderContainerUpdateEmailTemplate(containerName, imageRef, oldDigest, newDigest)
if err != nil {
return fmt.Errorf("failed to render email template: %w", err)
}
subject := fmt.Sprintf("Container Updated: %s", notifications.SanitizeForEmail(containerName))
- message, err := notifications.BuildMultipartMessage(emailConfig.FromAddress, emailConfig.ToAddresses, subject, htmlBody, textBody)
- if err != nil {
- return fmt.Errorf("failed to build email message: %w", err)
- }
-
- client, err := notifications.ConnectSMTP(ctx, emailConfig)
- if err != nil {
- return fmt.Errorf("failed to connect to SMTP server: %w", err)
- }
- defer client.Close()
-
- if err := client.SendMessage(emailConfig.FromAddress, emailConfig.ToAddresses, message); err != nil {
+ if err := notifications.SendEmail(ctx, emailConfig, subject, htmlBody); err != nil {
return fmt.Errorf("failed to send email: %w", err)
}
@@ -614,8 +608,8 @@ func (s *NotificationService) renderContainerUpdateEmailTemplate(containerName,
"Environment": "Local Docker",
"ContainerName": containerName,
"ImageRef": imageRef,
- "OldDigest": truncateDigest(oldDigest),
- "NewDigest": truncateDigest(newDigest),
+ "OldDigest": oldDigest,
+ "NewDigest": newDigest,
"UpdateTime": time.Now().Format(time.RFC1123),
}
@@ -705,6 +699,16 @@ func (s *NotificationService) TestNotification(ctx context.Context, provider mod
return s.sendBatchEmailNotification(ctx, testUpdates, setting.Config)
}
return s.sendTestEmail(ctx, setting.Config)
+ case models.NotificationProviderTelegram:
+ return s.sendTelegramNotification(ctx, "nginx:latest", testUpdate, setting.Config)
+ case models.NotificationProviderSignal:
+ return s.sendSignalNotification(ctx, "nginx:latest", testUpdate, setting.Config)
+ case models.NotificationProviderSlack:
+ return s.sendSlackNotification(ctx, "nginx:latest", testUpdate, setting.Config)
+ case models.NotificationProviderNtfy:
+ return s.sendNtfyNotification(ctx, "test/image:latest", testUpdate, setting.Config)
+ case models.NotificationProviderGeneric:
+ return s.sendGenericNotification(ctx, "test/image:latest", testUpdate, setting.Config)
default:
return fmt.Errorf("unknown provider: %s", provider)
}
@@ -742,24 +746,13 @@ func (s *NotificationService) sendTestEmail(ctx context.Context, config models.J
}
}
- htmlBody, textBody, err := s.renderTestEmailTemplate()
+ htmlBody, _, err := s.renderTestEmailTemplate()
if err != nil {
return fmt.Errorf("failed to render test email template: %w", err)
}
subject := "Test Email from Arcane"
- message, err := notifications.BuildMultipartMessage(emailConfig.FromAddress, emailConfig.ToAddresses, subject, htmlBody, textBody)
- if err != nil {
- return fmt.Errorf("failed to build email message: %w", err)
- }
-
- client, err := notifications.ConnectSMTP(ctx, emailConfig)
- if err != nil {
- return fmt.Errorf("failed to connect to SMTP server: %w", err)
- }
- defer client.Close()
-
- if err := client.SendMessage(emailConfig.FromAddress, emailConfig.ToAddresses, message); err != nil {
+ if err := notifications.SendEmail(ctx, emailConfig, subject, htmlBody); err != nil {
return fmt.Errorf("failed to send email: %w", err)
}
@@ -864,6 +857,16 @@ func (s *NotificationService) SendBatchImageUpdateNotification(ctx context.Conte
sendErr = s.sendBatchDiscordNotification(ctx, updatesWithChanges, setting.Config)
case models.NotificationProviderEmail:
sendErr = s.sendBatchEmailNotification(ctx, updatesWithChanges, setting.Config)
+ case models.NotificationProviderTelegram:
+ sendErr = s.sendBatchTelegramNotification(ctx, updatesWithChanges, setting.Config)
+ case models.NotificationProviderSignal:
+ sendErr = s.sendBatchSignalNotification(ctx, updatesWithChanges, setting.Config)
+ case models.NotificationProviderSlack:
+ sendErr = s.sendBatchSlackNotification(ctx, updatesWithChanges, setting.Config)
+ case models.NotificationProviderNtfy:
+ sendErr = s.sendBatchNtfyNotification(ctx, updatesWithChanges, setting.Config)
+ case models.NotificationProviderGeneric:
+ sendErr = s.sendBatchGenericNotification(ctx, updatesWithChanges, setting.Config)
default:
slog.WarnContext(ctx, "Unknown notification provider", "provider", setting.Provider)
continue
@@ -907,76 +910,77 @@ func (s *NotificationService) sendBatchDiscordNotification(ctx context.Context,
return fmt.Errorf("failed to unmarshal discord config: %w", err)
}
- // Decrypt webhook URL if encrypted
- webhookURL := discordConfig.WebhookURL
- if decrypted, err := crypto.Decrypt(webhookURL); err == nil {
- webhookURL = decrypted
- }
-
- if err := validateWebhookURL(webhookURL); err != nil {
- return fmt.Errorf("invalid webhook URL: %w", err)
- }
-
- fields := make([]map[string]interface{}, 0, len(updates))
- for imageRef, update := range updates {
- fields = append(fields, map[string]interface{}{
- "name": imageRef,
- "value": fmt.Sprintf(
- "**Type:** %s\n**Current:** `%s`\n**Latest:** `%s`",
- update.UpdateType,
- truncateDigest(update.CurrentDigest),
- truncateDigest(update.LatestDigest),
- ),
- "inline": false,
- })
+ // Decrypt token if encrypted
+ if decrypted, err := crypto.Decrypt(discordConfig.Token); err == nil {
+ discordConfig.Token = decrypted
}
+ // Build batch message content
title := "Container Image Updates Available"
description := fmt.Sprintf("%d container image(s) have updates available.", len(updates))
if len(updates) == 1 {
description = "1 container image has an update available."
}
- embed := map[string]interface{}{
- "title": title,
- "description": description,
- "color": 3447003,
- "fields": fields,
- "timestamp": time.Now().Format(time.RFC3339),
+ message := fmt.Sprintf("**%s**\n\n%s\n\n", title, description)
+
+ for imageRef, update := range updates {
+ message += fmt.Sprintf("**%s**\n"+
+ "• **Type:** %s\n"+
+ "• **Current:** `%s`\n"+
+ "• **Latest:** `%s`\n\n",
+ imageRef,
+ update.UpdateType,
+ update.CurrentDigest,
+ update.LatestDigest,
+ )
}
- payload := map[string]interface{}{
- "embeds": []interface{}{embed},
+ if err := notifications.SendDiscord(ctx, discordConfig, message); err != nil {
+ return fmt.Errorf("failed to send batch Discord notification: %w", err)
}
- if discordConfig.Username != "" {
- payload["username"] = discordConfig.Username
+ return nil
+}
+
+func (s *NotificationService) sendBatchTelegramNotification(ctx context.Context, updates map[string]*imageupdate.Response, config models.JSON) error {
+ var telegramConfig models.TelegramConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal telegram config: %w", err)
}
- if discordConfig.AvatarURL != "" {
- payload["avatar_url"] = discordConfig.AvatarURL
+ if err := json.Unmarshal(configBytes, &telegramConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal telegram config: %w", err)
}
- jsonPayload, err := json.Marshal(payload)
- if err != nil {
- return fmt.Errorf("failed to marshal Discord payload: %w", err)
+ // Decrypt bot token if encrypted
+ if decrypted, err := crypto.Decrypt(telegramConfig.BotToken); err == nil {
+ telegramConfig.BotToken = decrypted
}
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, webhookURL, bytes.NewReader(jsonPayload))
- if err != nil {
- return fmt.Errorf("failed to create HTTP request: %w", err)
+ // Build batch message content
+ title := "Container Image Updates Available"
+ description := fmt.Sprintf("%d container image(s) have updates available.", len(updates))
+ if len(updates) == 1 {
+ description = "1 container image has an update available."
}
- req.Header.Set("Content-Type", "application/json")
- client := &http.Client{Timeout: 10 * time.Second}
- resp, err := client.Do(req)
- if err != nil {
- return fmt.Errorf("failed to send Discord webhook: %w", err)
+ message := fmt.Sprintf("*%s*\n\n%s\n\n", title, description)
+
+ for imageRef, update := range updates {
+ message += fmt.Sprintf("*%s*\n"+
+ "• *Type:* %s\n"+
+ "• *Current:* `%s`\n"+
+ "• *Latest:* `%s`\n\n",
+ imageRef,
+ update.UpdateType,
+ update.CurrentDigest,
+ update.LatestDigest,
+ )
}
- defer resp.Body.Close()
- if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- body, _ := io.ReadAll(resp.Body)
- return fmt.Errorf("discord webhook failed with status %d: %s", resp.StatusCode, string(body))
+ if err := notifications.SendTelegram(ctx, telegramConfig, message); err != nil {
+ return fmt.Errorf("failed to send batch Telegram notification: %w", err)
}
return nil
@@ -1011,10 +1015,12 @@ func (s *NotificationService) sendBatchEmailNotification(ctx context.Context, up
if emailConfig.SMTPPassword != "" {
if decrypted, err := crypto.Decrypt(emailConfig.SMTPPassword); err == nil {
emailConfig.SMTPPassword = decrypted
+ } else {
+ slog.Warn("Failed to decrypt email SMTP password, using raw value (may be unencrypted legacy value)", "error", err)
}
}
- htmlBody, textBody, err := s.renderBatchEmailTemplate(updates)
+ htmlBody, _, err := s.renderBatchEmailTemplate(updates)
if err != nil {
return fmt.Errorf("failed to render email template: %w", err)
}
@@ -1026,18 +1032,7 @@ func (s *NotificationService) sendBatchEmailNotification(ctx context.Context, up
}
return ""
}())
- message, err := notifications.BuildMultipartMessage(emailConfig.FromAddress, emailConfig.ToAddresses, subject, htmlBody, textBody)
- if err != nil {
- return fmt.Errorf("failed to build email message: %w", err)
- }
-
- client, err := notifications.ConnectSMTP(ctx, emailConfig)
- if err != nil {
- return fmt.Errorf("failed to connect to SMTP server: %w", err)
- }
- defer client.Close()
-
- if err := client.SendMessage(emailConfig.FromAddress, emailConfig.ToAddresses, message); err != nil {
+ if err := notifications.SendEmail(ctx, emailConfig, subject, htmlBody); err != nil {
return fmt.Errorf("failed to send email: %w", err)
}
@@ -1094,48 +1089,703 @@ func (s *NotificationService) renderBatchEmailTemplate(updates map[string]*image
return htmlBuf.String(), textBuf.String(), nil
}
-func truncateDigest(digest string) string {
- if len(digest) > 19 {
- return digest[:19] + "..."
+func (s *NotificationService) sendSignalNotification(ctx context.Context, imageRef string, updateInfo *imageupdate.Response, config models.JSON) error {
+ var signalConfig models.SignalConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Signal config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &signalConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Signal config: %w", err)
+ }
+
+ if signalConfig.Host == "" {
+ return fmt.Errorf("signal host not configured")
+ }
+ if signalConfig.Port == 0 {
+ return fmt.Errorf("signal port not configured")
+ }
+ if signalConfig.Source == "" {
+ return fmt.Errorf("signal source phone number not configured")
+ }
+ if len(signalConfig.Recipients) == 0 {
+ return fmt.Errorf("no signal recipients configured")
+ }
+
+ // Validate authentication
+ hasBasicAuth := signalConfig.User != "" && signalConfig.Password != ""
+ hasTokenAuth := signalConfig.Token != ""
+ if !hasBasicAuth && !hasTokenAuth {
+ return fmt.Errorf("signal requires either basic auth (user/password) or token authentication")
+ }
+ if hasBasicAuth && hasTokenAuth {
+ return fmt.Errorf("signal cannot use both basic auth and token authentication simultaneously")
+ }
+
+ // Decrypt sensitive fields if encrypted
+ if signalConfig.Password != "" {
+ if decrypted, err := crypto.Decrypt(signalConfig.Password); err == nil {
+ signalConfig.Password = decrypted
+ } else {
+ slog.Warn("Failed to decrypt Signal password, using raw value (may be unencrypted legacy value)", "error", err)
+ }
+ }
+ if signalConfig.Token != "" {
+ if decrypted, err := crypto.Decrypt(signalConfig.Token); err == nil {
+ signalConfig.Token = decrypted
+ } else {
+ slog.Warn("Failed to decrypt Signal token, using raw value (may be unencrypted legacy value)", "error", err)
+ }
+ }
+
+ // Build message content
+ updateStatus := "No Update"
+ if updateInfo.HasUpdate {
+ updateStatus = "⚠️ Update Available"
+ }
+
+ message := fmt.Sprintf("🔔 Container Image Update Notification\n\n"+
+ "Image: %s\n"+
+ "Status: %s\n"+
+ "Update Type: %s\n",
+ imageRef, updateStatus, updateInfo.UpdateType)
+
+ if updateInfo.CurrentDigest != "" {
+ message += fmt.Sprintf("Current Digest: %s\n", updateInfo.CurrentDigest)
+ }
+ if updateInfo.LatestDigest != "" {
+ message += fmt.Sprintf("Latest Digest: %s\n", updateInfo.LatestDigest)
+ }
+
+ if err := notifications.SendSignal(ctx, signalConfig, message); err != nil {
+ return fmt.Errorf("failed to send Signal notification: %w", err)
+ }
+
+ return nil
+}
+
+func (s *NotificationService) sendSignalContainerUpdateNotification(ctx context.Context, containerName, imageRef, oldDigest, newDigest string, config models.JSON) error {
+ var signalConfig models.SignalConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Signal config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &signalConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Signal config: %w", err)
+ }
+
+ if signalConfig.Host == "" {
+ return fmt.Errorf("signal host not configured")
+ }
+ if signalConfig.Port == 0 {
+ return fmt.Errorf("signal port not configured")
+ }
+ if signalConfig.Source == "" {
+ return fmt.Errorf("signal source phone number not configured")
+ }
+ if len(signalConfig.Recipients) == 0 {
+ return fmt.Errorf("no signal recipients configured")
+ }
+
+ // Validate authentication
+ hasBasicAuth := signalConfig.User != "" && signalConfig.Password != ""
+ hasTokenAuth := signalConfig.Token != ""
+ if !hasBasicAuth && !hasTokenAuth {
+ return fmt.Errorf("signal requires either basic auth (user/password) or token authentication")
+ }
+ if hasBasicAuth && hasTokenAuth {
+ return fmt.Errorf("signal cannot use both basic auth and token authentication simultaneously")
+ }
+
+ // Decrypt sensitive fields if encrypted
+ if signalConfig.Password != "" {
+ if decrypted, err := crypto.Decrypt(signalConfig.Password); err == nil {
+ signalConfig.Password = decrypted
+ } else {
+ slog.Warn("Failed to decrypt Signal password, using raw value (may be unencrypted legacy value)", "error", err)
+ }
+ }
+ if signalConfig.Token != "" {
+ if decrypted, err := crypto.Decrypt(signalConfig.Token); err == nil {
+ signalConfig.Token = decrypted
+ } else {
+ slog.Warn("Failed to decrypt Signal token, using raw value (may be unencrypted legacy value)", "error", err)
+ }
+ }
+
+ // Build message content
+ message := fmt.Sprintf("✅ Container Successfully Updated\n\n"+
+ "Your container has been updated with the latest image version.\n\n"+
+ "Container: %s\n"+
+ "Image: %s\n"+
+ "Status: ✅ Updated Successfully\n",
+ containerName, imageRef)
+
+ if oldDigest != "" {
+ message += fmt.Sprintf("Previous Version: %s\n", oldDigest)
+ }
+ if newDigest != "" {
+ message += fmt.Sprintf("Current Version: %s\n", newDigest)
+ }
+
+ if err := notifications.SendSignal(ctx, signalConfig, message); err != nil {
+ return fmt.Errorf("failed to send Signal notification: %w", err)
+ }
+
+ return nil
+}
+
+func (s *NotificationService) sendBatchSignalNotification(ctx context.Context, updates map[string]*imageupdate.Response, config models.JSON) error {
+ var signalConfig models.SignalConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal signal config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &signalConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal signal config: %w", err)
+ }
+
+ // Validate authentication
+ hasBasicAuth := signalConfig.User != "" && signalConfig.Password != ""
+ hasTokenAuth := signalConfig.Token != ""
+ if !hasBasicAuth && !hasTokenAuth {
+ return fmt.Errorf("signal requires either basic auth (user/password) or token authentication")
+ }
+ if hasBasicAuth && hasTokenAuth {
+ return fmt.Errorf("signal cannot use both basic auth and token authentication simultaneously")
+ }
+
+ // Decrypt sensitive fields if encrypted
+ if signalConfig.Password != "" {
+ if decrypted, err := crypto.Decrypt(signalConfig.Password); err == nil {
+ signalConfig.Password = decrypted
+ }
+ }
+ if signalConfig.Token != "" {
+ if decrypted, err := crypto.Decrypt(signalConfig.Token); err == nil {
+ signalConfig.Token = decrypted
+ }
+ }
+
+ // Build batch message content
+ title := "Container Image Updates Available"
+ description := fmt.Sprintf("%d container image(s) have updates available.", len(updates))
+ if len(updates) == 1 {
+ description = "1 container image has an update available."
+ }
+
+ message := fmt.Sprintf("%s\n\n%s\n\n", title, description)
+
+ for imageRef, update := range updates {
+ message += fmt.Sprintf("%s\n"+
+ "• Type: %s\n"+
+ "• Current: %s\n"+
+ "• Latest: %s\n\n",
+ imageRef,
+ update.UpdateType,
+ update.CurrentDigest,
+ update.LatestDigest,
+ )
+ }
+
+ if err := notifications.SendSignal(ctx, signalConfig, message); err != nil {
+ return fmt.Errorf("failed to send batch Signal notification: %w", err)
+ }
+
+ return nil
+}
+
+func (s *NotificationService) sendSlackNotification(ctx context.Context, imageRef string, updateInfo *imageupdate.Response, config models.JSON) error {
+ var slackConfig models.SlackConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Slack config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &slackConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Slack config: %w", err)
+ }
+
+ if slackConfig.Token == "" {
+ return fmt.Errorf("slack token not configured")
+ }
+
+ // Decrypt token if encrypted
+ if slackConfig.Token != "" {
+ if decrypted, err := crypto.Decrypt(slackConfig.Token); err == nil {
+ slackConfig.Token = decrypted
+ } else {
+ slog.Warn("Failed to decrypt Slack token, using raw value (may be unencrypted legacy value)", "error", err)
+ }
+ }
+
+ // Build message content
+ updateStatus := "No Update"
+ if updateInfo.HasUpdate {
+ updateStatus = "⚠️ Update Available"
+ }
+
+ message := fmt.Sprintf("🔔 *Container Image Update Notification*\n\n"+
+ "*Image:* %s\n"+
+ "*Status:* %s\n"+
+ "*Update Type:* %s\n",
+ imageRef, updateStatus, updateInfo.UpdateType)
+
+ if updateInfo.CurrentDigest != "" {
+ message += fmt.Sprintf("*Current Digest:* `%s`\n", updateInfo.CurrentDigest)
+ }
+ if updateInfo.LatestDigest != "" {
+ message += fmt.Sprintf("*Latest Digest:* `%s`\n", updateInfo.LatestDigest)
+ }
+
+ if err := notifications.SendSlack(ctx, slackConfig, message); err != nil {
+ return fmt.Errorf("failed to send Slack notification: %w", err)
+ }
+
+ return nil
+}
+
+func (s *NotificationService) sendSlackContainerUpdateNotification(ctx context.Context, containerName, imageRef, oldDigest, newDigest string, config models.JSON) error {
+ var slackConfig models.SlackConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Slack config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &slackConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Slack config: %w", err)
+ }
+
+ if slackConfig.Token == "" {
+ return fmt.Errorf("slack token not configured")
+ }
+
+ // Decrypt token if encrypted
+ if slackConfig.Token != "" {
+ if decrypted, err := crypto.Decrypt(slackConfig.Token); err == nil {
+ slackConfig.Token = decrypted
+ } else {
+ slog.Warn("Failed to decrypt Slack token, using raw value (may be unencrypted legacy value)", "error", err)
+ }
+ }
+
+ // Build message content
+ message := fmt.Sprintf("✅ *Container Successfully Updated*\n\n"+
+ "Your container has been updated with the latest image version.\n\n"+
+ "*Container:* %s\n"+
+ "*Image:* %s\n"+
+ "*Status:* ✅ Updated Successfully\n",
+ containerName, imageRef)
+
+ if oldDigest != "" {
+ message += fmt.Sprintf("*Previous Version:* `%s`\n", oldDigest)
+ }
+ if newDigest != "" {
+ message += fmt.Sprintf("*Current Version:* `%s`\n", newDigest)
+ }
+
+ if err := notifications.SendSlack(ctx, slackConfig, message); err != nil {
+ return fmt.Errorf("failed to send Slack notification: %w", err)
+ }
+
+ return nil
+}
+
+func (s *NotificationService) sendBatchSlackNotification(ctx context.Context, updates map[string]*imageupdate.Response, config models.JSON) error {
+ var slackConfig models.SlackConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal slack config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &slackConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal slack config: %w", err)
+ }
+
+ // Decrypt token if encrypted
+ if decrypted, err := crypto.Decrypt(slackConfig.Token); err == nil {
+ slackConfig.Token = decrypted
+ }
+
+ // Build batch message content
+ title := "*Container Image Updates Available*"
+ description := fmt.Sprintf("%d container image(s) have updates available.", len(updates))
+ if len(updates) == 1 {
+ description = "1 container image has an update available."
+ }
+
+ message := fmt.Sprintf("%s\n\n%s\n\n", title, description)
+
+ for imageRef, update := range updates {
+ message += fmt.Sprintf("*%s*\n"+
+ "• *Type:* %s\n"+
+ "• *Current:* `%s`\n"+
+ "• *Latest:* `%s`\n\n",
+ imageRef,
+ update.UpdateType,
+ update.CurrentDigest,
+ update.LatestDigest,
+ )
+ }
+
+ if err := notifications.SendSlack(ctx, slackConfig, message); err != nil {
+ return fmt.Errorf("failed to send batch Slack notification: %w", err)
+ }
+
+ return nil
+}
+
+func (s *NotificationService) sendNtfyNotification(ctx context.Context, imageRef string, updateInfo *imageupdate.Response, config models.JSON) error {
+ var ntfyConfig models.NtfyConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Ntfy config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &ntfyConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Ntfy config: %w", err)
+ }
+
+ if ntfyConfig.Topic == "" {
+ return fmt.Errorf("ntfy topic is required")
+ }
+
+ // Decrypt password if encrypted
+ if ntfyConfig.Password != "" {
+ if decrypted, err := crypto.Decrypt(ntfyConfig.Password); err == nil {
+ ntfyConfig.Password = decrypted
+ } else {
+ slog.Warn("Failed to decrypt Ntfy password, using raw value (may be unencrypted legacy value)", "error", err)
+ }
+ }
+
+ // Build message content
+ updateStatus := "No Update"
+ if updateInfo.HasUpdate {
+ updateStatus = "⚠️ Update Available"
+ }
+
+ message := fmt.Sprintf("🔔 Container Image Update Notification\n\n"+
+ "Image: %s\n"+
+ "Status: %s\n"+
+ "Update Type: %s\n",
+ imageRef, updateStatus, updateInfo.UpdateType)
+
+ if updateInfo.CurrentDigest != "" {
+ message += fmt.Sprintf("Current Digest: %s\n", updateInfo.CurrentDigest)
+ }
+ if updateInfo.LatestDigest != "" {
+ message += fmt.Sprintf("Latest Digest: %s\n", updateInfo.LatestDigest)
+ }
+
+ if err := notifications.SendNtfy(ctx, ntfyConfig, message); err != nil {
+ return fmt.Errorf("failed to send Ntfy notification: %w", err)
+ }
+
+ return nil
+}
+
+func (s *NotificationService) sendNtfyContainerUpdateNotification(ctx context.Context, containerName, imageRef, oldDigest, newDigest string, config models.JSON) error {
+ var ntfyConfig models.NtfyConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Ntfy config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &ntfyConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Ntfy config: %w", err)
+ }
+
+ if ntfyConfig.Topic == "" {
+ return fmt.Errorf("ntfy topic is required")
+ }
+
+ // Decrypt password if encrypted
+ if ntfyConfig.Password != "" {
+ if decrypted, err := crypto.Decrypt(ntfyConfig.Password); err == nil {
+ ntfyConfig.Password = decrypted
+ } else {
+ slog.Warn("Failed to decrypt Ntfy password, using raw value (may be unencrypted legacy value)", "error", err)
+ }
+ }
+
+ // Build message content
+ message := fmt.Sprintf("✅ Container Successfully Updated\n\n"+
+ "Your container has been updated with the latest image version.\n\n"+
+ "Container: %s\n"+
+ "Image: %s\n"+
+ "Status: ✅ Updated Successfully\n",
+ containerName, imageRef)
+
+ if oldDigest != "" {
+ message += fmt.Sprintf("Previous Version: %s\n", oldDigest)
+ }
+ if newDigest != "" {
+ message += fmt.Sprintf("Current Version: %s\n", newDigest)
+ }
+
+ if err := notifications.SendNtfy(ctx, ntfyConfig, message); err != nil {
+ return fmt.Errorf("failed to send Ntfy notification: %w", err)
+ }
+
+ return nil
+}
+
+func (s *NotificationService) sendBatchNtfyNotification(ctx context.Context, updates map[string]*imageupdate.Response, config models.JSON) error {
+ var ntfyConfig models.NtfyConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal ntfy config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &ntfyConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal ntfy config: %w", err)
+ }
+
+ // Decrypt password if encrypted
+ if ntfyConfig.Password != "" {
+ if decrypted, err := crypto.Decrypt(ntfyConfig.Password); err == nil {
+ ntfyConfig.Password = decrypted
+ }
+ }
+
+ // Build batch message content
+ title := "Container Image Updates Available"
+ description := fmt.Sprintf("%d container image(s) have updates available.", len(updates))
+ if len(updates) == 1 {
+ description = "1 container image has an update available."
+ }
+
+ message := fmt.Sprintf("%s\n\n%s\n\n", title, description)
+
+ for imageRef, update := range updates {
+ message += fmt.Sprintf("%s\n"+
+ "• Type: %s\n"+
+ "• Current: %s\n"+
+ "• Latest: %s\n\n",
+ imageRef,
+ update.UpdateType,
+ update.CurrentDigest,
+ update.LatestDigest,
+ )
+ }
+
+ if err := notifications.SendNtfy(ctx, ntfyConfig, message); err != nil {
+ return fmt.Errorf("failed to send batch Ntfy notification: %w", err)
+ }
+
+ return nil
+}
+
+func (s *NotificationService) sendGenericNotification(ctx context.Context, imageRef string, updateInfo *imageupdate.Response, config models.JSON) error {
+ var genericConfig models.GenericConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Generic config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &genericConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Generic config: %w", err)
}
- return digest
+
+ if genericConfig.WebhookURL == "" {
+ return fmt.Errorf("webhook URL not configured")
+ }
+
+ // Build message content
+ updateStatus := "No Update"
+ if updateInfo.HasUpdate {
+ updateStatus = "Update Available"
+ }
+
+ message := fmt.Sprintf("Container Image Update Notification\n\n"+
+ "Image: %s\n"+
+ "Status: %s\n"+
+ "Update Type: %s\n",
+ imageRef, updateStatus, updateInfo.UpdateType)
+
+ if updateInfo.CurrentDigest != "" {
+ message += fmt.Sprintf("Current Digest: %s\n", updateInfo.CurrentDigest)
+ }
+ if updateInfo.LatestDigest != "" {
+ message += fmt.Sprintf("Latest Digest: %s\n", updateInfo.LatestDigest)
+ }
+
+ // Use SendGenericWithTitle to include a title
+ title := "Container Image Update"
+ if err := notifications.SendGenericWithTitle(ctx, genericConfig, title, message); err != nil {
+ return fmt.Errorf("failed to send Generic webhook notification: %w", err)
+ }
+
+ return nil
+}
+
+func (s *NotificationService) sendGenericContainerUpdateNotification(ctx context.Context, containerName, imageRef, oldDigest, newDigest string, config models.JSON) error {
+ var genericConfig models.GenericConfig
+ configBytes, err := json.Marshal(config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Generic config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &genericConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal Generic config: %w", err)
+ }
+
+ if genericConfig.WebhookURL == "" {
+ return fmt.Errorf("webhook URL not configured")
+ }
+
+ // Build message content
+ message := fmt.Sprintf("Container Successfully Updated\n\n"+
+ "Your container has been updated with the latest image version.\n\n"+
+ "Container: %s\n"+
+ "Image: %s\n"+
+ "Status: Updated Successfully\n",
+ containerName, imageRef)
+
+ if oldDigest != "" {
+ message += fmt.Sprintf("Previous Version: %s\n", oldDigest)
+ }
+ if newDigest != "" {
+ message += fmt.Sprintf("Current Version: %s\n", newDigest)
+ }
+
+ // Use SendGenericWithTitle to include a title
+ title := "Container Updated"
+ if err := notifications.SendGenericWithTitle(ctx, genericConfig, title, message); err != nil {
+ return fmt.Errorf("failed to send Generic webhook notification: %w", err)
+ }
+
+ return nil
}
-// validateWebhookURL validates that the webhook URL is a valid Discord webhook URL
-// This prevents SSRF attacks by ensuring the URL points to Discord's API
-func validateWebhookURL(webhookURL string) error {
- parsedURL, err := url.Parse(webhookURL)
+func (s *NotificationService) sendBatchGenericNotification(ctx context.Context, updates map[string]*imageupdate.Response, config models.JSON) error {
+ var genericConfig models.GenericConfig
+ configBytes, err := json.Marshal(config)
if err != nil {
- return fmt.Errorf("failed to parse webhook URL: %w", err)
+ return fmt.Errorf("failed to marshal generic config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &genericConfig); err != nil {
+ return fmt.Errorf("failed to unmarshal generic config: %w", err)
}
- // Ensure it's HTTPS
- if parsedURL.Scheme != "https" {
- return fmt.Errorf("webhook URL must use HTTPS")
+ if genericConfig.WebhookURL == "" {
+ return fmt.Errorf("webhook URL not configured")
+ }
+
+ // Build batch message content
+ title := "Container Image Updates Available"
+ description := fmt.Sprintf("%d container image(s) have updates available.", len(updates))
+ if len(updates) == 1 {
+ description = "1 container image has an update available."
+ }
+
+ message := fmt.Sprintf("%s\n\n", description)
+
+ for imageRef, update := range updates {
+ message += fmt.Sprintf("%s\n"+
+ "• Type: %s\n"+
+ "• Current: %s\n"+
+ "• Latest: %s\n\n",
+ imageRef,
+ update.UpdateType,
+ update.CurrentDigest,
+ update.LatestDigest,
+ )
}
- // Validate it's a Discord webhook URL
- validHosts := []string{
- "discord.com",
- "discordapp.com",
+ if err := notifications.SendGenericWithTitle(ctx, genericConfig, title, message); err != nil {
+ return fmt.Errorf("failed to send batch Generic webhook notification: %w", err)
}
- isValid := false
- for _, validHost := range validHosts {
- if parsedURL.Host == validHost || strings.HasSuffix(parsedURL.Host, "."+validHost) {
- isValid = true
- break
+ return nil
+}
+
+// MigrateDiscordWebhookUrlToFields migrates legacy Discord webhookUrl to separate webhookId and token fields.
+// This should be called during bootstrap to ensure existing Discord configurations are preserved.
+func (s *NotificationService) MigrateDiscordWebhookUrlToFields(ctx context.Context) error {
+ var setting models.NotificationSettings
+ err := s.db.WithContext(ctx).Where("provider = ?", models.NotificationProviderDiscord).First(&setting).Error
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ // No Discord config exists, nothing to migrate
+ return nil
}
+ return fmt.Errorf("failed to query Discord settings: %w", err)
+ }
+
+ var discordConfig models.DiscordConfig
+ configBytes, err := json.Marshal(setting.Config)
+ if err != nil {
+ return fmt.Errorf("failed to marshal Discord config: %w", err)
+ }
+ if err := json.Unmarshal(configBytes, &discordConfig); err != nil {
+ slog.WarnContext(ctx, "Failed to parse Discord config for migration", "error", err)
+ return nil
}
- if !isValid {
- return fmt.Errorf("webhook URL must be a Discord webhook URL")
+ // Check if already migrated (has webhookId and token)
+ if discordConfig.WebhookID != "" && discordConfig.Token != "" {
+ slog.DebugContext(ctx, "Discord config already migrated, skipping")
+ return nil
+ }
+
+ // Check for legacy webhookUrl field
+ var legacyConfig struct {
+ WebhookUrl string `json:"webhookUrl"`
+ Username string `json:"username,omitempty"`
+ AvatarURL string `json:"avatarUrl,omitempty"`
+ Events map[models.NotificationEventType]bool `json:"events,omitempty"`
+ }
+ if err := json.Unmarshal(configBytes, &legacyConfig); err != nil {
+ slog.WarnContext(ctx, "Failed to parse legacy Discord config structure", "error", err)
+ return nil
+ }
+
+ if legacyConfig.WebhookUrl == "" {
+ slog.DebugContext(ctx, "No legacy webhookUrl to migrate")
+ return nil
+ }
+
+ // Parse webhook URL: https://discord.com/api/webhooks/{id}/{token}
+ parts := strings.Split(legacyConfig.WebhookUrl, "/webhooks/")
+ if len(parts) != 2 {
+ slog.WarnContext(ctx, "Invalid Discord webhook URL format, skipping migration", "url", legacyConfig.WebhookUrl)
+ return nil
+ }
+
+ webhookParts := strings.Split(parts[1], "/")
+ if len(webhookParts) != 2 {
+ slog.WarnContext(ctx, "Invalid Discord webhook URL format, skipping migration", "url", legacyConfig.WebhookUrl)
+ return nil
+ }
+
+ webhookID := webhookParts[0]
+ token := webhookParts[1]
+
+ slog.InfoContext(ctx, "Migrating legacy Discord webhookUrl to webhookId and token")
+
+ // Encrypt token before storing
+ encryptedToken, err := crypto.Encrypt(token)
+ if err != nil {
+ return fmt.Errorf("failed to encrypt Discord token: %w", err)
+ }
+
+ // Update with new structure
+ newConfig := models.DiscordConfig{
+ WebhookID: webhookID,
+ Token: encryptedToken,
+ Username: legacyConfig.Username,
+ AvatarURL: legacyConfig.AvatarURL,
+ Events: legacyConfig.Events,
+ }
+
+ var configMap models.JSON
+ newConfigBytes, err := json.Marshal(newConfig)
+ if err != nil {
+ return fmt.Errorf("failed to marshal new Discord config: %w", err)
+ }
+ if err = json.Unmarshal(newConfigBytes, &configMap); err != nil {
+ return fmt.Errorf("failed to unmarshal new Discord config to JSON: %w", err)
}
- // Validate it's a webhook path
- if !strings.HasPrefix(parsedURL.Path, "/api/webhooks/") {
- return fmt.Errorf("invalid Discord webhook path")
+ setting.Config = configMap
+ if err = s.db.WithContext(ctx).Save(&setting).Error; err != nil {
+ return fmt.Errorf("failed to save migrated Discord config: %w", err)
}
+ slog.InfoContext(ctx, "Successfully migrated Discord config")
return nil
}
diff --git a/backend/internal/services/notification_service_test.go b/backend/internal/services/notification_service_test.go
new file mode 100644
index 000000000..804bd9a44
--- /dev/null
+++ b/backend/internal/services/notification_service_test.go
@@ -0,0 +1,301 @@
+package services
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+
+ glsqlite "github.com/glebarez/sqlite"
+ "github.com/stretchr/testify/require"
+ "gorm.io/gorm"
+
+ "github.com/getarcaneapp/arcane/backend/internal/config"
+ "github.com/getarcaneapp/arcane/backend/internal/database"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/crypto"
+)
+
+func setupNotificationTestDB(t *testing.T) *database.DB {
+ t.Helper()
+ db, err := gorm.Open(glsqlite.Open(":memory:"), &gorm.Config{})
+ require.NoError(t, err)
+ require.NoError(t, db.AutoMigrate(&models.NotificationSettings{}))
+
+ // Initialize crypto for tests (requires 32+ byte key)
+ testCfg := &config.Config{
+ EncryptionKey: "test-encryption-key-for-testing-32bytes-min",
+ Environment: "test",
+ }
+ crypto.InitEncryption(testCfg)
+
+ return &database.DB{DB: db}
+}
+
+func TestNotificationService_MigrateDiscordWebhookUrlToFields(t *testing.T) {
+ ctx := context.Background()
+ db := setupNotificationTestDB(t)
+ cfg := &config.Config{}
+ svc := NewNotificationService(db, cfg)
+
+ // Create legacy Discord config with webhookUrl
+ legacyConfig := map[string]interface{}{
+ "webhookUrl": "https://discord.com/api/webhooks/123456789/abcdef123456",
+ "username": "Arcane Bot",
+ "avatarUrl": "https://example.com/avatar.png",
+ "events": map[string]bool{
+ "image_update": true,
+ "container_update": false,
+ },
+ }
+
+ configBytes, err := json.Marshal(legacyConfig)
+ require.NoError(t, err)
+
+ var configJSON models.JSON
+ require.NoError(t, json.Unmarshal(configBytes, &configJSON))
+
+ setting := models.NotificationSettings{
+ Provider: models.NotificationProviderDiscord,
+ Enabled: true,
+ Config: configJSON,
+ }
+ require.NoError(t, db.Create(&setting).Error)
+
+ // Run migration
+ err = svc.MigrateDiscordWebhookUrlToFields(ctx)
+ require.NoError(t, err)
+
+ // Verify migration results
+ var migratedSetting models.NotificationSettings
+ require.NoError(t, db.Where("provider = ?", models.NotificationProviderDiscord).First(&migratedSetting).Error)
+
+ var discordConfig models.DiscordConfig
+ configBytes, err = json.Marshal(migratedSetting.Config)
+ require.NoError(t, err)
+ require.NoError(t, json.Unmarshal(configBytes, &discordConfig))
+
+ // Verify webhookId and token were extracted
+ require.Equal(t, "123456789", discordConfig.WebhookID)
+ require.NotEmpty(t, discordConfig.Token)
+
+ // Verify token is encrypted and can be decrypted
+ decryptedToken, err := crypto.Decrypt(discordConfig.Token)
+ require.NoError(t, err)
+ require.Equal(t, "abcdef123456", decryptedToken)
+
+ // Verify other fields were preserved
+ require.Equal(t, "Arcane Bot", discordConfig.Username)
+ require.Equal(t, "https://example.com/avatar.png", discordConfig.AvatarURL)
+ require.True(t, discordConfig.Events[models.NotificationEventImageUpdate])
+ require.False(t, discordConfig.Events[models.NotificationEventContainerUpdate])
+}
+
+func TestNotificationService_MigrateDiscordWebhookUrlToFields_SkipsIfAlreadyMigrated(t *testing.T) {
+ ctx := context.Background()
+ db := setupNotificationTestDB(t)
+ cfg := &config.Config{}
+ svc := NewNotificationService(db, cfg)
+
+ // Create already-migrated config with webhookId and token
+ encryptedToken, err := crypto.Encrypt("already-migrated-token")
+ require.NoError(t, err)
+
+ migratedConfig := models.DiscordConfig{
+ WebhookID: "999999999",
+ Token: encryptedToken,
+ Username: "Already Migrated",
+ }
+
+ configBytes, err := json.Marshal(migratedConfig)
+ require.NoError(t, err)
+
+ var configJSON models.JSON
+ require.NoError(t, json.Unmarshal(configBytes, &configJSON))
+
+ setting := models.NotificationSettings{
+ Provider: models.NotificationProviderDiscord,
+ Enabled: true,
+ Config: configJSON,
+ }
+ require.NoError(t, db.Create(&setting).Error)
+
+ // Run migration - should skip
+ err = svc.MigrateDiscordWebhookUrlToFields(ctx)
+ require.NoError(t, err)
+
+ // Verify config was NOT changed
+ var unchangedSetting models.NotificationSettings
+ require.NoError(t, db.Where("provider = ?", models.NotificationProviderDiscord).First(&unchangedSetting).Error)
+
+ var discordConfig models.DiscordConfig
+ configBytes, err = json.Marshal(unchangedSetting.Config)
+ require.NoError(t, err)
+ require.NoError(t, json.Unmarshal(configBytes, &discordConfig))
+
+ require.Equal(t, "999999999", discordConfig.WebhookID)
+ require.Equal(t, encryptedToken, discordConfig.Token)
+ require.Equal(t, "Already Migrated", discordConfig.Username)
+}
+
+func TestNotificationService_MigrateDiscordWebhookUrlToFields_NoDiscordConfig(t *testing.T) {
+ ctx := context.Background()
+ db := setupNotificationTestDB(t)
+ cfg := &config.Config{}
+ svc := NewNotificationService(db, cfg)
+
+ // No Discord config exists - migration should not error
+ err := svc.MigrateDiscordWebhookUrlToFields(ctx)
+ require.NoError(t, err)
+
+ // Verify no settings were created
+ var count int64
+ require.NoError(t, db.Model(&models.NotificationSettings{}).Count(&count).Error)
+ require.Equal(t, int64(0), count)
+}
+
+func TestNotificationService_MigrateDiscordWebhookUrlToFields_InvalidWebhookUrl(t *testing.T) {
+ ctx := context.Background()
+ db := setupNotificationTestDB(t)
+ cfg := &config.Config{}
+ svc := NewNotificationService(db, cfg)
+
+ testCases := []struct {
+ name string
+ webhookUrl string
+ }{
+ {
+ name: "missing webhooks path",
+ webhookUrl: "https://discord.com/api/other/123456789/abcdef",
+ },
+ {
+ name: "incomplete webhook path",
+ webhookUrl: "https://discord.com/api/webhooks/123456789",
+ },
+ {
+ name: "empty webhook url",
+ webhookUrl: "",
+ },
+ }
+
+ for _, tc := range testCases {
+ t.Run(tc.name, func(t *testing.T) {
+ // Clean up before each sub-test
+ db.Exec("DELETE FROM notification_settings")
+
+ legacyConfig := map[string]interface{}{
+ "webhookUrl": tc.webhookUrl,
+ }
+
+ configBytes, err := json.Marshal(legacyConfig)
+ require.NoError(t, err)
+
+ var configJSON models.JSON
+ require.NoError(t, json.Unmarshal(configBytes, &configJSON))
+
+ setting := models.NotificationSettings{
+ Provider: models.NotificationProviderDiscord,
+ Enabled: true,
+ Config: configJSON,
+ }
+ require.NoError(t, db.Create(&setting).Error)
+
+ // Migration should not error but should skip invalid URLs
+ err = svc.MigrateDiscordWebhookUrlToFields(ctx)
+ require.NoError(t, err)
+
+ // Verify config was not changed
+ var unchangedSetting models.NotificationSettings
+ require.NoError(t, db.Where("provider = ?", models.NotificationProviderDiscord).First(&unchangedSetting).Error)
+
+ var resultConfig map[string]interface{}
+ configBytes, err = json.Marshal(unchangedSetting.Config)
+ require.NoError(t, err)
+ require.NoError(t, json.Unmarshal(configBytes, &resultConfig))
+
+ // Should still have webhookUrl (not migrated)
+ if tc.webhookUrl != "" {
+ require.Equal(t, tc.webhookUrl, resultConfig["webhookUrl"])
+ }
+ })
+ }
+}
+
+func TestNotificationService_MigrateDiscordWebhookUrlToFields_EmptyConfig(t *testing.T) {
+ ctx := context.Background()
+ db := setupNotificationTestDB(t)
+ cfg := &config.Config{}
+ svc := NewNotificationService(db, cfg)
+
+ // Create Discord setting with empty config
+ setting := models.NotificationSettings{
+ Provider: models.NotificationProviderDiscord,
+ Enabled: false,
+ Config: models.JSON{},
+ }
+ require.NoError(t, db.Create(&setting).Error)
+
+ // Migration should not error
+ err := svc.MigrateDiscordWebhookUrlToFields(ctx)
+ require.NoError(t, err)
+
+ // Verify config remains empty
+ var unchangedSetting models.NotificationSettings
+ require.NoError(t, db.Where("provider = ?", models.NotificationProviderDiscord).First(&unchangedSetting).Error)
+ require.Empty(t, unchangedSetting.Config)
+}
+
+func TestNotificationService_MigrateDiscordWebhookUrlToFields_PreservesAllFields(t *testing.T) {
+ ctx := context.Background()
+ db := setupNotificationTestDB(t)
+ cfg := &config.Config{}
+ svc := NewNotificationService(db, cfg)
+
+ // Create legacy config with all optional fields
+ legacyConfig := map[string]interface{}{
+ "webhookUrl": "https://discord.com/api/webhooks/111222333/token444555",
+ "username": "Custom Bot Name",
+ "avatarUrl": "https://cdn.example.com/bot-avatar.jpg",
+ "events": map[string]bool{
+ "image_update": false,
+ "container_update": true,
+ },
+ }
+
+ configBytes, err := json.Marshal(legacyConfig)
+ require.NoError(t, err)
+
+ var configJSON models.JSON
+ require.NoError(t, json.Unmarshal(configBytes, &configJSON))
+
+ setting := models.NotificationSettings{
+ Provider: models.NotificationProviderDiscord,
+ Enabled: true,
+ Config: configJSON,
+ }
+ require.NoError(t, db.Create(&setting).Error)
+
+ // Run migration
+ err = svc.MigrateDiscordWebhookUrlToFields(ctx)
+ require.NoError(t, err)
+
+ // Verify all fields were preserved
+ var migratedSetting models.NotificationSettings
+ require.NoError(t, db.Where("provider = ?", models.NotificationProviderDiscord).First(&migratedSetting).Error)
+
+ var discordConfig models.DiscordConfig
+ configBytes, err = json.Marshal(migratedSetting.Config)
+ require.NoError(t, err)
+ require.NoError(t, json.Unmarshal(configBytes, &discordConfig))
+
+ require.Equal(t, "111222333", discordConfig.WebhookID)
+ require.NotEmpty(t, discordConfig.Token)
+
+ decryptedToken, err := crypto.Decrypt(discordConfig.Token)
+ require.NoError(t, err)
+ require.Equal(t, "token444555", decryptedToken)
+
+ require.Equal(t, "Custom Bot Name", discordConfig.Username)
+ require.Equal(t, "https://cdn.example.com/bot-avatar.jpg", discordConfig.AvatarURL)
+ require.False(t, discordConfig.Events[models.NotificationEventImageUpdate])
+ require.True(t, discordConfig.Events[models.NotificationEventContainerUpdate])
+}
diff --git a/backend/internal/utils/bootstrap_util.go b/backend/internal/utils/bootstrap_util.go
index 12ad7a98f..78f839be1 100644
--- a/backend/internal/utils/bootstrap_util.go
+++ b/backend/internal/utils/bootstrap_util.go
@@ -55,7 +55,7 @@ func TestDockerConnection(ctx context.Context, testFunc func(context.Context) er
}
}
-func InitializeNonAgentFeatures(ctx context.Context, cfg *config.Config, createAdminFunc func(context.Context) error, migrateOidcFunc func(context.Context) error) {
+func InitializeNonAgentFeatures(ctx context.Context, cfg *config.Config, createAdminFunc func(context.Context) error, migrateOidcFunc func(context.Context) error, migrateDiscordFunc func(context.Context) error) {
if cfg.AgentMode {
return
}
@@ -70,4 +70,11 @@ func InitializeNonAgentFeatures(ctx context.Context, cfg *config.Config, createA
slog.WarnContext(ctx, "Failed to migrate OIDC config to individual fields", "error", err.Error())
}
}
+
+ // Migrate legacy Discord webhookUrl to separate webhookId and token fields
+ if migrateDiscordFunc != nil {
+ if err := migrateDiscordFunc(ctx); err != nil {
+ slog.WarnContext(ctx, "Failed to migrate Discord webhook config", "error", err.Error())
+ }
+ }
}
diff --git a/backend/internal/utils/notifications/discord_sender.go b/backend/internal/utils/notifications/discord_sender.go
new file mode 100644
index 000000000..cb201a5ad
--- /dev/null
+++ b/backend/internal/utils/notifications/discord_sender.go
@@ -0,0 +1,51 @@
+package notifications
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/nicholas-fedor/shoutrrr"
+ "github.com/nicholas-fedor/shoutrrr/pkg/services/chat/discord"
+)
+
+// BuildDiscordURL converts DiscordConfig to Shoutrrr URL format using shoutrrr's Config
+func BuildDiscordURL(config models.DiscordConfig) (string, error) {
+ discordConfig := &discord.Config{
+ WebhookID: config.WebhookID,
+ Token: config.Token,
+ Username: config.Username,
+ Avatar: config.AvatarURL,
+ }
+
+ url := discordConfig.GetURL()
+ return url.String(), nil
+}
+
+// SendDiscord sends a message via Shoutrrr Discord using proper service configuration
+func SendDiscord(ctx context.Context, config models.DiscordConfig, message string) error {
+ if config.WebhookID == "" {
+ return fmt.Errorf("discord webhook ID is empty")
+ }
+ if config.Token == "" {
+ return fmt.Errorf("discord token is empty")
+ }
+
+ shoutrrrURL, err := BuildDiscordURL(config)
+ if err != nil {
+ return fmt.Errorf("failed to build shoutrrr Discord URL: %w", err)
+ }
+
+ sender, err := shoutrrr.CreateSender(shoutrrrURL)
+ if err != nil {
+ return fmt.Errorf("failed to create shoutrrr Discord sender: %w", err)
+ }
+
+ errs := sender.Send(message, nil)
+ for _, err := range errs {
+ if err != nil {
+ return fmt.Errorf("failed to send Discord message via shoutrrr: %w", err)
+ }
+ }
+ return nil
+}
diff --git a/backend/internal/utils/notifications/discord_sender_test.go b/backend/internal/utils/notifications/discord_sender_test.go
new file mode 100644
index 000000000..b59f11657
--- /dev/null
+++ b/backend/internal/utils/notifications/discord_sender_test.go
@@ -0,0 +1,283 @@
+package notifications
+
+import (
+ "fmt"
+ "testing"
+
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestBuildDiscordURL(t *testing.T) {
+ tests := []struct {
+ name string
+ config models.DiscordConfig
+ check func(string) bool
+ }{
+ {
+ name: "basic webhook configuration",
+ config: models.DiscordConfig{
+ WebhookID: "123456789012345678",
+ Token: "abcdefghijklmnopqrstuvwxyz0123456789",
+ },
+ check: func(url string) bool {
+ return assert.Contains(t, url, "discord://") &&
+ assert.Contains(t, url, "abcdefghijklmnopqrstuvwxyz0123456789") &&
+ assert.Contains(t, url, "@123456789012345678")
+ },
+ },
+ {
+ name: "webhook with custom username",
+ config: models.DiscordConfig{
+ WebhookID: "987654321098765432",
+ Token: "token123456789abcdefghij",
+ Username: "Arcane Bot",
+ },
+ check: func(url string) bool {
+ return assert.Contains(t, url, "username=Arcane+Bot")
+ },
+ },
+ {
+ name: "webhook with avatar URL",
+ config: models.DiscordConfig{
+ WebhookID: "111222333444555666",
+ Token: "tokenXYZ",
+ AvatarURL: "https://example.com/avatar.png",
+ },
+ check: func(url string) bool {
+ return assert.Contains(t, url, "avatar=https%3A%2F%2Fexample.com%2Favatar.png")
+ },
+ },
+ {
+ name: "webhook with username and avatar",
+ config: models.DiscordConfig{
+ WebhookID: "123456789012345678",
+ Token: "abcdeftoken",
+ Username: "Custom Bot",
+ AvatarURL: "https://cdn.example.com/bot.jpg",
+ },
+ check: func(url string) bool {
+ return assert.Contains(t, url, "avatar=https%3A%2F%2Fcdn.example.com%2Fbot.jpg") &&
+ assert.Contains(t, url, "username=Custom+Bot")
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ gotURL, err := BuildDiscordURL(tt.config)
+ require.NoError(t, err)
+ tt.check(gotURL)
+ })
+ }
+}
+
+func TestBuildDiscordURL_WebhookIdTokenSplit(t *testing.T) {
+ tests := []struct {
+ name string
+ webhookID string
+ token string
+ wantID bool
+ wantToken bool
+ }{
+ {
+ name: "valid webhook ID and token",
+ webhookID: "123456789012345678",
+ token: "abcdefghijklmnopqrstuvwxyz",
+ wantID: true,
+ wantToken: true,
+ },
+ {
+ name: "numeric webhook ID",
+ webhookID: "999888777666555444",
+ token: "token-with-dashes",
+ wantID: true,
+ wantToken: true,
+ },
+ {
+ name: "long alphanumeric token",
+ webhookID: "123456789012345678",
+ token: "aB3dE5gH7jK9mN1pQ4sT6vX8zZ0cF2hJ5",
+ wantID: true,
+ wantToken: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ config := models.DiscordConfig{
+ WebhookID: tt.webhookID,
+ Token: tt.token,
+ }
+
+ gotURL, err := BuildDiscordURL(config)
+ require.NoError(t, err)
+
+ if tt.wantID {
+ assert.Contains(t, gotURL, tt.webhookID)
+ }
+ if tt.wantToken {
+ assert.Contains(t, gotURL, tt.token)
+ }
+
+ // Verify format: discord://token@webhookID
+ assert.Contains(t, gotURL, "discord://")
+ assert.Contains(t, gotURL, "@"+tt.webhookID)
+ })
+ }
+}
+
+func TestBuildDiscordURL_OptionalFields(t *testing.T) {
+ tests := []struct {
+ name string
+ config models.DiscordConfig
+ wantUsername bool
+ wantAvatar bool
+ }{
+ {
+ name: "no optional fields",
+ config: models.DiscordConfig{
+ WebhookID: "123456789012345678",
+ Token: "token123",
+ },
+ wantUsername: false,
+ wantAvatar: false,
+ },
+ {
+ name: "only username",
+ config: models.DiscordConfig{
+ WebhookID: "123456789012345678",
+ Token: "token123",
+ Username: "Bot Name",
+ },
+ wantUsername: true,
+ wantAvatar: false,
+ },
+ {
+ name: "only avatar",
+ config: models.DiscordConfig{
+ WebhookID: "123456789012345678",
+ Token: "token123",
+ AvatarURL: "https://example.com/avatar.png",
+ },
+ wantUsername: false,
+ wantAvatar: true,
+ },
+ {
+ name: "both username and avatar",
+ config: models.DiscordConfig{
+ WebhookID: "123456789012345678",
+ Token: "token123",
+ Username: "My Bot",
+ AvatarURL: "https://example.com/bot.png",
+ },
+ wantUsername: true,
+ wantAvatar: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ gotURL, err := BuildDiscordURL(tt.config)
+ require.NoError(t, err)
+
+ if tt.wantUsername {
+ assert.Contains(t, gotURL, "username=")
+ } else {
+ assert.NotContains(t, gotURL, "username=")
+ }
+
+ if tt.wantAvatar {
+ assert.Contains(t, gotURL, "avatar=")
+ } else {
+ assert.NotContains(t, gotURL, "avatar=")
+ }
+ })
+ }
+}
+
+func TestBuildDiscordURL_URLEncoding(t *testing.T) {
+ config := models.DiscordConfig{
+ WebhookID: "123456789012345678",
+ Token: "token123",
+ Username: "Bot with spaces & special chars!",
+ AvatarURL: "https://example.com/path/to/avatar.png?size=256",
+ }
+
+ gotURL, err := BuildDiscordURL(config)
+ require.NoError(t, err)
+
+ // Verify URL encoding for special characters
+ assert.Contains(t, gotURL, "username=Bot+with+spaces")
+ assert.Contains(t, gotURL, "avatar=https%3A%2F%2F")
+}
+
+func TestSendDiscord_Validation(t *testing.T) {
+ tests := []struct {
+ name string
+ config models.DiscordConfig
+ wantErr string
+ }{
+ {
+ name: "missing webhook ID",
+ config: models.DiscordConfig{
+ Token: "token123",
+ },
+ wantErr: "discord webhook ID is empty",
+ },
+ {
+ name: "missing token",
+ config: models.DiscordConfig{
+ WebhookID: "123456789012345678",
+ },
+ wantErr: "discord token is empty",
+ },
+ {
+ name: "empty webhook ID",
+ config: models.DiscordConfig{
+ WebhookID: "",
+ Token: "token123",
+ },
+ wantErr: "discord webhook ID is empty",
+ },
+ {
+ name: "empty token",
+ config: models.DiscordConfig{
+ WebhookID: "123456789012345678",
+ Token: "",
+ },
+ wantErr: "discord token is empty",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := validateDiscordConfig(tt.config)
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), tt.wantErr)
+ })
+ }
+}
+
+func TestSendDiscord_ValidConfiguration(t *testing.T) {
+ config := models.DiscordConfig{
+ WebhookID: "123456789012345678",
+ Token: "valid-token-123",
+ Username: "Test Bot",
+ }
+
+ err := validateDiscordConfig(config)
+ assert.NoError(t, err)
+}
+
+// Helper function to extract validation logic for testing
+func validateDiscordConfig(config models.DiscordConfig) error {
+ if config.WebhookID == "" {
+ return fmt.Errorf("discord webhook ID is empty")
+ }
+ if config.Token == "" {
+ return fmt.Errorf("discord token is empty")
+ }
+ return nil
+}
diff --git a/backend/internal/utils/notifications/email_sender.go b/backend/internal/utils/notifications/email_sender.go
new file mode 100644
index 000000000..b236bf736
--- /dev/null
+++ b/backend/internal/utils/notifications/email_sender.go
@@ -0,0 +1,78 @@
+package notifications
+
+import (
+ "context"
+ "fmt"
+ "net/url"
+ "strings"
+
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/nicholas-fedor/shoutrrr"
+ shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types"
+)
+
+// BuildSMTPURL converts EmailConfig to Shoutrrr URL format
+// URL example: smtp://user:pass@host:port/?fromAddress=...&toAddresses=...&useHTML=yes
+func BuildSMTPURL(config models.EmailConfig) (string, error) {
+ u := &url.URL{
+ Scheme: "smtp",
+ Host: fmt.Sprintf("%s:%d", config.SMTPHost, config.SMTPPort),
+ Path: "/",
+ }
+
+ if config.SMTPUsername != "" || config.SMTPPassword != "" {
+ u.User = url.UserPassword(config.SMTPUsername, config.SMTPPassword)
+ }
+
+ q := u.Query()
+ q.Set("fromAddress", config.FromAddress)
+ q.Set("toAddresses", strings.Join(config.ToAddresses, ","))
+ q.Set("useHTML", "yes")
+
+ // TLS Mode Mapping
+ // none -> encryption=None, useStartTLS=no
+ // starttls -> encryption=ExplicitTLS, useStartTLS=yes
+ // ssl -> encryption=ImplicitTLS, useStartTLS=no
+ switch config.TLSMode {
+ case models.EmailTLSModeNone:
+ q.Set("encryption", "None")
+ q.Set("useStartTLS", "no")
+ case models.EmailTLSModeStartTLS:
+ q.Set("encryption", "ExplicitTLS")
+ q.Set("useStartTLS", "yes")
+ case models.EmailTLSModeSSL:
+ q.Set("encryption", "ImplicitTLS")
+ q.Set("useStartTLS", "no")
+ default:
+ q.Set("encryption", "None")
+ q.Set("useStartTLS", "no")
+ }
+
+ u.RawQuery = q.Encode()
+ return u.String(), nil
+}
+
+// SendEmail sends pre-rendered HTML via Shoutrrr
+func SendEmail(ctx context.Context, config models.EmailConfig, subject, htmlBody string) error {
+ shoutrrrURL, err := BuildSMTPURL(config)
+ if err != nil {
+ return fmt.Errorf("failed to build shoutrrr URL: %w", err)
+ }
+
+ sender, err := shoutrrr.CreateSender(shoutrrrURL)
+ if err != nil {
+ return fmt.Errorf("failed to create shoutrrr sender: %w", err)
+ }
+
+ params := shoutrrrTypes.Params{
+ "subject": subject,
+ }
+
+ errs := sender.Send(htmlBody, &params)
+ for _, err := range errs {
+ if err != nil {
+ return fmt.Errorf("failed to send email via shoutrrr: %w", err)
+ }
+ }
+ return nil
+}
diff --git a/backend/internal/utils/notifications/email_sender_test.go b/backend/internal/utils/notifications/email_sender_test.go
new file mode 100644
index 000000000..4514e5e79
--- /dev/null
+++ b/backend/internal/utils/notifications/email_sender_test.go
@@ -0,0 +1,63 @@
+package notifications
+
+import (
+ "testing"
+
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestBuildSMTPURL(t *testing.T) {
+ tests := []struct {
+ name string
+ config models.EmailConfig
+ wantURL string
+ }{
+ {
+ name: "Basic SMTP no auth, no TLS",
+ config: models.EmailConfig{
+ SMTPHost: "smtp.example.com",
+ SMTPPort: 25,
+ FromAddress: "[email protected]",
+ ToAddresses: []string{"[email protected]"},
+ TLSMode: models.EmailTLSModeNone,
+ },
+ wantURL: "smtp://smtp.example.com:25/?encryption=None&fromAddress=from%40example.com&toAddresses=to%40example.com&useHTML=yes&useStartTLS=no",
+ },
+ {
+ name: "SMTP with auth and starttls",
+ config: models.EmailConfig{
+ SMTPHost: "smtp.example.com",
+ SMTPPort: 587,
+ SMTPUsername: "user",
+ SMTPPassword: "password",
+ FromAddress: "[email protected]",
+ ToAddresses: []string{"[email protected]", "[email protected]"},
+ TLSMode: models.EmailTLSModeStartTLS,
+ },
+ wantURL: "smtp://user:[email protected]:587/?encryption=ExplicitTLS&fromAddress=from%40example.com&toAddresses=to1%40example.com%2Cto2%40example.com&useHTML=yes&useStartTLS=yes",
+ },
+ {
+ name: "SMTP with SSL/TLS and special characters in credentials",
+ config: models.EmailConfig{
+ SMTPHost: "smtp.example.com",
+ SMTPPort: 465,
+ SMTPUsername: "[email protected]",
+ SMTPPassword: "pass/word!",
+ FromAddress: "[email protected]",
+ ToAddresses: []string{"[email protected]"},
+ TLSMode: models.EmailTLSModeSSL,
+ },
+ wantURL: "smtp://user%40example.com:pass%2Fword%[email protected]:465/?encryption=ImplicitTLS&fromAddress=from%40example.com&toAddresses=to%40example.com&useHTML=yes&useStartTLS=no",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ gotURL, err := BuildSMTPURL(tt.config)
+ require.NoError(t, err)
+ assert.Equal(t, tt.wantURL, gotURL)
+ })
+ }
+}
diff --git a/backend/internal/utils/notifications/email_util.go b/backend/internal/utils/notifications/email_util.go
deleted file mode 100644
index 2cd1435d1..000000000
--- a/backend/internal/utils/notifications/email_util.go
+++ /dev/null
@@ -1,217 +0,0 @@
-package notifications
-
-import (
- "bytes"
- "context"
- "crypto/tls"
- "errors"
- "fmt"
- "mime/quotedprintable"
- "os"
- "strings"
- "time"
-
- "github.com/emersion/go-sasl"
- "github.com/emersion/go-smtp"
- "github.com/getarcaneapp/arcane/backend/internal/models"
-)
-
-// EmailClient wraps the SMTP client functionality
-type EmailClient struct {
- client *smtp.Client
-}
-
-// ConnectSMTP establishes a connection to the SMTP server based on the TLS mode
-func ConnectSMTP(ctx context.Context, config models.EmailConfig) (*EmailClient, error) {
- // Check if context is still valid
- select {
- case <-ctx.Done():
- return nil, ctx.Err()
- default:
- }
-
- addr := fmt.Sprintf("%s:%d", config.SMTPHost, config.SMTPPort)
-
- tlsConfig := &tls.Config{
- ServerName: config.SMTPHost,
- MinVersion: tls.VersionTLS12,
- InsecureSkipVerify: false,
- }
-
- var client *smtp.Client
- var err error
-
- // Default to StartTLS if not set
- tlsMode := config.TLSMode
- if tlsMode == "" {
- tlsMode = models.EmailTLSModeStartTLS
- }
-
- // Connect based on TLS mode
- switch tlsMode {
- case models.EmailTLSModeNone:
- client, err = smtp.Dial(addr)
- case models.EmailTLSModeSSL:
- client, err = smtp.DialTLS(addr, tlsConfig)
- case models.EmailTLSModeStartTLS:
- client, err = smtp.DialStartTLS(addr, tlsConfig)
- default:
- return nil, fmt.Errorf("unknown TLS mode: %s", tlsMode)
- }
-
- if err != nil {
- return nil, fmt.Errorf("failed to connect to SMTP server: %w", err)
- }
-
- client.CommandTimeout = 10 * time.Second
-
- // Send HELLO command
- if err := sendHelloCommand(client); err != nil {
- client.Close()
- return nil, fmt.Errorf("failed to send HELLO command: %w", err)
- }
-
- // Authenticate if credentials are provided
- if config.SMTPUsername != "" || config.SMTPPassword != "" {
- if err := authenticateSMTP(client, config.SMTPUsername, config.SMTPPassword); err != nil {
- client.Close()
- return nil, fmt.Errorf("failed to authenticate: %w", err)
- }
- }
-
- return &EmailClient{client: client}, nil
-}
-
-// sendHelloCommand sends the HELO/EHLO command to the SMTP server with the system hostname
-func sendHelloCommand(client *smtp.Client) error {
- hostname, err := os.Hostname()
- if err != nil || hostname == "" {
- hostname = "arcane"
- }
- return client.Hello(hostname)
-}
-
-// authenticateSMTP authenticates with the SMTP server using PLAIN or LOGIN mechanisms
-func authenticateSMTP(client *smtp.Client, username, password string) error {
- // Try PLAIN authentication first
- auth := sasl.NewPlainClient("", username, password)
- err := client.Auth(auth)
-
- if err != nil {
- // If PLAIN fails with unknown mechanism, try LOGIN
- var smtpErr *smtp.SMTPError
- if errors.As(err, &smtpErr) && smtpErr.Code == smtp.ErrAuthUnknownMechanism.Code {
- auth = sasl.NewLoginClient(username, password)
- err = client.Auth(auth)
- }
- }
-
- return err
-}
-
-// SendMessage sends an email message through the SMTP client
-func (ec *EmailClient) SendMessage(fromAddress string, toAddresses []string, message string) error {
- // Set the sender
- if err := ec.client.Mail(fromAddress, nil); err != nil {
- return fmt.Errorf("failed to set sender: %w", err)
- }
-
- // Set recipients
- for _, to := range toAddresses {
- if err := ec.client.Rcpt(to, nil); err != nil {
- return fmt.Errorf("failed to set recipient %s: %w", to, err)
- }
- }
-
- // Get a writer to write the email data
- w, err := ec.client.Data()
- if err != nil {
- return fmt.Errorf("failed to start data: %w", err)
- }
-
- // Write the email content
- if _, err := w.Write([]byte(message)); err != nil {
- return fmt.Errorf("failed to write email data: %w", err)
- }
-
- // Close the writer
- if err := w.Close(); err != nil {
- return fmt.Errorf("failed to close data writer: %w", err)
- }
-
- return nil
-}
-
-// Close closes the SMTP connection
-func (ec *EmailClient) Close() error {
- if ec.client != nil {
- return ec.client.Close()
- }
- return nil
-}
-
-// SanitizeForEmail restricts to safe characters for email (alphanumerics, dash, dot, slash, colon, at, underscore).
-// It removes any character not matching the safe set and explicitly strips CRLF characters to prevent header injection.
-func SanitizeForEmail(s string) string {
- // First, strip out all carriage returns and newlines to prevent email header/content injection
- s = strings.ReplaceAll(s, "\r", "")
- s = strings.ReplaceAll(s, "\n", "")
-
- // Allow only: letters, numbers, dot, slash, dash, colon, at, underscore
- safe := make([]rune, 0)
- for _, c := range s {
- if (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
- (c >= '0' && c <= '9') ||
- c == '.' || c == '/' || c == '-' || c == ':' ||
- c == '@' || c == '_' {
- safe = append(safe, c)
- }
- }
- return string(safe)
-}
-
-// BuildMultipartMessage constructs a MIME multipart email message with both HTML and text parts
-func BuildMultipartMessage(fromAddress string, toAddresses []string, subject string, htmlBody string, textBody string) (string, error) {
- var buf bytes.Buffer
- boundary := fmt.Sprintf("boundary_%d", time.Now().UnixNano())
-
- // Add headers
- buf.WriteString(fmt.Sprintf("From: %s\r\n", fromAddress))
- buf.WriteString(fmt.Sprintf("To: %s\r\n", strings.Join(toAddresses, ", ")))
- buf.WriteString(fmt.Sprintf("Subject: %s\r\n", subject))
- buf.WriteString(fmt.Sprintf("Date: %s\r\n", time.Now().Format(time.RFC1123Z)))
- buf.WriteString("MIME-Version: 1.0\r\n")
- buf.WriteString(fmt.Sprintf("Content-Type: multipart/alternative; boundary=\"%s\"\r\n", boundary))
- buf.WriteString("\r\n")
-
- // Add text part
- buf.WriteString(fmt.Sprintf("--%s\r\n", boundary))
- buf.WriteString("Content-Type: text/plain; charset=UTF-8\r\n")
- buf.WriteString("Content-Transfer-Encoding: quoted-printable\r\n")
- buf.WriteString("\r\n")
-
- qp := quotedprintable.NewWriter(&buf)
- if _, err := qp.Write([]byte(textBody)); err != nil {
- return "", fmt.Errorf("failed to encode text body: %w", err)
- }
- qp.Close()
- buf.WriteString("\r\n")
-
- // Add HTML part
- buf.WriteString(fmt.Sprintf("--%s\r\n", boundary))
- buf.WriteString("Content-Type: text/html; charset=UTF-8\r\n")
- buf.WriteString("Content-Transfer-Encoding: quoted-printable\r\n")
- buf.WriteString("\r\n")
-
- qp = quotedprintable.NewWriter(&buf)
- if _, err := qp.Write([]byte(htmlBody)); err != nil {
- return "", fmt.Errorf("failed to encode html body: %w", err)
- }
- qp.Close()
- buf.WriteString("\r\n")
-
- // End boundary
- buf.WriteString(fmt.Sprintf("--%s--\r\n", boundary))
-
- return buf.String(), nil
-}
diff --git a/backend/internal/utils/notifications/generic_sender.go b/backend/internal/utils/notifications/generic_sender.go
new file mode 100644
index 000000000..3d40606e0
--- /dev/null
+++ b/backend/internal/utils/notifications/generic_sender.go
@@ -0,0 +1,118 @@
+package notifications
+
+import (
+ "context"
+ "fmt"
+ "net/url"
+ "strings"
+
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/nicholas-fedor/shoutrrr"
+ shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types"
+)
+
+// BuildGenericURL converts GenericConfig to Shoutrrr URL format for generic webhooks
+func BuildGenericURL(config models.GenericConfig) (string, error) {
+ if config.WebhookURL == "" {
+ return "", fmt.Errorf("webhook URL is empty")
+ }
+
+ // Parse the webhook URL
+ webhookURL, err := url.Parse(config.WebhookURL)
+ if err != nil {
+ return "", fmt.Errorf("invalid webhook URL: %w", err)
+ }
+
+ // Build generic service URL
+ // Format: generic://host[:port]/path?params
+ // Shoutrrr's generic service uses HTTP or HTTPS based on the DisableTLS setting
+ scheme := "generic"
+
+ // Start with the base URL
+ shoutrrrURL := &url.URL{
+ Scheme: scheme,
+ Host: webhookURL.Host,
+ Path: webhookURL.Path,
+ }
+
+ // Build query parameters
+ query := url.Values{}
+
+ // Set template to JSON (default for generic webhooks)
+ query.Set("template", "json")
+
+ // Set content type if provided
+ if config.ContentType != "" {
+ query.Set("contenttype", config.ContentType)
+ }
+
+ // Set HTTP method if provided
+ if config.Method != "" {
+ query.Set("method", config.Method)
+ }
+
+ // Set title and message keys if provided
+ if config.TitleKey != "" {
+ query.Set("titlekey", config.TitleKey)
+ }
+ if config.MessageKey != "" {
+ query.Set("messagekey", config.MessageKey)
+ }
+
+ // Determine TLS setting: respect both the original URL scheme and explicit config
+ // If original URL was http:// OR DisableTLS is true → use HTTP (disabletls=yes)
+ // Otherwise → use HTTPS (disabletls=no)
+ disableTLS := config.DisableTLS || strings.ToLower(webhookURL.Scheme) == "http"
+ if disableTLS {
+ query.Set("disabletls", "yes")
+ } else {
+ query.Set("disabletls", "no")
+ }
+
+ // Add custom headers as query parameters with @ prefix
+ if len(config.CustomHeaders) > 0 {
+ for key, value := range config.CustomHeaders {
+ // Shoutrrr uses @ prefix for headers
+ query.Set("@"+key, value)
+ }
+ }
+
+ shoutrrrURL.RawQuery = query.Encode()
+
+ return shoutrrrURL.String(), nil
+}
+
+// SendGenericWithTitle sends a message with title via Shoutrrr Generic webhook
+func SendGenericWithTitle(ctx context.Context, config models.GenericConfig, title, message string) error {
+ if config.WebhookURL == "" {
+ return fmt.Errorf("webhook URL is empty")
+ }
+
+ shoutrrrURL, err := BuildGenericURL(config)
+ if err != nil {
+ return fmt.Errorf("failed to build shoutrrr Generic URL: %w", err)
+ }
+
+ sender, err := shoutrrr.CreateSender(shoutrrrURL)
+ if err != nil {
+ return fmt.Errorf("failed to create shoutrrr Generic sender: %w", err)
+ }
+
+ // Build params with title
+ params := shoutrrrTypes.Params{}
+ if title != "" {
+ titleKey := config.TitleKey
+ if titleKey == "" {
+ titleKey = "title"
+ }
+ params[titleKey] = title
+ }
+
+ errs := sender.Send(message, &params)
+ for _, err := range errs {
+ if err != nil {
+ return fmt.Errorf("failed to send Generic webhook message with title via shoutrrr: %w", err)
+ }
+ }
+ return nil
+}
diff --git a/backend/internal/utils/notifications/generic_sender_test.go b/backend/internal/utils/notifications/generic_sender_test.go
new file mode 100644
index 000000000..c2ea71eff
--- /dev/null
+++ b/backend/internal/utils/notifications/generic_sender_test.go
@@ -0,0 +1,304 @@
+package notifications
+
+import (
+ "testing"
+
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestBuildGenericURL(t *testing.T) {
+ tests := []struct {
+ name string
+ config models.GenericConfig
+ wantURL string
+ wantErr string
+ }{
+ {
+ name: "basic HTTPS webhook",
+ config: models.GenericConfig{
+ WebhookURL: "https://webhook.example.com/notify",
+ },
+ wantURL: "generic://webhook.example.com/notify?disabletls=no&template=json",
+ },
+ {
+ name: "basic HTTP webhook",
+ config: models.GenericConfig{
+ WebhookURL: "http://webhook.example.com/notify",
+ },
+ wantURL: "generic://webhook.example.com/notify?disabletls=yes&template=json",
+ },
+ {
+ name: "webhook with port",
+ config: models.GenericConfig{
+ WebhookURL: "https://webhook.example.com:8443/api/notify",
+ },
+ wantURL: "generic://webhook.example.com:8443/api/notify?disabletls=no&template=json",
+ },
+ {
+ name: "webhook with custom content type",
+ config: models.GenericConfig{
+ WebhookURL: "https://webhook.example.com/notify",
+ ContentType: "application/x-www-form-urlencoded",
+ },
+ wantURL: "generic://webhook.example.com/notify?contenttype=application%2Fx-www-form-urlencoded&disabletls=no&template=json",
+ },
+ {
+ name: "webhook with POST method",
+ config: models.GenericConfig{
+ WebhookURL: "https://webhook.example.com/notify",
+ Method: "POST",
+ },
+ wantURL: "generic://webhook.example.com/notify?disabletls=no&method=POST&template=json",
+ },
+ {
+ name: "webhook with custom title and message keys",
+ config: models.GenericConfig{
+ WebhookURL: "https://webhook.example.com/notify",
+ TitleKey: "subject",
+ MessageKey: "body",
+ },
+ wantURL: "generic://webhook.example.com/notify?disabletls=no&messagekey=body&template=json&titlekey=subject",
+ },
+ {
+ name: "webhook with DisableTLS",
+ config: models.GenericConfig{
+ WebhookURL: "https://webhook.example.com/notify",
+ DisableTLS: true,
+ },
+ wantURL: "generic://webhook.example.com/notify?disabletls=yes&template=json",
+ },
+ {
+ name: "webhook with single custom header",
+ config: models.GenericConfig{
+ WebhookURL: "https://webhook.example.com/notify",
+ CustomHeaders: map[string]string{
+ "Authorization": "Bearer token123",
+ },
+ },
+ wantURL: "generic://webhook.example.com/notify?%40Authorization=Bearer+token123&disabletls=no&template=json",
+ },
+ {
+ name: "webhook with multiple custom headers",
+ config: models.GenericConfig{
+ WebhookURL: "https://webhook.example.com/notify",
+ CustomHeaders: map[string]string{
+ "Authorization": "Bearer token123",
+ "X-Api-Key": "secret-key",
+ "X-Source": "Arcane",
+ },
+ },
+ // Note: URL encoding may vary in order due to map iteration
+ wantURL: "generic://webhook.example.com/notify",
+ },
+ {
+ name: "webhook with all options",
+ config: models.GenericConfig{
+ WebhookURL: "https://webhook.example.com:8443/api/v1/notify",
+ ContentType: "application/json",
+ Method: "PUT",
+ TitleKey: "heading",
+ MessageKey: "content",
+ DisableTLS: true,
+ CustomHeaders: map[string]string{
+ "Authorization": "Bearer token123",
+ },
+ },
+ wantURL: "generic://webhook.example.com:8443/api/v1/notify",
+ },
+ {
+ name: "empty webhook URL",
+ config: models.GenericConfig{
+ WebhookURL: "",
+ },
+ wantErr: "webhook URL is empty",
+ },
+ {
+ name: "invalid webhook URL",
+ config: models.GenericConfig{
+ WebhookURL: "://invalid-url",
+ },
+ wantErr: "invalid webhook URL",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ gotURL, err := BuildGenericURL(tt.config)
+
+ if tt.wantErr != "" {
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), tt.wantErr)
+ return
+ }
+
+ require.NoError(t, err)
+
+ // For tests with multiple headers or all options, just check prefix
+ if tt.name == "webhook with multiple custom headers" || tt.name == "webhook with all options" {
+ assert.Contains(t, gotURL, tt.wantURL)
+ } else {
+ assert.Equal(t, tt.wantURL, gotURL)
+ }
+ })
+ }
+}
+
+func TestBuildGenericURL_HTTPSchemeHandling(t *testing.T) {
+ tests := []struct {
+ name string
+ webhookURL string
+ wantHost string
+ }{
+ {
+ name: "HTTPS URL",
+ webhookURL: "https://webhook.example.com/notify",
+ wantHost: "webhook.example.com",
+ },
+ {
+ name: "HTTP URL",
+ webhookURL: "http://webhook.example.com/notify",
+ wantHost: "webhook.example.com",
+ },
+ {
+ name: "URL with custom port",
+ webhookURL: "https://webhook.example.com:9443/notify",
+ wantHost: "webhook.example.com:9443",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ config := models.GenericConfig{
+ WebhookURL: tt.webhookURL,
+ }
+
+ gotURL, err := BuildGenericURL(config)
+ require.NoError(t, err)
+
+ // Verify the scheme is always "generic"
+ assert.Contains(t, gotURL, "generic://")
+
+ // Verify the host is preserved
+ assert.Contains(t, gotURL, tt.wantHost)
+ })
+ }
+}
+
+func TestBuildGenericURL_CustomHeadersEncoding(t *testing.T) {
+ config := models.GenericConfig{
+ WebhookURL: "https://webhook.example.com/notify",
+ CustomHeaders: map[string]string{
+ "Authorization": "Bearer token-with-special-chars!@#",
+ "X-Custom-Value": "value with spaces",
+ },
+ }
+
+ gotURL, err := BuildGenericURL(config)
+ require.NoError(t, err)
+
+ // Verify headers are prefixed with @
+ assert.Contains(t, gotURL, "%40Authorization=")
+ assert.Contains(t, gotURL, "%40X-Custom-Value=")
+
+ // Verify special characters and spaces are encoded
+ assert.Contains(t, gotURL, "value+with+spaces")
+}
+
+func TestBuildGenericURL_DisableTLSFlag(t *testing.T) {
+ tests := []struct {
+ name string
+ disableTLS bool
+ wantParam string
+ }{
+ {
+ name: "TLS enabled (default)",
+ disableTLS: false,
+ wantParam: "disabletls=no",
+ },
+ {
+ name: "TLS disabled",
+ disableTLS: true,
+ wantParam: "disabletls=yes",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ config := models.GenericConfig{
+ WebhookURL: "https://webhook.example.com/notify",
+ DisableTLS: tt.disableTLS,
+ }
+
+ gotURL, err := BuildGenericURL(config)
+ require.NoError(t, err)
+
+ assert.Contains(t, gotURL, tt.wantParam)
+ })
+ }
+}
+
+func TestBuildGenericURL_CustomKeys(t *testing.T) {
+ tests := []struct {
+ name string
+ titleKey string
+ messageKey string
+ wantTitle string
+ wantMsg string
+ }{
+ {
+ name: "default keys (empty)",
+ titleKey: "",
+ messageKey: "",
+ wantTitle: "",
+ wantMsg: "",
+ },
+ {
+ name: "custom title key only",
+ titleKey: "subject",
+ messageKey: "",
+ wantTitle: "titlekey=subject",
+ wantMsg: "",
+ },
+ {
+ name: "custom message key only",
+ titleKey: "",
+ messageKey: "body",
+ wantTitle: "",
+ wantMsg: "messagekey=body",
+ },
+ {
+ name: "both custom keys",
+ titleKey: "heading",
+ messageKey: "content",
+ wantTitle: "titlekey=heading",
+ wantMsg: "messagekey=content",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ config := models.GenericConfig{
+ WebhookURL: "https://webhook.example.com/notify",
+ TitleKey: tt.titleKey,
+ MessageKey: tt.messageKey,
+ }
+
+ gotURL, err := BuildGenericURL(config)
+ require.NoError(t, err)
+
+ if tt.wantTitle != "" {
+ assert.Contains(t, gotURL, tt.wantTitle)
+ } else if tt.titleKey == "" {
+ assert.NotContains(t, gotURL, "titlekey=")
+ }
+
+ if tt.wantMsg != "" {
+ assert.Contains(t, gotURL, tt.wantMsg)
+ } else if tt.messageKey == "" {
+ assert.NotContains(t, gotURL, "messagekey=")
+ }
+ })
+ }
+}
diff --git a/backend/internal/utils/notifications/ntfy_sender.go b/backend/internal/utils/notifications/ntfy_sender.go
new file mode 100644
index 000000000..854f8c741
--- /dev/null
+++ b/backend/internal/utils/notifications/ntfy_sender.go
@@ -0,0 +1,108 @@
+package notifications
+
+import (
+ "context"
+ "fmt"
+ "net/url"
+ "strings"
+
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/nicholas-fedor/shoutrrr"
+ shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types"
+)
+
+// BuildNtfyURL converts NtfyConfig to Shoutrrr URL format
+// URL example: ntfy://[user:password@]host[:port]/topic[?query]
+func BuildNtfyURL(config models.NtfyConfig) (string, error) {
+ if config.Topic == "" {
+ return "", fmt.Errorf("ntfy topic is required")
+ }
+
+ // Default host to ntfy.sh if not specified
+ host := config.Host
+ if host == "" {
+ host = "ntfy.sh"
+ }
+
+ // Build the base URL
+ u := &url.URL{
+ Scheme: "ntfy",
+ }
+
+ // Add authentication if provided
+ if config.Username != "" || config.Password != "" {
+ u.User = url.UserPassword(config.Username, config.Password)
+ }
+
+ // Set host and port
+ if config.Port > 0 {
+ u.Host = fmt.Sprintf("%s:%d", host, config.Port)
+ } else {
+ u.Host = host
+ }
+
+ // Set path (topic)
+ u.Path = "/" + config.Topic
+
+ // Add query parameters
+ q := u.Query()
+
+ if config.Priority != "" {
+ q.Set("priority", config.Priority)
+ }
+
+ if len(config.Tags) > 0 {
+ q.Set("tags", strings.Join(config.Tags, ","))
+ }
+
+ if config.Icon != "" {
+ q.Set("icon", config.Icon)
+ }
+
+ // Always send explicit cache/firebase params to avoid ambiguity
+ if config.Cache {
+ q.Set("cache", "yes")
+ } else {
+ q.Set("cache", "no")
+ }
+
+ if config.Firebase {
+ q.Set("firebase", "yes")
+ } else {
+ q.Set("firebase", "no")
+ }
+
+ if config.DisableTLSVerification {
+ q.Set("disabletls", "yes")
+ }
+
+ u.RawQuery = q.Encode()
+ return u.String(), nil
+}
+
+// SendNtfy sends a message via Shoutrrr Ntfy using proper service configuration
+func SendNtfy(ctx context.Context, config models.NtfyConfig, message string) error {
+ if config.Topic == "" {
+ return fmt.Errorf("ntfy topic is required")
+ }
+
+ shoutrrrURL, err := BuildNtfyURL(config)
+ if err != nil {
+ return fmt.Errorf("failed to build shoutrrr Ntfy URL: %w", err)
+ }
+
+ sender, err := shoutrrr.CreateSender(shoutrrrURL)
+ if err != nil {
+ return fmt.Errorf("failed to create shoutrrr Ntfy sender: %w", err)
+ }
+
+ params := &shoutrrrTypes.Params{}
+
+ errs := sender.Send(message, params)
+ for _, err := range errs {
+ if err != nil {
+ return fmt.Errorf("failed to send Ntfy message via shoutrrr: %w", err)
+ }
+ }
+ return nil
+}
diff --git a/backend/internal/utils/notifications/ntfy_sender_test.go b/backend/internal/utils/notifications/ntfy_sender_test.go
new file mode 100644
index 000000000..dcc8747f7
--- /dev/null
+++ b/backend/internal/utils/notifications/ntfy_sender_test.go
@@ -0,0 +1,128 @@
+package notifications
+
+import (
+ "testing"
+
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestBuildNtfyURL(t *testing.T) {
+ tests := []struct {
+ name string
+ config models.NtfyConfig
+ wantErr bool
+ check func(string) bool
+ }{
+ {
+ name: "basic config with default host",
+ config: models.NtfyConfig{
+ Topic: "test-topic",
+ Cache: true,
+ Firebase: true,
+ },
+ wantErr: false,
+ check: func(url string) bool {
+ return url == "ntfy://ntfy.sh/test-topic?cache=yes&firebase=yes"
+ },
+ },
+ {
+ name: "config with custom host",
+ config: models.NtfyConfig{
+ Host: "ntfy.example.com",
+ Topic: "alerts",
+ Cache: true,
+ Firebase: true,
+ },
+ wantErr: false,
+ check: func(url string) bool {
+ return url == "ntfy://ntfy.example.com/alerts?cache=yes&firebase=yes"
+ },
+ },
+ {
+ name: "config with port",
+ config: models.NtfyConfig{
+ Host: "ntfy.example.com",
+ Port: 8080,
+ Topic: "updates",
+ Cache: true,
+ Firebase: true,
+ },
+ wantErr: false,
+ check: func(url string) bool {
+ return url == "ntfy://ntfy.example.com:8080/updates?cache=yes&firebase=yes"
+ },
+ },
+ {
+ name: "config with auth",
+ config: models.NtfyConfig{
+ Host: "ntfy.example.com",
+ Port: 443,
+ Topic: "private",
+ Username: "user",
+ Password: "pass",
+ Cache: true,
+ Firebase: true,
+ },
+ wantErr: false,
+ check: func(url string) bool {
+ return url == "ntfy://user:[email protected]:443/private?cache=yes&firebase=yes"
+ },
+ },
+ {
+ name: "config with priority and tags",
+ config: models.NtfyConfig{
+ Host: "ntfy.sh",
+ Topic: "alerts",
+ Priority: "high",
+ Tags: []string{"warning", "server"},
+ Cache: true,
+ Firebase: true,
+ },
+ wantErr: false,
+ check: func(url string) bool {
+ return url == "ntfy://ntfy.sh/alerts?cache=yes&firebase=yes&priority=high&tags=warning%2Cserver"
+ },
+ },
+ {
+ name: "missing topic",
+ config: models.NtfyConfig{
+ Host: "ntfy.sh",
+ },
+ wantErr: true,
+ },
+ {
+ name: "config with all options",
+ config: models.NtfyConfig{
+ Host: "ntfy.example.com",
+ Port: 8080,
+ Topic: "test",
+ Username: "user",
+ Password: "pass",
+ Priority: "max",
+ Tags: []string{"urgent"},
+ Icon: "https://example.com/icon.png",
+ Cache: false,
+ Firebase: false,
+ DisableTLSVerification: true,
+ },
+ wantErr: false,
+ check: func(url string) bool {
+ return url == "ntfy://user:[email protected]:8080/test?cache=no&disabletls=yes&firebase=no&icon=https%3A%2F%2Fexample.com%2Ficon.png&priority=max&tags=urgent"
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ gotURL, err := BuildNtfyURL(tt.config)
+ if tt.wantErr {
+ require.Error(t, err)
+ } else {
+ require.NoError(t, err)
+ assert.True(t, tt.check(gotURL), "URL mismatch: %s", gotURL)
+ }
+ })
+ }
+}
diff --git a/backend/internal/utils/notifications/signal_sender.go b/backend/internal/utils/notifications/signal_sender.go
new file mode 100644
index 000000000..63900f58d
--- /dev/null
+++ b/backend/internal/utils/notifications/signal_sender.go
@@ -0,0 +1,71 @@
+package notifications
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/nicholas-fedor/shoutrrr"
+ "github.com/nicholas-fedor/shoutrrr/pkg/services/chat/signal"
+)
+
+// BuildSignalURL converts SignalConfig to Shoutrrr URL format using shoutrrr's Config
+func BuildSignalURL(config models.SignalConfig) (string, error) {
+ signalConfig := &signal.Config{
+ Host: config.Host,
+ Port: config.Port,
+ User: config.User,
+ Password: config.Password,
+ Token: config.Token,
+ Source: config.Source,
+ Recipients: config.Recipients,
+ DisableTLS: config.DisableTLS,
+ }
+
+ url := signalConfig.GetURL()
+ return url.String(), nil
+}
+
+// SendSignal sends a message via Shoutrrr Signal using proper service configuration
+func SendSignal(ctx context.Context, config models.SignalConfig, message string) error {
+ if config.Host == "" {
+ return fmt.Errorf("signal host is empty")
+ }
+ if config.Port == 0 {
+ return fmt.Errorf("signal port is not set")
+ }
+ if config.Source == "" {
+ return fmt.Errorf("signal source phone number is empty")
+ }
+ if len(config.Recipients) == 0 {
+ return fmt.Errorf("no signal recipients configured")
+ }
+
+ // Validate authentication
+ hasBasicAuth := config.User != "" && config.Password != ""
+ hasTokenAuth := config.Token != ""
+ if !hasBasicAuth && !hasTokenAuth {
+ return fmt.Errorf("signal requires either basic auth (user/password) or token authentication")
+ }
+ if hasBasicAuth && hasTokenAuth {
+ return fmt.Errorf("signal cannot use both basic auth and token authentication simultaneously")
+ }
+
+ shoutrrrURL, err := BuildSignalURL(config)
+ if err != nil {
+ return fmt.Errorf("failed to build shoutrrr Signal URL: %w", err)
+ }
+
+ sender, err := shoutrrr.CreateSender(shoutrrrURL)
+ if err != nil {
+ return fmt.Errorf("failed to create shoutrrr Signal sender: %w", err)
+ }
+
+ errs := sender.Send(message, nil)
+ for _, err := range errs {
+ if err != nil {
+ return fmt.Errorf("failed to send Signal message via shoutrrr: %w", err)
+ }
+ }
+ return nil
+}
diff --git a/backend/internal/utils/notifications/signal_sender_test.go b/backend/internal/utils/notifications/signal_sender_test.go
new file mode 100644
index 000000000..05b4ed293
--- /dev/null
+++ b/backend/internal/utils/notifications/signal_sender_test.go
@@ -0,0 +1,338 @@
+package notifications
+
+import (
+ "fmt"
+ "testing"
+
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestBuildSignalURL(t *testing.T) {
+ tests := []struct {
+ name string
+ config models.SignalConfig
+ check func(string) bool
+ }{
+ {
+ name: "basic auth configuration",
+ config: models.SignalConfig{
+ Host: "signal.example.com",
+ Port: 8080,
+ User: "admin",
+ Password: "secret",
+ Source: "+1234567890",
+ Recipients: []string{"+0987654321"},
+ },
+ check: func(url string) bool {
+ return assert.Contains(t, url, "signal://admin:[email protected]:8080") &&
+ assert.Contains(t, url, "source=%2B1234567890") &&
+ assert.Contains(t, url, "recipients=%2B0987654321")
+ },
+ },
+ {
+ name: "token auth configuration",
+ config: models.SignalConfig{
+ Host: "signal.example.com",
+ Port: 8080,
+ Token: "auth-token-123",
+ Source: "+1234567890",
+ Recipients: []string{"+0987654321"},
+ },
+ check: func(url string) bool {
+ return assert.Contains(t, url, "signal://signal.example.com:8080") &&
+ assert.Contains(t, url, "token=auth-token-123") &&
+ assert.Contains(t, url, "source=%2B1234567890")
+ },
+ },
+ {
+ name: "multiple recipients",
+ config: models.SignalConfig{
+ Host: "signal.example.com",
+ Port: 8080,
+ Token: "token123",
+ Source: "+1111111111",
+ Recipients: []string{"+2222222222", "+3333333333", "+4444444444"},
+ },
+ check: func(url string) bool {
+ return assert.Contains(t, url, "recipients=%2B2222222222%2C%2B3333333333%2C%2B4444444444")
+ },
+ },
+ {
+ name: "with DisableTLS",
+ config: models.SignalConfig{
+ Host: "signal.example.com",
+ Port: 8080,
+ Token: "token123",
+ Source: "+1234567890",
+ Recipients: []string{"+0987654321"},
+ DisableTLS: true,
+ },
+ check: func(url string) bool {
+ return assert.Contains(t, url, "disabletls=Yes")
+ },
+ },
+ {
+ name: "custom port",
+ config: models.SignalConfig{
+ Host: "signal-api.local",
+ Port: 9443,
+ User: "user",
+ Password: "pass",
+ Source: "+1234567890",
+ Recipients: []string{"+0987654321"},
+ },
+ check: func(url string) bool {
+ return assert.Contains(t, url, "signal://user:[email protected]:9443") &&
+ assert.Contains(t, url, "port=9443")
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ gotURL, err := BuildSignalURL(tt.config)
+ require.NoError(t, err)
+ tt.check(gotURL)
+ })
+ }
+}
+
+func TestBuildSignalURL_AuthenticationMethods(t *testing.T) {
+ tests := []struct {
+ name string
+ config models.SignalConfig
+ wantAuth string
+ }{
+ {
+ name: "basic auth only",
+ config: models.SignalConfig{
+ Host: "signal.example.com",
+ Port: 8080,
+ User: "testuser",
+ Password: "testpass",
+ Source: "+1234567890",
+ Recipients: []string{"+0987654321"},
+ },
+ wantAuth: "testuser:testpass@",
+ },
+ {
+ name: "token auth only",
+ config: models.SignalConfig{
+ Host: "signal.example.com",
+ Port: 8080,
+ Token: "my-secure-token",
+ Source: "+1234567890",
+ Recipients: []string{"+0987654321"},
+ },
+ wantAuth: "token=my-secure-token",
+ },
+ {
+ name: "both basic and token auth provided",
+ config: models.SignalConfig{
+ Host: "signal.example.com",
+ Port: 8080,
+ User: "user",
+ Password: "pass",
+ Token: "token",
+ Source: "+1234567890",
+ Recipients: []string{"+0987654321"},
+ },
+ wantAuth: "user:pass@",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ gotURL, err := BuildSignalURL(tt.config)
+ require.NoError(t, err)
+ assert.Contains(t, gotURL, tt.wantAuth)
+ })
+ }
+}
+
+func TestBuildSignalURL_PhoneNumberEncoding(t *testing.T) {
+ config := models.SignalConfig{
+ Host: "signal.example.com",
+ Port: 8080,
+ Token: "token",
+ Source: "+1 (555) 123-4567", // Phone with special chars
+ Recipients: []string{"+1 (555) 987-6543"},
+ }
+
+ gotURL, err := BuildSignalURL(config)
+ require.NoError(t, err)
+
+ // Phone numbers should be in the URL path and query params
+ assert.Contains(t, gotURL, "source=")
+ assert.Contains(t, gotURL, "recipients=")
+}
+
+func TestSendSignal_Validation(t *testing.T) {
+ tests := []struct {
+ name string
+ config models.SignalConfig
+ wantErr string
+ }{
+ {
+ name: "missing host",
+ config: models.SignalConfig{
+ Port: 8080,
+ Token: "token",
+ Source: "+1234567890",
+ Recipients: []string{"+0987654321"},
+ },
+ wantErr: "signal host is empty",
+ },
+ {
+ name: "missing port",
+ config: models.SignalConfig{
+ Host: "signal.example.com",
+ Token: "token",
+ Source: "+1234567890",
+ Recipients: []string{"+0987654321"},
+ },
+ wantErr: "signal port is not set",
+ },
+ {
+ name: "missing source",
+ config: models.SignalConfig{
+ Host: "signal.example.com",
+ Port: 8080,
+ Token: "token",
+ Recipients: []string{"+0987654321"},
+ },
+ wantErr: "signal source phone number is empty",
+ },
+ {
+ name: "missing recipients",
+ config: models.SignalConfig{
+ Host: "signal.example.com",
+ Port: 8080,
+ Token: "token",
+ Source: "+1234567890",
+ },
+ wantErr: "no signal recipients configured",
+ },
+ {
+ name: "missing authentication - no user/password/token",
+ config: models.SignalConfig{
+ Host: "signal.example.com",
+ Port: 8080,
+ Source: "+1234567890",
+ Recipients: []string{"+0987654321"},
+ },
+ wantErr: "signal requires either basic auth (user/password) or token authentication",
+ },
+ {
+ name: "incomplete basic auth - user only",
+ config: models.SignalConfig{
+ Host: "signal.example.com",
+ Port: 8080,
+ User: "admin",
+ Source: "+1234567890",
+ Recipients: []string{"+0987654321"},
+ },
+ wantErr: "signal requires either basic auth (user/password) or token authentication",
+ },
+ {
+ name: "incomplete basic auth - password only",
+ config: models.SignalConfig{
+ Host: "signal.example.com",
+ Port: 8080,
+ Password: "secret",
+ Source: "+1234567890",
+ Recipients: []string{"+0987654321"},
+ },
+ wantErr: "signal requires either basic auth (user/password) or token authentication",
+ },
+ {
+ name: "both auth methods provided",
+ config: models.SignalConfig{
+ Host: "signal.example.com",
+ Port: 8080,
+ User: "user",
+ Password: "pass",
+ Token: "token",
+ Source: "+1234567890",
+ Recipients: []string{"+0987654321"},
+ },
+ wantErr: "signal cannot use both basic auth and token authentication simultaneously",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ // Note: SendSignal will try to actually send, so we only test validation logic
+ // by checking the error message before network call
+ err := validateSignalConfig(tt.config)
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), tt.wantErr)
+ })
+ }
+}
+
+func TestSendSignal_ValidConfigurations(t *testing.T) {
+ tests := []struct {
+ name string
+ config models.SignalConfig
+ }{
+ {
+ name: "valid basic auth",
+ config: models.SignalConfig{
+ Host: "signal.example.com",
+ Port: 8080,
+ User: "admin",
+ Password: "secret",
+ Source: "+1234567890",
+ Recipients: []string{"+0987654321"},
+ },
+ },
+ {
+ name: "valid token auth",
+ config: models.SignalConfig{
+ Host: "signal.example.com",
+ Port: 8080,
+ Token: "token123",
+ Source: "+1234567890",
+ Recipients: []string{"+0987654321"},
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := validateSignalConfig(tt.config)
+ assert.NoError(t, err)
+ })
+ }
+}
+
+// Helper function to extract validation logic for testing
+func validateSignalConfig(config models.SignalConfig) error {
+ if config.Host == "" {
+ return fmt.Errorf("signal host is empty")
+ }
+ if config.Port == 0 {
+ return fmt.Errorf("signal port is not set")
+ }
+ if config.Source == "" {
+ return fmt.Errorf("signal source phone number is empty")
+ }
+ if len(config.Recipients) == 0 {
+ return fmt.Errorf("no signal recipients configured")
+ }
+
+ // Validate authentication
+ hasBasicAuth := config.User != "" && config.Password != ""
+ hasTokenAuth := config.Token != ""
+ if !hasBasicAuth && !hasTokenAuth {
+ return fmt.Errorf("signal requires either basic auth (user/password) or token authentication")
+ }
+ if hasBasicAuth && hasTokenAuth {
+ return fmt.Errorf("signal cannot use both basic auth and token authentication simultaneously")
+ }
+
+ return nil
+}
diff --git a/backend/internal/utils/notifications/slack_sender.go b/backend/internal/utils/notifications/slack_sender.go
new file mode 100644
index 000000000..6798ad883
--- /dev/null
+++ b/backend/internal/utils/notifications/slack_sender.go
@@ -0,0 +1,61 @@
+package notifications
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/nicholas-fedor/shoutrrr"
+ "github.com/nicholas-fedor/shoutrrr/pkg/services/chat/slack"
+)
+
+// BuildSlackURL converts SlackConfig to Shoutrrr URL format using shoutrrr's Config
+func BuildSlackURL(config models.SlackConfig) (string, error) {
+ if config.Token == "" {
+ return "", fmt.Errorf("slack token is required")
+ }
+
+ // Parse the token to get the token object
+ token, err := slack.ParseToken(config.Token)
+ if err != nil {
+ return "", fmt.Errorf("invalid Slack token format (expected format: xoxb-... or xoxp-...): %w", err)
+ }
+
+ slackConfig := &slack.Config{
+ BotName: config.BotName,
+ Icon: config.Icon,
+ Token: *token,
+ Color: config.Color,
+ Title: config.Title,
+ Channel: config.Channel,
+ ThreadTS: config.ThreadTS,
+ }
+
+ url := slackConfig.GetURL()
+ return url.String(), nil
+}
+
+// SendSlack sends a message via Shoutrrr Slack using proper service configuration
+func SendSlack(ctx context.Context, config models.SlackConfig, message string) error {
+ if config.Token == "" {
+ return fmt.Errorf("slack token is empty")
+ }
+
+ shoutrrrURL, err := BuildSlackURL(config)
+ if err != nil {
+ return fmt.Errorf("failed to build shoutrrr Slack URL: %w", err)
+ }
+
+ sender, err := shoutrrr.CreateSender(shoutrrrURL)
+ if err != nil {
+ return fmt.Errorf("failed to create shoutrrr Slack sender: %w", err)
+ }
+
+ errs := sender.Send(message, nil)
+ for _, err := range errs {
+ if err != nil {
+ return fmt.Errorf("failed to send Slack message via shoutrrr: %w", err)
+ }
+ }
+ return nil
+}
diff --git a/backend/internal/utils/notifications/slack_sender_test.go b/backend/internal/utils/notifications/slack_sender_test.go
new file mode 100644
index 000000000..5890121ce
--- /dev/null
+++ b/backend/internal/utils/notifications/slack_sender_test.go
@@ -0,0 +1,150 @@
+package notifications
+
+import (
+ "testing"
+
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestBuildSlackURL(t *testing.T) {
+ tests := []struct {
+ name string
+ config models.SlackConfig
+ wantURL string
+ wantErr string
+ }{
+ {
+ name: "basic config with bot token and channel",
+ config: models.SlackConfig{
+ Token: "xoxb-123456789012-123456789012-abcdefghijklmnopqrstuvwx",
+ Channel: "general",
+ },
+ wantURL: "slack://xoxb:123456789012-123456789012-abcdefghijklmnopqrstuvwx@general",
+ },
+ {
+ name: "config with user token",
+ config: models.SlackConfig{
+ Token: "xoxp-123456789012-123456789012-abcdefghijklmnopqrstuvwx",
+ Channel: "alerts",
+ },
+ wantURL: "slack://xoxp:123456789012-123456789012-abcdefghijklmnopqrstuvwx@alerts",
+ },
+ {
+ name: "config with all optional fields",
+ config: models.SlackConfig{
+ Token: "xoxb-123456789012-123456789012-abcdefghijklmnopqrstuvwx",
+ Channel: "notifications",
+ BotName: "Arcane Bot",
+ Icon: ":robot:",
+ Color: "#FF0000",
+ Title: "Container Update",
+ ThreadTS: "1234567890.123456",
+ },
+ wantURL: "slack://xoxb:123456789012-123456789012-abcdefghijklmnopqrstuvwx@notifications?botname=Arcane+Bot&color=%23FF0000&icon=%3Arobot%3A&thread_ts=1234567890.123456&title=Container+Update",
+ },
+ {
+ name: "empty token",
+ config: models.SlackConfig{
+ Channel: "general",
+ },
+ wantErr: "slack token is required",
+ },
+ {
+ name: "invalid token format",
+ config: models.SlackConfig{
+ Token: "invalid-token",
+ Channel: "general",
+ },
+ wantErr: "invalid Slack token format (expected format: xoxb-... or xoxp-...)",
+ },
+ {
+ name: "token without prefix",
+ config: models.SlackConfig{
+ Token: "1234-5678-abcd",
+ Channel: "general",
+ },
+ wantErr: "invalid Slack token format (expected format: xoxb-... or xoxp-...)",
+ },
+ {
+ name: "short invalid token",
+ config: models.SlackConfig{
+ Token: "xoxb-1234-5678-abcd",
+ Channel: "general",
+ },
+ wantErr: "invalid Slack token format (expected format: xoxb-... or xoxp-...)",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ gotURL, err := BuildSlackURL(tt.config)
+
+ if tt.wantErr != "" {
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), tt.wantErr)
+ return
+ }
+
+ require.NoError(t, err)
+ assert.Equal(t, tt.wantURL, gotURL)
+ })
+ }
+}
+
+func TestBuildSlackURL_TokenParsing(t *testing.T) {
+ tests := []struct {
+ name string
+ token string
+ wantErr bool
+ }{
+ {
+ name: "valid bot token",
+ token: "xoxb-123456789012-123456789012-abcdefghijklmnopqrstuvwx",
+ wantErr: false,
+ },
+ {
+ name: "valid user token",
+ token: "xoxp-123456789012-123456789012-abcdefghijklmnopqrstuvwx",
+ wantErr: false,
+ },
+ {
+ name: "token with xoxa prefix is also accepted",
+ token: "xoxa-123456789012-123456789012-abcdefghijklmnopqrstuvwx",
+ wantErr: false,
+ },
+ {
+ name: "token without dashes",
+ token: "xoxb1234567890",
+ wantErr: true,
+ },
+ {
+ name: "short token",
+ token: "xoxb-1234-5678-abcd",
+ wantErr: true,
+ },
+ {
+ name: "empty token",
+ token: "",
+ wantErr: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ config := models.SlackConfig{
+ Token: tt.token,
+ Channel: "test",
+ }
+
+ _, err := BuildSlackURL(config)
+
+ if tt.wantErr {
+ assert.Error(t, err)
+ } else {
+ assert.NoError(t, err)
+ }
+ })
+ }
+}
diff --git a/backend/internal/utils/notifications/telegram_sender.go b/backend/internal/utils/notifications/telegram_sender.go
new file mode 100644
index 000000000..05b5af6dc
--- /dev/null
+++ b/backend/internal/utils/notifications/telegram_sender.go
@@ -0,0 +1,66 @@
+package notifications
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/nicholas-fedor/shoutrrr"
+ "github.com/nicholas-fedor/shoutrrr/pkg/services/chat/telegram"
+)
+
+// BuildTelegramURL converts TelegramConfig to Shoutrrr URL format using shoutrrr's Config
+func BuildTelegramURL(config models.TelegramConfig) (string, error) {
+ telegramConfig := &telegram.Config{
+ Token: config.BotToken,
+ Chats: config.ChatIDs,
+ Preview: config.Preview,
+ Notification: config.Notification,
+ Title: config.Title,
+ }
+
+ url := telegramConfig.GetURL()
+
+ // Add parse mode as query parameter if provided
+ if config.ParseMode != "" {
+ // Validate parse mode
+ switch config.ParseMode {
+ case "Markdown", "HTML", "MarkdownV2", "None":
+ q := url.Query()
+ q.Set("parsemode", config.ParseMode)
+ url.RawQuery = q.Encode()
+ default:
+ return "", fmt.Errorf("invalid parse mode: %s (must be Markdown, HTML, MarkdownV2, or None)", config.ParseMode)
+ }
+ }
+
+ return url.String(), nil
+}
+
+// SendTelegram sends a message via Shoutrrr Telegram using proper service configuration
+func SendTelegram(ctx context.Context, config models.TelegramConfig, message string) error {
+ if config.BotToken == "" {
+ return fmt.Errorf("telegram bot token is empty")
+ }
+ if len(config.ChatIDs) == 0 {
+ return fmt.Errorf("no telegram chat IDs configured")
+ }
+
+ shoutrrrURL, err := BuildTelegramURL(config)
+ if err != nil {
+ return fmt.Errorf("failed to build shoutrrr Telegram URL: %w", err)
+ }
+
+ sender, err := shoutrrr.CreateSender(shoutrrrURL)
+ if err != nil {
+ return fmt.Errorf("failed to create shoutrrr Telegram sender: %w", err)
+ }
+
+ errs := sender.Send(message, nil)
+ for _, err := range errs {
+ if err != nil {
+ return fmt.Errorf("failed to send Telegram message via shoutrrr: %w", err)
+ }
+ }
+ return nil
+}
diff --git a/backend/internal/utils/notifications/telegram_sender_test.go b/backend/internal/utils/notifications/telegram_sender_test.go
new file mode 100644
index 000000000..dd0098882
--- /dev/null
+++ b/backend/internal/utils/notifications/telegram_sender_test.go
@@ -0,0 +1,58 @@
+package notifications
+
+import (
+ "testing"
+
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestBuildTelegramURL(t *testing.T) {
+ tests := []struct {
+ name string
+ config models.TelegramConfig
+ wantURL string
+ }{
+ {
+ name: "basic config with single chat",
+ config: models.TelegramConfig{
+ BotToken: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11",
+ ChatIDs: []string{"@channel"},
+ Preview: true,
+ Notification: true,
+ },
+ wantURL: "telegram://123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11@telegram?chats=%40channel",
+ },
+ {
+ name: "config with multiple chats",
+ config: models.TelegramConfig{
+ BotToken: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11",
+ ChatIDs: []string{"@channel1", "123456789"},
+ Preview: false,
+ Notification: false,
+ Title: "Arcane",
+ },
+ wantURL: "telegram://123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11@telegram?chats=%40channel1%2C123456789&notification=No&preview=No&title=Arcane",
+ },
+ {
+ name: "config with title",
+ config: models.TelegramConfig{
+ BotToken: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11",
+ ChatIDs: []string{"@mybot"},
+ Preview: true,
+ Notification: true,
+ Title: "Container Updates",
+ },
+ wantURL: "telegram://123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11@telegram?chats=%40mybot&title=Container+Updates",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ gotURL, err := BuildTelegramURL(tt.config)
+ require.NoError(t, err)
+ assert.Equal(t, tt.wantURL, gotURL)
+ })
+ }
+}
diff --git a/backend/internal/utils/notifications/utils.go b/backend/internal/utils/notifications/utils.go
new file mode 100644
index 000000000..faf9ea3c9
--- /dev/null
+++ b/backend/internal/utils/notifications/utils.go
@@ -0,0 +1,14 @@
+package notifications
+
+import "strings"
+
+// SanitizeForEmail sanitizes text for safe use in email subjects
+func SanitizeForEmail(text string) string {
+ // Remove control characters and newlines
+ text = strings.ReplaceAll(text, "\r", "")
+ text = strings.ReplaceAll(text, "\n", " ")
+ text = strings.ReplaceAll(text, "\t", " ")
+
+ // Trim whitespace
+ return strings.TrimSpace(text)
+}
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 5f236ee73..bd9f67b6b 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -1478,16 +1478,18 @@
"notifications_discord_description": "Send notifications to Discord when container updates are detected",
"notifications_discord_enabled_label": "Enable Discord Notifications",
"notifications_discord_enabled_description": "Send update notifications to Discord via webhook",
- "notifications_discord_webhook_url_label": "Webhook URL",
- "notifications_discord_webhook_url_placeholder": "https://discord.com/api/webhooks/...",
- "notifications_discord_webhook_url_help": "Discord webhook URL for sending notifications",
+ "notifications_discord_webhook_id_label": "Webhook ID",
+ "notifications_discord_webhook_id_placeholder": "Enter webhook ID",
+ "notifications_discord_webhook_id_help": "The webhook ID from your Discord webhook URL (found after /webhooks/)",
+ "notifications_discord_token_label": "Webhook Token",
+ "notifications_discord_token_placeholder": "Enter webhook token",
+ "notifications_discord_token_help": "The token from your Discord webhook URL (the second part after the webhook ID)",
"notifications_discord_username_label": "Bot Username",
"notifications_discord_username_placeholder": "Arcane",
"notifications_discord_username_help": "Display name for the notification bot",
"notifications_discord_avatar_url_label": "Avatar URL (Optional)",
"notifications_discord_avatar_url_placeholder": "https://...",
"notifications_discord_avatar_url_help": "Avatar image URL for the notification bot",
- "notifications_discord_test_button": "Test Discord",
"notifications_email_title": "Email Notifications",
"notifications_email_description": "Send notifications via email when container updates are detected",
"notifications_email_enabled_label": "Enable Email Notifications",
@@ -1510,7 +1512,6 @@
"notifications_email_to_addresses_label": "To Addresses",
"notifications_email_to_addresses_placeholder": "[email protected], [email protected]",
"notifications_email_to_addresses_help": "Comma-separated list of email addresses to send notifications to",
- "notifications_email_test_button": "Test Email",
"notifications_saved_failed": "Failed to save {provider} settings: {error}",
"notifications_test_success": "Test notification sent successfully via {provider}",
"notifications_test_failed": "Failed to send test notification: {error}",
@@ -1539,10 +1540,130 @@
"notifications_apprise_container_tag_label": "Container Update Tag",
"notifications_apprise_container_tag_placeholder": "container-updates",
"notifications_apprise_container_tag_help": "Optional tag for container update notifications",
- "notifications_apprise_test_button": "Test Apprise",
+ "notifications_signal_title": "Signal Notifications",
+ "notifications_signal_description": "Send notifications via Signal Messenger through a Signal API server",
+ "notifications_signal_enabled_label": "Enable Signal Notifications",
+ "notifications_signal_host_label": "Signal API Host",
+ "notifications_signal_host_placeholder": "localhost",
+ "notifications_signal_host_help": "Hostname or IP address of your Signal REST API server",
+ "notifications_signal_host_required": "Host is required when Signal is enabled",
+ "notifications_signal_port_label": "Port",
+ "notifications_signal_port_placeholder": "8080",
+ "notifications_signal_port_help": "Port number of your Signal REST API server",
+ "notifications_signal_port_invalid": "Port must be between 1 and 65535",
+ "notifications_signal_auth_section": "Authentication",
+ "notifications_signal_auth_help": "Provide either Basic Auth (username + password) OR Bearer Token authentication, not both",
+ "notifications_signal_auth_or": "or",
+ "notifications_signal_user_label": "Username (Basic Auth)",
+ "notifications_signal_user_placeholder": "api_user",
+ "notifications_signal_user_help": "Username for HTTP Basic Auth",
+ "notifications_signal_password_label": "Password (Basic Auth)",
+ "notifications_signal_password_placeholder": "••••••••",
+ "notifications_signal_password_help": "Password for HTTP Basic Auth",
+ "notifications_signal_token_label": "API Token (Bearer Auth)",
+ "notifications_signal_token_placeholder": "your-api-token",
+ "notifications_signal_token_help": "Bearer token for API authentication",
+ "notifications_signal_auth_required": "Either Basic Auth (username + password) or API Token is required",
+ "notifications_signal_auth_conflict": "Cannot use both Basic Auth and API Token authentication",
+ "notifications_signal_source_label": "Source Phone Number",
+ "notifications_signal_source_placeholder": "+1234567890",
+ "notifications_signal_source_help": "Your Signal phone number with country code (must start with +)",
+ "notifications_signal_source_required": "Source phone number is required when Signal is enabled",
+ "notifications_signal_source_format": "Source phone number must start with + and include country code",
+ "notifications_signal_recipients_label": "Recipients",
+ "notifications_signal_recipients_placeholder": "+1234567890, +0987654321, group_id_base64",
+ "notifications_signal_recipients_help": "Comma-separated list of phone numbers (with +) or Signal group IDs",
+ "notifications_signal_recipients_required": "At least one recipient is required when Signal is enabled",
+ "notifications_signal_disable_tls_label": "Disable TLS",
+ "notifications_signal_disable_tls_description": "Disable TLS/SSL for Signal REST API connection (not recommended for production)",
+ "notifications_slack_title": "Slack Notifications",
+ "notifications_slack_description": "Send notifications to Slack channels or direct messages",
+ "notifications_slack_enabled_label": "Enable Slack Notifications",
+ "notifications_slack_token_label": "Slack Token",
+ "notifications_slack_token_placeholder": "xoxb-... or xoxp-...",
+ "notifications_slack_token_help": "API token (xoxb-, xoxp-) or webhook token (hook-)",
+ "notifications_slack_token_required": "Token is required when Slack is enabled",
+ "notifications_slack_bot_name_label": "Bot Name (Optional)",
+ "notifications_slack_bot_name_placeholder": "Arcane",
+ "notifications_slack_bot_name_help": "Display name for the bot in Slack",
+ "notifications_slack_channel_label": "Channel (Optional)",
+ "notifications_slack_channel_placeholder": "#notifications",
+ "notifications_slack_channel_help": "Override default channel (include # for public channels)",
+ "notifications_slack_icon_label": "Icon (Optional)",
+ "notifications_slack_icon_placeholder": ":robot_face: or https://...",
+ "notifications_slack_icon_help": "Emoji (e.g., :robot_face:) or image URL for bot avatar",
+ "notifications_slack_color_label": "Message Color (Optional)",
+ "notifications_slack_color_placeholder": "#FF0000",
+ "notifications_slack_color_help": "Hex color code for message sidebar",
+ "notifications_slack_title_label": "Message Title (Optional)",
+ "notifications_slack_title_placeholder": "Container Update",
+ "notifications_slack_title_help": "Prepended text above the message",
+ "notifications_slack_thread_ts_label": "Thread TS (Optional)",
+ "notifications_slack_thread_ts_placeholder": "1234567890.123456",
+ "notifications_slack_thread_ts_help": "Reply in a thread (ts value of parent message)",
+ "notifications_ntfy_title": "Ntfy Notifications",
+ "notifications_ntfy_description": "Send notifications via ntfy.sh when container updates are detected",
+ "notifications_ntfy_enabled_label": "Enable Ntfy Notifications",
+ "notifications_ntfy_enabled_description": "Send update notifications via ntfy service",
+ "notifications_ntfy_host_label": "Host",
+ "notifications_ntfy_host_placeholder": "ntfy.sh",
+ "notifications_ntfy_host_help": "Ntfy server hostname (defaults to ntfy.sh)",
+ "notifications_ntfy_port_label": "Port (Optional)",
+ "notifications_ntfy_port_placeholder": "0",
+ "notifications_ntfy_port_help": "Port number for ntfy server (leave empty or 0 for default)",
+ "notifications_ntfy_topic_label": "Topic",
+ "notifications_ntfy_topic_placeholder": "my-updates",
+ "notifications_ntfy_topic_help": "Topic name to publish notifications to (required, treat as a password)",
+ "notifications_ntfy_username_label": "Username (Optional)",
+ "notifications_ntfy_username_placeholder": "username",
+ "notifications_ntfy_username_help": "Username for authentication (if required by server)",
+ "notifications_ntfy_password_label": "Password (Optional)",
+ "notifications_ntfy_password_placeholder": "••••••••",
+ "notifications_ntfy_password_help": "Password for authentication (if required by server)",
+ "notifications_ntfy_priority_label": "Priority",
+ "notifications_ntfy_priority_help": "Notification priority level (Min=1, Low=2, Default=3, High=4, Max/Urgent=5)",
+ "notifications_ntfy_tags_label": "Tags (Optional)",
+ "notifications_ntfy_tags_placeholder": "warning, server, docker",
+ "notifications_ntfy_tags_help": "Comma-separated list of tags (may map to emojis on supported clients)",
+ "notifications_ntfy_icon_label": "Icon URL (Optional)",
+ "notifications_ntfy_icon_placeholder": "https://...",
+ "notifications_ntfy_icon_help": "URL to use as notification icon",
+ "notifications_ntfy_cache_label": "Cache Messages",
+ "notifications_ntfy_cache_help": "Allow ntfy server to cache messages (enabled by default)",
+ "notifications_ntfy_firebase_label": "Firebase Notifications",
+ "notifications_ntfy_firebase_help": "Send notifications via Firebase (enabled by default)",
+ "notifications_ntfy_disable_tls_label": "Disable TLS Verification",
+ "notifications_ntfy_disable_tls_help": "Disable TLS certificate verification (not recommended)",
+ "notifications_generic_title": "Generic Webhook",
+ "notifications_generic_description": "Send notifications to any webhook endpoint that accepts HTTP POST requests",
+ "notifications_generic_enabled_label": "Enable Generic Webhook Notifications",
+ "notifications_generic_webhook_url_label": "Webhook URL",
+ "notifications_generic_webhook_url_placeholder": "https://example.com/webhook",
+ "notifications_generic_webhook_url_help": "The full webhook endpoint URL including protocol (http:// or https://)",
+ "notifications_generic_method_label": "HTTP Method",
+ "notifications_generic_method_placeholder": "POST",
+ "notifications_generic_method_help": "HTTP method to use for requests (default: POST)",
+ "notifications_generic_content_type_label": "Content Type",
+ "notifications_generic_content_type_placeholder": "application/json",
+ "notifications_generic_content_type_help": "Content-Type header value (default: application/json)",
+ "notifications_generic_title_key_label": "Title Key",
+ "notifications_generic_title_key_placeholder": "title",
+ "notifications_generic_title_key_help": "JSON key name for the notification title (default: title)",
+ "notifications_generic_message_key_label": "Message Key",
+ "notifications_generic_message_key_placeholder": "message",
+ "notifications_generic_message_key_help": "JSON key name for the notification message (default: message)",
+ "notifications_generic_custom_headers_label": "Custom Headers (Optional)",
+ "notifications_generic_custom_headers_placeholder": "Authorization:Bearer token, X-Custom:value",
+ "notifications_generic_custom_headers_help": "Comma-separated list of custom headers in format 'Key:Value' (e.g., Authorization:Bearer token)",
+ "notifications_generic_disable_tls_label": "Disable TLS (Use HTTP)",
+ "notifications_generic_disable_tls_help": "Use HTTP instead of HTTPS (not recommended for production)",
+ "notifications_test_notification": "Test Provider",
"notifications_unsaved_changes_title": "Unsaved Changes",
"notifications_unsaved_changes_description": "You have unsaved changes. Would you like to save them before testing?",
"notifications_unsaved_changes_save_and_test": "Save & Test",
+ "notifications_shoutrrr_providers_title": "Notification Providers",
+ "notifications_shoutrrr_tab_email": "Email",
+ "notifications_shoutrrr_tab_discord": "Discord",
"glass_effect_title": "Glass Effect (Preview)",
"glass_effect_description": "Enable modern glassmorphism design with blur, gradients, and ambient effects",
"glass_effect_label": "Glassmorphism UI",
diff --git a/frontend/src/lib/types/notification-providers.ts b/frontend/src/lib/types/notification-providers.ts
new file mode 100644
index 000000000..de6dc25e0
--- /dev/null
+++ b/frontend/src/lib/types/notification-providers.ts
@@ -0,0 +1,433 @@
+import type { NotificationSettings, AppriseSettings, EmailTLSMode } from './notification.type';
+
+// Provider keys - this is the source of truth for all providers (alphabetically sorted)
+export const NOTIFICATION_PROVIDER_KEYS = ['discord', 'email', 'generic', 'ntfy', 'signal', 'slack', 'telegram'] as const;
+export type NotificationProviderKey = (typeof NOTIFICATION_PROVIDER_KEYS)[number];
+
+// Base form values that all providers share
+export interface BaseProviderFormValues {
+ enabled: boolean;
+ eventImageUpdate: boolean;
+ eventContainerUpdate: boolean;
+}
+
+// Provider-specific form value types
+export interface DiscordFormValues extends BaseProviderFormValues {
+ webhookId: string;
+ token: string;
+ username: string;
+ avatarUrl: string;
+}
+
+export interface EmailFormValues extends BaseProviderFormValues {
+ smtpHost: string;
+ smtpPort: number;
+ smtpUsername: string;
+ smtpPassword: string;
+ fromAddress: string;
+ toAddresses: string;
+ tlsMode: EmailTLSMode;
+}
+
+export interface TelegramFormValues extends BaseProviderFormValues {
+ botToken: string;
+ chatIds: string;
+ preview: boolean;
+ notification: boolean;
+ title: string;
+}
+
+export interface SignalFormValues extends BaseProviderFormValues {
+ host: string;
+ port: number;
+ user: string;
+ password: string;
+ token: string;
+ source: string;
+ recipients: string;
+ disableTls: boolean;
+}
+
+export interface SlackFormValues extends BaseProviderFormValues {
+ token: string;
+ botName: string;
+ icon: string;
+ color: string;
+ title: string;
+ channel: string;
+ threadTs: string;
+}
+
+export interface NtfyFormValues extends BaseProviderFormValues {
+ host: string;
+ port: number;
+ topic: string;
+ username: string;
+ password: string;
+ priority: string;
+ tags: string;
+ icon: string;
+ cache: boolean;
+ firebase: boolean;
+ disableTlsVerification: boolean;
+}
+
+export interface GenericFormValues extends BaseProviderFormValues {
+ webhookUrl: string;
+ method: string;
+ contentType: string;
+ titleKey: string;
+ messageKey: string;
+ customHeaders: string;
+ disableTls: boolean;
+}
+
+export interface AppriseFormValues {
+ enabled: boolean;
+ apiUrl: string;
+ imageUpdateTag: string;
+ containerUpdateTag: string;
+}
+
+// Union type for all provider form values
+export type ProviderFormValues =
+ | DiscordFormValues
+ | EmailFormValues
+ | TelegramFormValues
+ | SignalFormValues
+ | SlackFormValues
+ | NtfyFormValues
+ | GenericFormValues;
+
+// Map provider keys to their form value types
+export type ProviderFormValuesMap = {
+ discord: DiscordFormValues;
+ email: EmailFormValues;
+ telegram: TelegramFormValues;
+ signal: SignalFormValues;
+ slack: SlackFormValues;
+ ntfy: NtfyFormValues;
+ generic: GenericFormValues;
+};
+
+// Provider state with current values and saved baseline
+export interface ProviderState<T> {
+ current: T;
+ baseline: T;
+ hasChanges: boolean;
+ isValid: boolean;
+ errors: Partial<Record<keyof T, string>>;
+}
+
+// Helper to convert settings to form values
+export function discordSettingsToFormValues(settings?: NotificationSettings): DiscordFormValues {
+ const cfg = (settings?.config ?? {}) as Record<string, unknown>;
+ const events = (cfg?.events ?? {}) as Record<string, boolean>;
+ return {
+ enabled: settings?.enabled ?? false,
+ webhookId: (cfg?.webhookId as string) || '',
+ token: (cfg?.token as string) || '',
+ username: (cfg?.username as string) || 'Arcane',
+ avatarUrl: (cfg?.avatarUrl as string) || '',
+ eventImageUpdate: events?.image_update ?? true,
+ eventContainerUpdate: events?.container_update ?? true
+ };
+}
+
+export function emailSettingsToFormValues(settings?: NotificationSettings): EmailFormValues {
+ const cfg = (settings?.config ?? {}) as Record<string, unknown>;
+ const events = (cfg?.events ?? {}) as Record<string, boolean>;
+ return {
+ enabled: settings?.enabled ?? false,
+ smtpHost: (cfg?.smtpHost as string) || '',
+ smtpPort: (cfg?.smtpPort as number) || 587,
+ smtpUsername: (cfg?.smtpUsername as string) || '',
+ smtpPassword: (cfg?.smtpPassword as string) || '',
+ fromAddress: (cfg?.fromAddress as string) || '',
+ toAddresses: Array.isArray(cfg?.toAddresses) ? (cfg.toAddresses as string[]).join(', ') : '',
+ tlsMode: ((cfg?.tlsMode as string) || 'starttls') as EmailTLSMode,
+ eventImageUpdate: events?.image_update ?? true,
+ eventContainerUpdate: events?.container_update ?? true
+ };
+}
+
+export function telegramSettingsToFormValues(settings?: NotificationSettings): TelegramFormValues {
+ const cfg = (settings?.config ?? {}) as Record<string, unknown>;
+ const events = (cfg?.events ?? {}) as Record<string, boolean>;
+ return {
+ enabled: settings?.enabled ?? false,
+ botToken: (cfg?.botToken as string) || '',
+ chatIds: Array.isArray(cfg?.chatIds) ? (cfg.chatIds as string[]).join(', ') : '',
+ preview: (cfg?.preview as boolean) ?? true,
+ notification: (cfg?.notification as boolean) ?? true,
+ title: (cfg?.title as string) || '',
+ eventImageUpdate: events?.image_update ?? true,
+ eventContainerUpdate: events?.container_update ?? true
+ };
+}
+
+export function signalSettingsToFormValues(settings?: NotificationSettings): SignalFormValues {
+ const cfg = (settings?.config ?? {}) as Record<string, unknown>;
+ const events = (cfg?.events ?? {}) as Record<string, boolean>;
+ return {
+ enabled: settings?.enabled ?? false,
+ host: (cfg?.host as string) || 'localhost',
+ port: (cfg?.port as number) || 8080,
+ user: (cfg?.user as string) || '',
+ password: (cfg?.password as string) || '',
+ token: (cfg?.token as string) || '',
+ source: (cfg?.source as string) || '',
+ recipients: Array.isArray(cfg?.recipients) ? (cfg.recipients as string[]).join(', ') : '',
+ disableTls: (cfg?.disableTls as boolean) ?? false,
+ eventImageUpdate: events?.image_update ?? true,
+ eventContainerUpdate: events?.container_update ?? true
+ };
+}
+
+export function slackSettingsToFormValues(settings?: NotificationSettings): SlackFormValues {
+ const cfg = (settings?.config ?? {}) as Record<string, unknown>;
+ const events = (cfg?.events ?? {}) as Record<string, boolean>;
+ return {
+ enabled: settings?.enabled ?? false,
+ token: (cfg?.token as string) || '',
+ botName: (cfg?.botName as string) || 'Arcane',
+ icon: (cfg?.icon as string) || '',
+ color: (cfg?.color as string) || '',
+ title: (cfg?.title as string) || '',
+ channel: (cfg?.channel as string) || '',
+ threadTs: (cfg?.threadTs as string) || '',
+ eventImageUpdate: events?.image_update ?? true,
+ eventContainerUpdate: events?.container_update ?? true
+ };
+}
+
+export function appriseSettingsToFormValues(settings?: AppriseSettings): AppriseFormValues {
+ return {
+ enabled: settings?.enabled ?? false,
+ apiUrl: settings?.apiUrl || '',
+ imageUpdateTag: settings?.imageUpdateTag || '',
+ containerUpdateTag: settings?.containerUpdateTag || ''
+ };
+}
+
+// Helper to convert form values back to API format
+export function discordFormValuesToSettings(values: DiscordFormValues): NotificationSettings {
+ return {
+ provider: 'discord',
+ enabled: values.enabled,
+ config: {
+ webhookId: values.webhookId,
+ token: values.token,
+ username: values.username,
+ avatarUrl: values.avatarUrl,
+ events: {
+ image_update: values.eventImageUpdate,
+ container_update: values.eventContainerUpdate
+ }
+ }
+ };
+}
+
+export function emailFormValuesToSettings(values: EmailFormValues): NotificationSettings {
+ return {
+ provider: 'email',
+ enabled: values.enabled,
+ config: {
+ smtpHost: values.smtpHost,
+ smtpPort: values.smtpPort,
+ smtpUsername: values.smtpUsername,
+ smtpPassword: values.smtpPassword,
+ fromAddress: values.fromAddress,
+ toAddresses: values.toAddresses
+ .split(',')
+ .map((addr) => addr.trim())
+ .filter((addr) => addr.length > 0),
+ tlsMode: values.tlsMode,
+ events: {
+ image_update: values.eventImageUpdate,
+ container_update: values.eventContainerUpdate
+ }
+ }
+ };
+}
+
+export function telegramFormValuesToSettings(values: TelegramFormValues): NotificationSettings {
+ return {
+ provider: 'telegram',
+ enabled: values.enabled,
+ config: {
+ botToken: values.botToken,
+ chatIds: values.chatIds
+ .split(',')
+ .map((id) => id.trim())
+ .filter((id) => id.length > 0),
+ preview: values.preview,
+ notification: values.notification,
+ title: values.title,
+ events: {
+ image_update: values.eventImageUpdate,
+ container_update: values.eventContainerUpdate
+ }
+ }
+ };
+}
+
+export function signalFormValuesToSettings(values: SignalFormValues): NotificationSettings {
+ return {
+ provider: 'signal',
+ enabled: values.enabled,
+ config: {
+ host: values.host,
+ port: values.port,
+ user: values.user,
+ password: values.password,
+ token: values.token,
+ source: values.source,
+ recipients: values.recipients
+ .split(',')
+ .map((recipient) => recipient.trim())
+ .filter((recipient) => recipient.length > 0),
+ disableTls: values.disableTls,
+ events: {
+ image_update: values.eventImageUpdate,
+ container_update: values.eventContainerUpdate
+ }
+ }
+ };
+}
+
+export function slackFormValuesToSettings(values: SlackFormValues): NotificationSettings {
+ return {
+ provider: 'slack',
+ enabled: values.enabled,
+ config: {
+ token: values.token,
+ botName: values.botName,
+ icon: values.icon,
+ color: values.color,
+ title: values.title,
+ channel: values.channel,
+ threadTs: values.threadTs,
+ events: {
+ image_update: values.eventImageUpdate,
+ container_update: values.eventContainerUpdate
+ }
+ }
+ };
+}
+
+export function ntfySettingsToFormValues(settings?: NotificationSettings): NtfyFormValues {
+ const cfg = (settings?.config ?? {}) as Record<string, unknown>;
+ const events = (cfg?.events ?? {}) as Record<string, boolean>;
+ return {
+ enabled: settings?.enabled ?? false,
+ host: (cfg?.host as string) || 'ntfy.sh',
+ port: (cfg?.port as number) || 0,
+ topic: (cfg?.topic as string) || '',
+ username: (cfg?.username as string) || '',
+ password: (cfg?.password as string) || '',
+ priority: (cfg?.priority as string) || 'default',
+ tags: Array.isArray(cfg?.tags) ? (cfg.tags as string[]).join(', ') : '',
+ icon: (cfg?.icon as string) || '',
+ cache: (cfg?.cache as boolean) ?? true,
+ firebase: (cfg?.firebase as boolean) ?? true,
+ disableTlsVerification: (cfg?.disableTlsVerification as boolean) ?? false,
+ eventImageUpdate: events?.image_update ?? true,
+ eventContainerUpdate: events?.container_update ?? true
+ };
+}
+
+export function genericSettingsToFormValues(settings?: NotificationSettings): GenericFormValues {
+ const cfg = (settings?.config ?? {}) as Record<string, unknown>;
+ const events = (cfg?.events ?? {}) as Record<string, boolean>;
+ const customHeaders = (cfg?.customHeaders ?? {}) as Record<string, string>;
+
+ // Convert customHeaders object to string format (key1:value1, key2:value2)
+ const customHeadersStr = Object.entries(customHeaders)
+ .map(([key, value]) => `${key}:${value}`)
+ .join(', ');
+
+ return {
+ enabled: settings?.enabled ?? false,
+ webhookUrl: (cfg?.webhookUrl as string) || '',
+ method: (cfg?.method as string) || 'POST',
+ contentType: (cfg?.contentType as string) || 'application/json',
+ titleKey: (cfg?.titleKey as string) || 'title',
+ messageKey: (cfg?.messageKey as string) || 'message',
+ customHeaders: customHeadersStr,
+ disableTls: (cfg?.disableTls as boolean) ?? false,
+ eventImageUpdate: events?.image_update ?? true,
+ eventContainerUpdate: events?.container_update ?? true
+ };
+}
+
+export function ntfyFormValuesToSettings(values: NtfyFormValues): NotificationSettings {
+ return {
+ provider: 'ntfy',
+ enabled: values.enabled,
+ config: {
+ host: values.host,
+ port: values.port,
+ topic: values.topic,
+ username: values.username,
+ password: values.password,
+ priority: values.priority,
+ tags: values.tags
+ .split(',')
+ .map((tag) => tag.trim())
+ .filter((tag) => tag.length > 0),
+ icon: values.icon,
+ cache: values.cache,
+ firebase: values.firebase,
+ disableTlsVerification: values.disableTlsVerification,
+ events: {
+ image_update: values.eventImageUpdate,
+ container_update: values.eventContainerUpdate
+ }
+ }
+ };
+}
+
+export function genericFormValuesToSettings(values: GenericFormValues): NotificationSettings {
+ // Parse customHeaders string (format: "key1:value1, key2:value2") into object
+ const customHeaders: Record<string, string> = {};
+ if (values.customHeaders) {
+ const headerPairs = values.customHeaders
+ .split(',')
+ .map((h) => h.trim())
+ .filter((h) => h.length > 0);
+ for (const pair of headerPairs) {
+ const [key, ...valueParts] = pair.split(':');
+ if (key && valueParts.length > 0) {
+ customHeaders[key.trim()] = valueParts.join(':').trim();
+ }
+ }
+ }
+
+ return {
+ provider: 'generic',
+ enabled: values.enabled,
+ config: {
+ webhookUrl: values.webhookUrl,
+ method: values.method,
+ contentType: values.contentType,
+ titleKey: values.titleKey,
+ messageKey: values.messageKey,
+ customHeaders: customHeaders,
+ disableTls: values.disableTls,
+ events: {
+ image_update: values.eventImageUpdate,
+ container_update: values.eventContainerUpdate
+ }
+ }
+ };
+}
+
+export function appriseFormValuesToSettings(values: AppriseFormValues): AppriseSettings {
+ return {
+ enabled: values.enabled,
+ apiUrl: values.apiUrl,
+ imageUpdateTag: values.imageUpdateTag,
+ containerUpdateTag: values.containerUpdateTag
+ };
+}
diff --git a/frontend/src/lib/types/notification.type.ts b/frontend/src/lib/types/notification.type.ts
index 5e252ea18..ba3194d03 100644
--- a/frontend/src/lib/types/notification.type.ts
+++ b/frontend/src/lib/types/notification.type.ts
@@ -1,4 +1,4 @@
-export type NotificationProvider = 'discord' | 'email';
+export type NotificationProvider = 'discord' | 'email' | 'telegram' | 'signal' | 'slack' | 'ntfy' | 'generic';
export type EmailTLSMode = 'none' | 'starttls' | 'ssl';
export interface NotificationSettings {
diff --git a/frontend/src/routes/(app)/settings/notifications/+page.svelte b/frontend/src/routes/(app)/settings/notifications/+page.svelte
index d576dbf54..9c5e19149 100644
--- a/frontend/src/routes/(app)/settings/notifications/+page.svelte
+++ b/frontend/src/routes/(app)/settings/notifications/+page.svelte
@@ -1,201 +1,136 @@
<script lang="ts">
import * as Alert from '$lib/components/ui/alert';
- import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
import * as Tabs from '$lib/components/ui/tabs';
import * as Dialog from '$lib/components/ui/dialog';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import { toast } from 'svelte-sonner';
import { getContext, onMount } from 'svelte';
- import { z } from 'zod/v4';
- import { createForm } from '$lib/utils/form.utils';
- import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
- import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
- import SelectWithLabel from '$lib/components/form/select-with-label.svelte';
import { SettingsPageLayout } from '$lib/layouts';
import settingsStore from '$lib/stores/config-store';
- import { Label } from '$lib/components/ui/label';
- import { Input } from '$lib/components/ui/input';
- import Textarea from '$lib/components/ui/textarea/textarea.svelte';
import { m } from '$lib/paraglide/messages';
import { notificationService } from '$lib/services/notification-service';
- import type { EmailTLSMode, AppriseSettings } from '$lib/types/notification.type';
- import { Switch } from '$lib/components/ui/switch/index.js';
- import { NotificationsIcon, SendEmailIcon, ArrowDownIcon } from '$lib/icons';
-
- interface FormNotificationSettings {
- discordEnabled: boolean;
- discordWebhookUrl: string;
- discordUsername: string;
- discordAvatarUrl: string;
- discordEventImageUpdate: boolean;
- discordEventContainerUpdate: boolean;
- emailEnabled: boolean;
- emailSmtpHost: string;
- emailSmtpPort: number;
- emailSmtpUsername: string;
- emailSmtpPassword: string;
- emailFromAddress: string;
- emailToAddresses: string;
- emailTlsMode: EmailTLSMode;
- emailEventImageUpdate: boolean;
- emailEventContainerUpdate: boolean;
- }
+ import type { NotificationSettings } from '$lib/types/notification.type';
+ import {
+ type DiscordFormValues,
+ type EmailFormValues,
+ type TelegramFormValues,
+ type SignalFormValues,
+ type SlackFormValues,
+ type NtfyFormValues,
+ type GenericFormValues,
+ type AppriseFormValues,
+ type NotificationProviderKey,
+ NOTIFICATION_PROVIDER_KEYS,
+ discordSettingsToFormValues,
+ emailSettingsToFormValues,
+ telegramSettingsToFormValues,
+ signalSettingsToFormValues,
+ slackSettingsToFormValues,
+ ntfySettingsToFormValues,
+ genericSettingsToFormValues,
+ appriseSettingsToFormValues,
+ discordFormValuesToSettings,
+ emailFormValuesToSettings,
+ telegramFormValuesToSettings,
+ signalFormValuesToSettings,
+ slackFormValuesToSettings,
+ ntfyFormValuesToSettings,
+ genericFormValuesToSettings,
+ appriseFormValuesToSettings
+ } from '$lib/types/notification-providers';
+ import { NotificationsIcon } from '$lib/icons';
+ import {
+ EmailProviderForm,
+ DiscordProviderForm,
+ TelegramProviderForm,
+ SignalProviderForm,
+ SlackProviderForm,
+ NtfyProviderForm,
+ GenericProviderForm,
+ AppriseProviderForm
+ } from './providers';
let { data } = $props();
+
+ // UI state
let isLoading = $state(false);
let isTesting = $state(false);
let showUnsavedDialog = $state(false);
let pendingTestAction: (() => Promise<void>) | null = $state(null);
- const isReadOnly = $derived.by(() => $settingsStore.uiConfigDisabled);
- const formState = getContext('settingsFormState') as any;
+ let notificationsTab = $state<'built-in' | 'apprise'>('built-in');
+ let providerTab = $state<NotificationProviderKey>('email');
- let appriseSettings: AppriseSettings = $state({
- apiUrl: '',
- enabled: false,
- imageUpdateTag: '',
- containerUpdateTag: ''
- });
+ const isReadOnly = $derived.by(() => $settingsStore.uiConfigDisabled);
- let savedAppriseSettings: AppriseSettings = $state({
- apiUrl: '',
- enabled: false,
- imageUpdateTag: '',
- containerUpdateTag: ''
- });
+ // Settings form context
+ let formState: any = null;
+ try {
+ formState = getContext('settingsFormState') as any;
+ } catch {
+ // Context not available (shouldn't happen in settings routes)
+ }
- // IMPORTANT: don't call `form.validate()` inside a `$derived` — it updates stores and will throw
- // `state_unsafe_mutation`, which can make buttons appear unresponsive until refresh.
- let currentSettings = $state<FormNotificationSettings>({
- discordEnabled: false,
- discordWebhookUrl: '',
- discordUsername: 'Arcane',
- discordAvatarUrl: '',
- discordEventImageUpdate: true,
- discordEventContainerUpdate: true,
- emailEnabled: false,
- emailSmtpHost: '',
- emailSmtpPort: 587,
- emailSmtpUsername: '',
- emailSmtpPassword: '',
- emailFromAddress: '',
- emailToAddresses: '',
- emailTlsMode: 'starttls',
- emailEventImageUpdate: true,
- emailEventContainerUpdate: true
+ // Provider form references for validation
+ let emailFormRef: EmailProviderForm;
+ let discordFormRef: DiscordProviderForm;
+ let telegramFormRef: TelegramProviderForm;
+ let signalFormRef: SignalProviderForm;
+ let slackFormRef: SlackProviderForm;
+ let ntfyFormRef: NtfyProviderForm;
+ let genericFormRef: GenericProviderForm;
+
+ // Saved settings from server (used to detect if settings exist)
+ let savedSettings = $state<Record<NotificationProviderKey, NotificationSettings | null>>({
+ email: null,
+ discord: null,
+ telegram: null,
+ signal: null,
+ slack: null,
+ ntfy: null,
+ generic: null
});
- const formSchema = z
- .object({
- discordEnabled: z.boolean(),
- discordWebhookUrl: z.url().or(z.literal('')),
- discordUsername: z.string(),
- discordAvatarUrl: z.string(),
- discordEventImageUpdate: z.boolean(),
- discordEventContainerUpdate: z.boolean(),
- emailEnabled: z.boolean(),
- emailSmtpHost: z.string(),
- emailSmtpPort: z.number().int().min(1).max(65535),
- emailSmtpUsername: z.string(),
- emailSmtpPassword: z.string(),
- emailFromAddress: z.email().or(z.literal('')),
- emailToAddresses: z.string(),
- emailTlsMode: z.enum(['none', 'starttls', 'ssl']),
- emailEventImageUpdate: z.boolean(),
- emailEventContainerUpdate: z.boolean()
- })
- .superRefine((data, ctx) => {
- // Validate Discord fields when Discord is enabled
- if (data.discordEnabled && !data.discordWebhookUrl.trim()) {
- ctx.addIssue({
- code: 'custom',
- message: 'Webhook URL is required when Discord is enabled',
- path: ['discordWebhookUrl']
- });
- } // Validate Email fields when Email is enabled
- if (data.emailEnabled) {
- if (!data.emailSmtpHost.trim()) {
- ctx.addIssue({
- code: 'custom',
- message: 'SMTP host is required when email is enabled',
- path: ['emailSmtpHost']
- });
- }
-
- if (!data.emailFromAddress.trim()) {
- ctx.addIssue({
- code: 'custom',
- message: 'From address is required when email is enabled',
- path: ['emailFromAddress']
- });
- } else {
- // Validate email format using Zod's built-in email validator
- const emailValidation = z.string().email().safeParse(data.emailFromAddress.trim());
- if (!emailValidation.success) {
- ctx.addIssue({
- code: 'custom',
- message: 'Invalid email address format',
- path: ['emailFromAddress']
- });
- }
- }
-
- if (!data.emailToAddresses.trim()) {
- ctx.addIssue({
- code: 'custom',
- message: 'At least one recipient address is required when email is enabled',
- path: ['emailToAddresses']
- });
- } else {
- // Validate each email in the comma-separated list
- const addresses = data.emailToAddresses
- .split(',')
- .map((addr) => addr.trim())
- .filter((addr) => addr.length > 0);
- const invalidAddresses: string[] = [];
-
- addresses.forEach((addr) => {
- const emailValidation = z.string().email().safeParse(addr);
- if (!emailValidation.success) {
- invalidAddresses.push(addr);
- }
- });
-
- if (invalidAddresses.length > 0) {
- ctx.addIssue({
- code: 'custom',
- message: `Invalid email addresses: ${invalidAddresses.join(', ')}`,
- path: ['emailToAddresses']
- });
- }
- }
- }
- });
-
- let { inputs: formInputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, currentSettings));
-
+ // Current form values - these are what the user edits
+ let emailValues = $state<EmailFormValues>(emailSettingsToFormValues());
+ let discordValues = $state<DiscordFormValues>(discordSettingsToFormValues());
+ let telegramValues = $state<TelegramFormValues>(telegramSettingsToFormValues());
+ let signalValues = $state<SignalFormValues>(signalSettingsToFormValues());
+ let slackValues = $state<SlackFormValues>(slackSettingsToFormValues());
+ let ntfyValues = $state<NtfyFormValues>(ntfySettingsToFormValues());
+ let genericValues = $state<GenericFormValues>(genericSettingsToFormValues());
+ let appriseValues = $state<AppriseFormValues>(appriseSettingsToFormValues());
+
+ // Baseline values - what was last saved (for change detection)
+ let emailBaseline = $state<EmailFormValues>(emailSettingsToFormValues());
+ let discordBaseline = $state<DiscordFormValues>(discordSettingsToFormValues());
+ let telegramBaseline = $state<TelegramFormValues>(telegramSettingsToFormValues());
+ let signalBaseline = $state<SignalFormValues>(signalSettingsToFormValues());
+ let slackBaseline = $state<SlackFormValues>(slackSettingsToFormValues());
+ let ntfyBaseline = $state<NtfyFormValues>(ntfySettingsToFormValues());
+ let genericBaseline = $state<GenericFormValues>(genericSettingsToFormValues());
+ let appriseBaseline = $state<AppriseFormValues>(appriseSettingsToFormValues());
+
+ // Change detection
+ const emailHasChanges = $derived(JSON.stringify(emailValues) !== JSON.stringify(emailBaseline));
+ const discordHasChanges = $derived(JSON.stringify(discordValues) !== JSON.stringify(discordBaseline));
+ const telegramHasChanges = $derived(JSON.stringify(telegramValues) !== JSON.stringify(telegramBaseline));
+ const signalHasChanges = $derived(JSON.stringify(signalValues) !== JSON.stringify(signalBaseline));
+ const slackHasChanges = $derived(JSON.stringify(slackValues) !== JSON.stringify(slackBaseline));
+ const ntfyHasChanges = $derived(JSON.stringify(ntfyValues) !== JSON.stringify(ntfyBaseline));
+ const genericHasChanges = $derived(JSON.stringify(genericValues) !== JSON.stringify(genericBaseline));
+ const appriseHasChanges = $derived(JSON.stringify(appriseValues) !== JSON.stringify(appriseBaseline));
const hasChanges = $derived(
- $formInputs.discordEnabled.value !== currentSettings.discordEnabled ||
- $formInputs.discordWebhookUrl.value !== currentSettings.discordWebhookUrl ||
- $formInputs.discordUsername.value !== currentSettings.discordUsername ||
- $formInputs.discordAvatarUrl.value !== currentSettings.discordAvatarUrl ||
- $formInputs.discordEventImageUpdate.value !== currentSettings.discordEventImageUpdate ||
- $formInputs.discordEventContainerUpdate.value !== currentSettings.discordEventContainerUpdate ||
- $formInputs.emailEnabled.value !== currentSettings.emailEnabled ||
- $formInputs.emailSmtpHost.value !== currentSettings.emailSmtpHost ||
- $formInputs.emailSmtpPort.value !== currentSettings.emailSmtpPort ||
- $formInputs.emailSmtpUsername.value !== currentSettings.emailSmtpUsername ||
- $formInputs.emailSmtpPassword.value !== currentSettings.emailSmtpPassword ||
- $formInputs.emailFromAddress.value !== currentSettings.emailFromAddress ||
- $formInputs.emailToAddresses.value !== currentSettings.emailToAddresses ||
- $formInputs.emailTlsMode.value !== currentSettings.emailTlsMode ||
- $formInputs.emailEventImageUpdate.value !== currentSettings.emailEventImageUpdate ||
- $formInputs.emailEventContainerUpdate.value !== currentSettings.emailEventContainerUpdate ||
- appriseSettings.enabled !== savedAppriseSettings.enabled ||
- appriseSettings.apiUrl !== savedAppriseSettings.apiUrl ||
- appriseSettings.imageUpdateTag !== savedAppriseSettings.imageUpdateTag ||
- appriseSettings.containerUpdateTag !== savedAppriseSettings.containerUpdateTag
+ emailHasChanges ||
+ discordHasChanges ||
+ telegramHasChanges ||
+ signalHasChanges ||
+ slackHasChanges ||
+ ntfyHasChanges ||
+ genericHasChanges ||
+ appriseHasChanges
);
+ // Sync with settings form context
$effect(() => {
if (formState) {
formState.hasChanges = hasChanges;
@@ -205,65 +140,57 @@
}
});
+ // Load initial data
onMount(async () => {
- // Initialize settings from loaded data
- if (data?.notificationSettings) {
- const discordSetting = data.notificationSettings.find((s) => s.provider === 'discord');
- if (discordSetting) {
- currentSettings.discordEnabled = discordSetting.enabled;
- currentSettings.discordWebhookUrl = discordSetting.config?.webhookUrl || '';
- currentSettings.discordUsername = discordSetting.config?.username || 'Arcane';
- currentSettings.discordAvatarUrl = discordSetting.config?.avatarUrl || '';
- currentSettings.discordEventImageUpdate = discordSetting.config?.events?.image_update ?? true;
- currentSettings.discordEventContainerUpdate = discordSetting.config?.events?.container_update ?? true;
- }
+ // Load built-in provider settings
+ for (const provider of NOTIFICATION_PROVIDER_KEYS) {
+ const found = data?.notificationSettings?.find((s: NotificationSettings) => s.provider === provider);
+ savedSettings[provider] = found ?? null;
+ }
- const emailSetting = data.notificationSettings.find((s) => s.provider === 'email');
- if (emailSetting) {
- currentSettings.emailEnabled = emailSetting.enabled;
- currentSettings.emailSmtpHost = emailSetting.config?.smtpHost || '';
- currentSettings.emailSmtpPort = emailSetting.config?.smtpPort || 587;
- currentSettings.emailSmtpUsername = emailSetting.config?.smtpUsername || '';
- currentSettings.emailSmtpPassword = emailSetting.config?.smtpPassword || '';
- currentSettings.emailFromAddress = emailSetting.config?.fromAddress || '';
- currentSettings.emailToAddresses = (emailSetting.config?.toAddresses || []).join(', ');
- currentSettings.emailTlsMode = emailSetting.config?.tlsMode || 'starttls';
- currentSettings.emailEventImageUpdate = emailSetting.config?.events?.image_update ?? true;
- currentSettings.emailEventContainerUpdate = emailSetting.config?.events?.container_update ?? true;
- }
+ // Apply saved values to form
+ emailValues = emailSettingsToFormValues(savedSettings.email ?? undefined);
+ emailBaseline = { ...emailValues };
- // Sync form inputs after currentSettings is updated
- $formInputs.discordEnabled.value = currentSettings.discordEnabled;
- $formInputs.discordWebhookUrl.value = currentSettings.discordWebhookUrl;
- $formInputs.discordUsername.value = currentSettings.discordUsername;
- $formInputs.discordAvatarUrl.value = currentSettings.discordAvatarUrl;
- $formInputs.discordEventImageUpdate.value = currentSettings.discordEventImageUpdate;
- $formInputs.discordEventContainerUpdate.value = currentSettings.discordEventContainerUpdate;
- $formInputs.emailEnabled.value = currentSettings.emailEnabled;
- $formInputs.emailSmtpHost.value = currentSettings.emailSmtpHost;
- $formInputs.emailSmtpPort.value = currentSettings.emailSmtpPort;
- $formInputs.emailSmtpUsername.value = currentSettings.emailSmtpUsername;
- $formInputs.emailSmtpPassword.value = currentSettings.emailSmtpPassword;
- $formInputs.emailFromAddress.value = currentSettings.emailFromAddress;
- $formInputs.emailToAddresses.value = currentSettings.emailToAddresses;
- $formInputs.emailTlsMode.value = currentSettings.emailTlsMode;
- $formInputs.emailEventImageUpdate.value = currentSettings.emailEventImageUpdate;
- $formInputs.emailEventContainerUpdate.value = currentSettings.emailEventContainerUpdate;
- }
+ discordValues = discordSettingsToFormValues(savedSettings.discord ?? undefined);
+ discordBaseline = { ...discordValues };
+
+ telegramValues = telegramSettingsToFormValues(savedSettings.telegram ?? undefined);
+ telegramBaseline = { ...telegramValues };
+
+ signalValues = signalSettingsToFormValues(savedSettings.signal ?? undefined);
+ signalBaseline = { ...signalValues };
+
+ slackValues = slackSettingsToFormValues(savedSettings.slack ?? undefined);
+ slackBaseline = { ...slackValues };
+
+ ntfyValues = ntfySettingsToFormValues(savedSettings.ntfy ?? undefined);
+ ntfyBaseline = { ...ntfyValues };
+
+ genericValues = genericSettingsToFormValues(savedSettings.generic ?? undefined);
+ genericBaseline = { ...genericValues };
// Load Apprise settings
try {
const settings = await notificationService.getAppriseSettings();
- appriseSettings = settings;
- savedAppriseSettings = { ...settings };
- } catch (error) {
+ appriseValues = appriseSettingsToFormValues(settings);
+ appriseBaseline = { ...appriseValues };
+ } catch {
// Apprise not configured yet, keep defaults
}
});
async function onSubmit() {
- const formData = form.validate();
- if (!formData) {
+ // Validate all forms
+ const emailValid = emailFormRef?.isValid() ?? true;
+ const discordValid = discordFormRef?.isValid() ?? true;
+ const telegramValid = telegramFormRef?.isValid() ?? true;
+ const signalValid = signalFormRef?.isValid() ?? true;
+ const slackValid = slackFormRef?.isValid() ?? true;
+ const ntfyValid = ntfyFormRef?.isValid() ?? true;
+ const genericValid = genericFormRef?.isValid() ?? true;
+
+ if (!(emailValid && discordValid && telegramValid && signalValid && slackValid && ntfyValid && genericValid)) {
toast.error('Please check the form for errors');
return;
}
@@ -273,66 +200,103 @@
try {
const errors: string[] = [];
- // Save Discord settings
- try {
- await notificationService.updateSettings('discord', {
- provider: 'discord',
- enabled: formData.discordEnabled,
- config: {
- webhookUrl: formData.discordWebhookUrl,
- username: formData.discordUsername,
- avatarUrl: formData.discordAvatarUrl,
- events: {
- image_update: formData.discordEventImageUpdate,
- container_update: formData.discordEventContainerUpdate
- }
- }
- });
- } catch (error: any) {
- const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';
- errors.push(m.notifications_saved_failed({ provider: 'Discord', error: errorMsg }));
+ // Save Email settings if changed
+ if (emailHasChanges) {
+ try {
+ const settings = emailFormValuesToSettings(emailValues);
+ await notificationService.updateSettings('email', settings);
+ savedSettings.email = settings;
+ emailBaseline = { ...emailValues };
+ } catch (error: any) {
+ const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';
+ errors.push(m.notifications_saved_failed({ provider: 'Email', error: errorMsg }));
+ }
}
- // Save Email settings
- try {
- const toAddressArray = formData.emailToAddresses
- .split(',')
- .map((addr) => addr.trim())
- .filter((addr) => addr.length > 0);
-
- await notificationService.updateSettings('email', {
- provider: 'email',
- enabled: formData.emailEnabled,
- config: {
- smtpHost: formData.emailSmtpHost,
- smtpPort: formData.emailSmtpPort,
- smtpUsername: formData.emailSmtpUsername,
- smtpPassword: formData.emailSmtpPassword,
- fromAddress: formData.emailFromAddress,
- toAddresses: toAddressArray,
- tlsMode: formData.emailTlsMode,
- events: {
- image_update: formData.emailEventImageUpdate,
- container_update: formData.emailEventContainerUpdate
- }
- }
- });
- } catch (error: any) {
- const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';
- errors.push(m.notifications_saved_failed({ provider: 'Email', error: errorMsg }));
+ // Save Discord settings if changed
+ if (discordHasChanges) {
+ try {
+ const settings = discordFormValuesToSettings(discordValues);
+ await notificationService.updateSettings('discord', settings);
+ savedSettings.discord = settings;
+ discordBaseline = { ...discordValues };
+ } catch (error: any) {
+ const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';
+ errors.push(m.notifications_saved_failed({ provider: 'Discord', error: errorMsg }));
+ }
+ }
+
+ // Save Telegram settings if changed
+ if (telegramHasChanges) {
+ try {
+ const settings = telegramFormValuesToSettings(telegramValues);
+ await notificationService.updateSettings('telegram', settings);
+ savedSettings.telegram = settings;
+ telegramBaseline = { ...telegramValues };
+ } catch (error: any) {
+ const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';
+ errors.push(m.notifications_saved_failed({ provider: 'Telegram', error: errorMsg }));
+ }
}
- // Save Apprise settings only if they changed
- const appriseChanged =
- appriseSettings.enabled !== savedAppriseSettings.enabled ||
- appriseSettings.apiUrl !== savedAppriseSettings.apiUrl ||
- appriseSettings.imageUpdateTag !== savedAppriseSettings.imageUpdateTag ||
- appriseSettings.containerUpdateTag !== savedAppriseSettings.containerUpdateTag;
+ // Save Signal settings if changed
+ if (signalHasChanges) {
+ try {
+ const settings = signalFormValuesToSettings(signalValues);
+ await notificationService.updateSettings('signal', settings);
+ savedSettings.signal = settings;
+ signalBaseline = { ...signalValues };
+ } catch (error: any) {
+ const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';
+ errors.push(m.notifications_saved_failed({ provider: 'Signal', error: errorMsg }));
+ }
+ }
+
+ // Save Slack settings if changed
+ if (slackHasChanges) {
+ try {
+ const settings = slackFormValuesToSettings(slackValues);
+ await notificationService.updateSettings('slack', settings);
+ savedSettings.slack = settings;
+ slackBaseline = { ...slackValues };
+ } catch (error: any) {
+ const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';
+ errors.push(m.notifications_saved_failed({ provider: 'Slack', error: errorMsg }));
+ }
+ }
- if (appriseChanged) {
+ // Save Ntfy settings if changed
+ if (ntfyHasChanges) {
try {
- await notificationService.updateAppriseSettings(appriseSettings);
- savedAppriseSettings = { ...appriseSettings };
+ const settings = ntfyFormValuesToSettings(ntfyValues);
+ await notificationService.updateSettings('ntfy', settings);
+ savedSettings.ntfy = settings;
+ ntfyBaseline = { ...ntfyValues };
+ } catch (error: any) {
+ const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';
+ errors.push(m.notifications_saved_failed({ provider: 'Ntfy', error: errorMsg }));
+ }
+ }
+
+ // Save Generic settings if changed
+ if (genericHasChanges) {
+ try {
+ const settings = genericFormValuesToSettings(genericValues);
+ await notificationService.updateSettings('generic', settings);
+ savedSettings.generic = settings;
+ genericBaseline = { ...genericValues };
+ } catch (error: any) {
+ const errorMsg = error?.response?.data?.error || error.message || 'Unknown error';
+ errors.push(m.notifications_saved_failed({ provider: 'Generic', error: errorMsg }));
+ }
+ }
+
+ // Save Apprise settings if changed
+ if (appriseHasChanges) {
+ try {
+ const settings = appriseFormValuesToSettings(appriseValues);
+ await notificationService.updateAppriseSettings(settings);
+ appriseBaseline = { ...appriseValues };
} catch (error: any) {
const errorMsg = error?.response?.data?.error || error.message || m.common_unknown();
errors.push(m.notifications_saved_failed({ provider: 'Apprise', error: errorMsg }));
@@ -340,7 +304,6 @@
}
if (errors.length === 0) {
- currentSettings = formData;
toast.success(m.general_settings_saved());
} else {
errors.forEach((err) => toast.error(err));
@@ -354,26 +317,17 @@
}
function resetForm() {
- $formInputs.discordEnabled.value = currentSettings.discordEnabled;
- $formInputs.discordWebhookUrl.value = currentSettings.discordWebhookUrl;
- $formInputs.discordUsername.value = currentSettings.discordUsername;
- $formInputs.discordAvatarUrl.value = currentSettings.discordAvatarUrl;
- $formInputs.discordEventImageUpdate.value = currentSettings.discordEventImageUpdate;
- $formInputs.discordEventContainerUpdate.value = currentSettings.discordEventContainerUpdate;
- $formInputs.emailEnabled.value = currentSettings.emailEnabled;
- $formInputs.emailSmtpHost.value = currentSettings.emailSmtpHost;
- $formInputs.emailSmtpPort.value = currentSettings.emailSmtpPort;
- $formInputs.emailSmtpUsername.value = currentSettings.emailSmtpUsername;
- $formInputs.emailSmtpPassword.value = currentSettings.emailSmtpPassword;
- $formInputs.emailFromAddress.value = currentSettings.emailFromAddress;
- $formInputs.emailToAddresses.value = currentSettings.emailToAddresses;
- $formInputs.emailTlsMode.value = currentSettings.emailTlsMode;
- $formInputs.emailEventImageUpdate.value = currentSettings.emailEventImageUpdate;
- $formInputs.emailEventContainerUpdate.value = currentSettings.emailEventContainerUpdate;
- appriseSettings = { ...savedAppriseSettings };
+ emailValues = { ...emailBaseline };
+ discordValues = { ...discordBaseline };
+ telegramValues = { ...telegramBaseline };
+ signalValues = { ...signalBaseline };
+ slackValues = { ...slackBaseline };
+ ntfyValues = { ...ntfyBaseline };
+ genericValues = { ...genericBaseline };
+ appriseValues = { ...appriseBaseline };
}
- async function testNotification(provider: 'discord' | 'email', testType: string = 'simple') {
+ async function testNotification(provider: NotificationProviderKey, testType: string = 'simple') {
if (hasChanges) {
pendingTestAction = () => executeTest(provider, testType);
showUnsavedDialog = true;
@@ -382,7 +336,7 @@
await executeTest(provider, testType);
}
- async function executeTest(provider: 'discord' | 'email', testType: string = 'simple') {
+ async function executeTest(provider: NotificationProviderKey, testType: string = 'simple') {
isTesting = true;
try {
await notificationService.testNotification(provider, testType);
@@ -394,6 +348,7 @@
isTesting = false;
}
}
+
async function testAppriseNotification() {
if (hasChanges) {
pendingTestAction = executeAppriseTest;
@@ -442,366 +397,104 @@
</Alert.Root>
{/if}
- <Tabs.Root value="built-in">
+ <Tabs.Root bind:value={notificationsTab}>
<Tabs.List class="inline-flex w-auto">
<Tabs.Trigger value="built-in">{m.notifications_tab_built_in()}</Tabs.Trigger>
<Tabs.Trigger value="apprise">{m.notifications_tab_apprise()}</Tabs.Trigger>
</Tabs.List>
- <Tabs.Content value="built-in" class="mt-4 space-y-8 sm:mt-6">
- <!-- Discord Section -->
- <div class="space-y-4">
- <h3 class="text-lg font-medium">Discord</h3>
- <div class="bg-card rounded-lg border shadow-sm">
- <div class="space-y-6 p-6">
- <div class="grid gap-4 md:grid-cols-[1fr_1.5fr] md:gap-8">
- <div>
- <Label class="text-base">{m.notifications_discord_title()}</Label>
- <p class="text-muted-foreground mt-1 text-sm">{m.notifications_discord_description()}</p>
- </div>
- <div class="space-y-4">
- <div class="flex items-center gap-2">
- <Switch
- id="discord-enabled"
- bind:checked={$formInputs.discordEnabled.value}
- disabled={isReadOnly}
- onCheckedChange={(checked) => {
- $formInputs.discordEnabled.value = checked;
- }}
- />
- <Label for="discord-enabled" class="font-normal">
- {m.notifications_discord_enabled_label()}
- </Label>
- </div>
-
- {#if $formInputs.discordEnabled.value}
- <div class="space-y-4 pt-2">
- <TextInputWithLabel
- bind:value={$formInputs.discordWebhookUrl.value}
- disabled={isReadOnly}
- label={m.notifications_discord_webhook_url_label()}
- placeholder={m.notifications_discord_webhook_url_placeholder()}
- type="text"
- autocomplete="off"
- helpText={m.notifications_discord_webhook_url_help()}
- />
- {#if $formInputs.discordWebhookUrl.error}
- <p class="text-destructive -mt-2 text-sm">{$formInputs.discordWebhookUrl.error}</p>
- {/if}
-
- <TextInputWithLabel
- bind:value={$formInputs.discordUsername.value}
- disabled={isReadOnly}
- label={m.notifications_discord_username_label()}
- placeholder={m.notifications_discord_username_placeholder()}
- type="text"
- autocomplete="off"
- helpText={m.notifications_discord_username_help()}
- />
-
- <TextInputWithLabel
- bind:value={$formInputs.discordAvatarUrl.value}
- disabled={isReadOnly}
- label={m.notifications_discord_avatar_url_label()}
- placeholder={m.notifications_discord_avatar_url_placeholder()}
- type="text"
- autocomplete="off"
- helpText={m.notifications_discord_avatar_url_help()}
- />
-
- <div class="space-y-3 pt-2">
- <Label class="text-sm font-medium">{m.notifications_events_title()}</Label>
- <p class="text-muted-foreground text-xs">{m.notifications_events_description()}</p>
- <div class="space-y-2">
- <SwitchWithLabel
- id="discord-event-image-update"
- bind:checked={$formInputs.discordEventImageUpdate.value}
- disabled={isReadOnly}
- label={m.notifications_event_image_update_label()}
- description={m.notifications_event_image_update_description()}
- />
- <SwitchWithLabel
- id="discord-event-container-update"
- bind:checked={$formInputs.discordEventContainerUpdate.value}
- disabled={isReadOnly}
- label={m.notifications_event_container_update_label()}
- description={m.notifications_event_container_update_description()}
- />
- </div>
- </div>
-
- <div class="pt-2">
- <ArcaneButton
- action="base"
- tone="outline"
- onclick={() => testNotification('discord')}
- disabled={isReadOnly || isTesting}
- loading={isTesting}
- icon={SendEmailIcon}
- customLabel={m.notifications_discord_test_button()}
- />
- </div>
- </div>
- {/if}
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Email Section -->
- <div class="space-y-4">
- <h3 class="text-lg font-medium">Email</h3>
- <div class="bg-card rounded-lg border shadow-sm">
- <div class="space-y-6 p-6">
- <div class="grid gap-4 md:grid-cols-[1fr_1.5fr] md:gap-8">
- <div>
- <Label class="text-base">{m.notifications_email_title()}</Label>
- <p class="text-muted-foreground mt-1 text-sm">{m.notifications_email_description()}</p>
- </div>
- <div class="space-y-4">
- <div class="flex items-center gap-2">
- <Switch
- id="email-enabled"
- bind:checked={$formInputs.emailEnabled.value}
- disabled={isReadOnly}
- onCheckedChange={(checked) => {
- $formInputs.emailEnabled.value = checked;
- }}
- />
- <Label for="email-enabled" class="font-normal">
- {m.notifications_email_enabled_label()}
- </Label>
- </div>
-
- {#if $formInputs.emailEnabled.value}
- <div class="space-y-4 pt-2">
- <div class="grid grid-cols-2 gap-4">
- <TextInputWithLabel
- bind:value={$formInputs.emailSmtpHost.value}
- disabled={isReadOnly}
- label={m.notifications_email_smtp_host_label()}
- placeholder={m.notifications_email_smtp_host_placeholder()}
- type="text"
- autocomplete="off"
- helpText={m.notifications_email_smtp_host_help()}
- />
- {#if $formInputs.emailSmtpHost.error}
- <p class="text-destructive col-span-2 -mt-2 text-sm">{$formInputs.emailSmtpHost.error}</p>
- {/if}
-
- <div class="space-y-2">
- <Label for="smtp-port">{m.notifications_email_smtp_port_label()}</Label>
- <Input
- id="smtp-port"
- type="number"
- bind:value={$formInputs.emailSmtpPort.value}
- disabled={isReadOnly}
- autocomplete="off"
- placeholder={m.notifications_email_smtp_port_placeholder()}
- />
- <p class="text-muted-foreground text-sm">{m.notifications_email_smtp_port_help()}</p>
- </div>
- </div>
-
- <div class="grid grid-cols-2 gap-4">
- <TextInputWithLabel
- bind:value={$formInputs.emailSmtpUsername.value}
- disabled={isReadOnly}
- label={m.notifications_email_username_label()}
- placeholder={m.notifications_email_username_placeholder()}
- type="text"
- autocomplete="off"
- helpText={m.notifications_email_username_help()}
- />
-
- <TextInputWithLabel
- bind:value={$formInputs.emailSmtpPassword.value}
- disabled={isReadOnly}
- label={m.notifications_email_password_label()}
- placeholder={m.notifications_email_password_placeholder()}
- type="password"
- autocomplete="new-password"
- helpText={m.notifications_email_password_help()}
- />
- </div>
-
- <TextInputWithLabel
- bind:value={$formInputs.emailFromAddress.value}
- disabled={isReadOnly}
- label={m.notifications_email_from_address_label()}
- placeholder={m.notifications_email_from_address_placeholder()}
- type="email"
- autocomplete="off"
- helpText={m.notifications_email_from_address_help()}
- />
- {#if $formInputs.emailFromAddress.error}
- <p class="text-destructive -mt-2 text-sm">{$formInputs.emailFromAddress.error}</p>
- {/if}
-
- <div class="space-y-2">
- <Label for="to-addresses">{m.notifications_email_to_addresses_label()}</Label>
- <Textarea
- id="to-addresses"
- bind:value={$formInputs.emailToAddresses.value}
- disabled={isReadOnly}
- autocomplete="off"
- placeholder={m.notifications_email_to_addresses_placeholder()}
- rows={2}
- />
- {#if $formInputs.emailToAddresses.error}
- <p class="text-destructive text-sm">{$formInputs.emailToAddresses.error}</p>
- {:else}
- <p class="text-muted-foreground text-sm">{m.notifications_email_to_addresses_help()}</p>
- {/if}
- </div>
-
- <SelectWithLabel
- id="email-tls-mode"
- label={m.notifications_email_tls_mode_label()}
- bind:value={$formInputs.emailTlsMode.value}
- disabled={isReadOnly}
- placeholder={m.notifications_email_tls_mode_placeholder()}
- options={[
- { value: 'none', label: 'None' },
- { value: 'starttls', label: 'StartTLS' },
- { value: 'ssl', label: 'SSL/TLS' }
- ]}
- description={m.notifications_email_tls_mode_description()}
- />
- <div class="space-y-3 pt-2">
- <Label class="text-sm font-medium">{m.notifications_events_title()}</Label>
- <p class="text-muted-foreground text-xs">{m.notifications_events_description()}</p>
- <div class="space-y-2">
- <SwitchWithLabel
- id="email-event-image-update"
- bind:checked={$formInputs.emailEventImageUpdate.value}
- disabled={isReadOnly}
- label={m.notifications_event_image_update_label()}
- description={m.notifications_event_image_update_description()}
- />
- <SwitchWithLabel
- id="email-event-container-update"
- bind:checked={$formInputs.emailEventContainerUpdate.value}
- disabled={isReadOnly}
- label={m.notifications_event_container_update_label()}
- description={m.notifications_event_container_update_description()}
- />
- </div>
- </div>
-
- <div class="pt-2">
- <DropdownMenu.Root>
- <DropdownMenu.Trigger>
- <ArcaneButton
- action="base"
- tone="outline"
- disabled={isReadOnly || isTesting}
- loading={isTesting}
- icon={SendEmailIcon}
- customLabel={m.notifications_email_test_button()}
- >
- <ArrowDownIcon class="ml-2 size-4" />
- </ArcaneButton>
- </DropdownMenu.Trigger>
- <DropdownMenu.Content align="start">
- <DropdownMenu.Item onclick={() => testNotification('email', 'simple')}>
- <SendEmailIcon class="size-4" />
- {m.notifications_email_test_simple()}
- </DropdownMenu.Item>
- <DropdownMenu.Item onclick={() => testNotification('email', 'image-update')}>
- <SendEmailIcon class="size-4" />
- {m.notifications_email_test_image_update()}
- </DropdownMenu.Item>
- <DropdownMenu.Item onclick={() => testNotification('email', 'batch-image-update')}>
- <SendEmailIcon class="size-4" />
- {m.notifications_email_test_batch_image_update()}
- </DropdownMenu.Item>
- </DropdownMenu.Content>
- </DropdownMenu.Root>
- </div>
- </div>
- {/if}
- </div>
- </div>
- </div>
- </div>
+ <Tabs.Content value="built-in" class="mt-4 sm:mt-6">
+ <div class="space-y-8">
+ <Tabs.Root bind:value={providerTab}>
+ <Tabs.List class="inline-flex w-auto">
+ {#each NOTIFICATION_PROVIDER_KEYS as provider}
+ <Tabs.Trigger value={provider}>{provider.charAt(0).toUpperCase() + provider.slice(1)}</Tabs.Trigger>
+ {/each}
+ </Tabs.List>
+
+ <Tabs.Content value="email" class="mt-4 space-y-4">
+ <EmailProviderForm
+ bind:this={emailFormRef}
+ bind:values={emailValues}
+ disabled={isReadOnly}
+ {isTesting}
+ onTest={(testType) => testNotification('email', testType)}
+ />
+ </Tabs.Content>
+
+ <Tabs.Content value="discord" class="mt-4 space-y-4">
+ <DiscordProviderForm
+ bind:this={discordFormRef}
+ bind:values={discordValues}
+ disabled={isReadOnly}
+ {isTesting}
+ onTest={() => testNotification('discord')}
+ />
+ </Tabs.Content>
+
+ <Tabs.Content value="telegram" class="mt-4 space-y-4">
+ <TelegramProviderForm
+ bind:this={telegramFormRef}
+ bind:values={telegramValues}
+ disabled={isReadOnly}
+ {isTesting}
+ onTest={() => testNotification('telegram')}
+ />
+ </Tabs.Content>
+
+ <Tabs.Content value="signal" class="mt-4 space-y-4">
+ <SignalProviderForm
+ bind:this={signalFormRef}
+ bind:values={signalValues}
+ disabled={isReadOnly}
+ {isTesting}
+ onTest={() => testNotification('signal')}
+ />
+ </Tabs.Content>
+
+ <Tabs.Content value="slack" class="mt-4 space-y-4">
+ <SlackProviderForm
+ bind:this={slackFormRef}
+ bind:values={slackValues}
+ disabled={isReadOnly}
+ {isTesting}
+ onTest={() => testNotification('slack')}
+ />
+ </Tabs.Content>
+
+ <Tabs.Content value="ntfy" class="mt-4 space-y-4">
+ <NtfyProviderForm
+ bind:this={ntfyFormRef}
+ bind:values={ntfyValues}
+ disabled={isReadOnly}
+ {isTesting}
+ onTest={() => testNotification('ntfy')}
+ />
+ </Tabs.Content>
+
+ <Tabs.Content value="generic" class="mt-4 space-y-4">
+ <GenericProviderForm
+ bind:this={genericFormRef}
+ bind:values={genericValues}
+ disabled={isReadOnly}
+ {isTesting}
+ onTest={() => testNotification('generic')}
+ />
+ </Tabs.Content>
+ </Tabs.Root>
</div>
</Tabs.Content>
<Tabs.Content value="apprise" class="mt-4 space-y-4 sm:mt-6 sm:space-y-6">
- <div class="space-y-4">
- <h3 class="text-lg font-medium">Apprise</h3>
- <div class="bg-card rounded-lg border shadow-sm">
- <div class="space-y-6 p-6">
- <div class="grid gap-4 md:grid-cols-[1fr_1.5fr] md:gap-8">
- <div>
- <Label class="text-base">{m.notifications_apprise_title()}</Label>
- <p class="text-muted-foreground mt-1 text-sm">{m.notifications_apprise_description()}</p>
- </div>
- <div class="space-y-4">
- <div class="flex items-center gap-2">
- <Switch
- id="apprise-enabled"
- bind:checked={appriseSettings.enabled}
- disabled={isReadOnly}
- onCheckedChange={(checked) => {
- appriseSettings.enabled = checked;
- }}
- />
- <Label for="apprise-enabled" class="font-normal">
- {m.notifications_apprise_enabled_label()}
- </Label>
- </div>
-
- {#if appriseSettings.enabled}
- <div class="space-y-4 pt-2">
- <TextInputWithLabel
- bind:value={appriseSettings.apiUrl}
- disabled={isReadOnly}
- label={m.notifications_apprise_api_url_label()}
- placeholder={m.notifications_apprise_api_url_placeholder()}
- type="url"
- autocomplete="off"
- helpText={m.notifications_apprise_api_url_help()}
- />
- <TextInputWithLabel
- bind:value={appriseSettings.imageUpdateTag}
- disabled={isReadOnly}
- label={m.notifications_apprise_image_tag_label()}
- placeholder={m.notifications_apprise_image_tag_placeholder()}
- type="text"
- autocomplete="off"
- helpText={m.notifications_apprise_image_tag_help()}
- />
- <TextInputWithLabel
- bind:value={appriseSettings.containerUpdateTag}
- disabled={isReadOnly}
- label={m.notifications_apprise_container_tag_label()}
- placeholder={m.notifications_apprise_container_tag_placeholder()}
- type="text"
- autocomplete="off"
- helpText={m.notifications_apprise_container_tag_help()}
- />
-
- <div class="pt-2">
- <ArcaneButton
- action="base"
- tone="outline"
- onclick={() => testAppriseNotification()}
- disabled={isReadOnly || isTesting}
- loading={isTesting}
- icon={SendEmailIcon}
- customLabel={m.notifications_apprise_test_button()}
- />
- </div>
- </div>
- {/if}
- </div>
- </div>
- </div>
- </div>
- </div>
+ <Alert.Root variant="default" class="border-yellow-500/50 bg-yellow-500/10 text-yellow-600 dark:text-yellow-400">
+ <Alert.Title>Deprecated</Alert.Title>
+ <Alert.Description>
+ Apprise support is deprecated and will be removed in a future release. Please migrate to the built-in notification
+ providers.
+ </Alert.Description>
+ </Alert.Root>
+
+ <AppriseProviderForm bind:values={appriseValues} disabled={isReadOnly} {isTesting} onTest={testAppriseNotification} />
</Tabs.Content>
</Tabs.Root>
</fieldset>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/AppriseProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/AppriseProviderForm.svelte
new file mode 100644
index 000000000..0eb53b14c
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/notifications/providers/AppriseProviderForm.svelte
@@ -0,0 +1,73 @@
+<script lang="ts">
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
+ import { m } from '$lib/paraglide/messages';
+ import { SendEmailIcon } from '$lib/icons';
+ import type { AppriseFormValues } from '$lib/types/notification-providers';
+ import ProviderFormWrapper from './ProviderFormWrapper.svelte';
+
+ interface Props {
+ values: AppriseFormValues;
+ disabled?: boolean;
+ isTesting?: boolean;
+ onTest?: () => void;
+ }
+
+ let { values = $bindable(), disabled = false, isTesting = false, onTest }: Props = $props();
+
+ export function isValid(): boolean {
+ if (!values.enabled) return true;
+ return values.apiUrl.trim().length > 0;
+ }
+</script>
+
+<ProviderFormWrapper
+ id="apprise"
+ title={m.notifications_apprise_title()}
+ description={m.notifications_apprise_description()}
+ enabledLabel={m.notifications_apprise_enabled_label()}
+ bind:enabled={values.enabled}
+ {disabled}
+>
+ <TextInputWithLabel
+ bind:value={values.apiUrl}
+ {disabled}
+ label={m.notifications_apprise_api_url_label()}
+ placeholder={m.notifications_apprise_api_url_placeholder()}
+ type="url"
+ autocomplete="off"
+ helpText={m.notifications_apprise_api_url_help()}
+ />
+ <TextInputWithLabel
+ bind:value={values.imageUpdateTag}
+ {disabled}
+ label={m.notifications_apprise_image_tag_label()}
+ placeholder={m.notifications_apprise_image_tag_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_apprise_image_tag_help()}
+ />
+ <TextInputWithLabel
+ bind:value={values.containerUpdateTag}
+ {disabled}
+ label={m.notifications_apprise_container_tag_label()}
+ placeholder={m.notifications_apprise_container_tag_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_apprise_container_tag_help()}
+ />
+
+ {#if onTest}
+ <div class="pt-2">
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ onclick={onTest}
+ disabled={disabled || isTesting}
+ loading={isTesting}
+ icon={SendEmailIcon}
+ customLabel={m.notifications_test_notification()}
+ />
+ </div>
+ {/if}
+</ProviderFormWrapper>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/DiscordProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/DiscordProviderForm.svelte
new file mode 100644
index 000000000..b84d96e7e
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/notifications/providers/DiscordProviderForm.svelte
@@ -0,0 +1,132 @@
+<script lang="ts">
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
+ import { m } from '$lib/paraglide/messages';
+ import { SendEmailIcon } from '$lib/icons';
+ import { z } from 'zod/v4';
+ import type { DiscordFormValues } from '$lib/types/notification-providers';
+ import ProviderFormWrapper from './ProviderFormWrapper.svelte';
+ import EventSubscriptions from './EventSubscriptions.svelte';
+
+ interface Props {
+ values: DiscordFormValues;
+ disabled?: boolean;
+ isTesting?: boolean;
+ onTest?: () => void;
+ }
+
+ let { values = $bindable(), disabled = false, isTesting = false, onTest }: Props = $props();
+
+ const schema = z
+ .object({
+ enabled: z.boolean(),
+ webhookId: z.string(),
+ token: z.string(),
+ username: z.string(),
+ avatarUrl: z.string(),
+ eventImageUpdate: z.boolean(),
+ eventContainerUpdate: z.boolean()
+ })
+ .superRefine((d, ctx) => {
+ if (!d.enabled) return;
+ if (!d.webhookId.trim()) {
+ ctx.addIssue({ code: 'custom', message: 'Webhook ID is required when Discord is enabled', path: ['webhookId'] });
+ }
+ if (!d.token.trim()) {
+ ctx.addIssue({ code: 'custom', message: 'Webhook Token is required when Discord is enabled', path: ['token'] });
+ }
+ });
+
+ const validation = $derived.by(() => schema.safeParse(values));
+
+ const fieldErrors = $derived.by(() => {
+ const errs: Partial<Record<keyof DiscordFormValues, string>> = {};
+ if (validation.success) return errs;
+ for (const issue of validation.error.issues) {
+ const key = issue.path?.[0] as keyof DiscordFormValues | undefined;
+ if (!key || errs[key]) continue;
+ errs[key] = issue.message;
+ }
+ return errs;
+ });
+
+ export function isValid(): boolean {
+ return validation.success;
+ }
+</script>
+
+<ProviderFormWrapper
+ id="discord"
+ title="Discord"
+ description={m.notifications_discord_description()}
+ enabledLabel={m.notifications_discord_enabled_label()}
+ bind:enabled={values.enabled}
+ {disabled}
+>
+ <TextInputWithLabel
+ bind:value={values.webhookId}
+ {disabled}
+ label={m.notifications_discord_webhook_id_label()}
+ placeholder={m.notifications_discord_webhook_id_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_discord_webhook_id_help()}
+ />
+ {#if fieldErrors.webhookId}
+ <p class="text-destructive -mt-2 text-sm">{fieldErrors.webhookId}</p>
+ {/if}
+
+ <TextInputWithLabel
+ bind:value={values.token}
+ {disabled}
+ label={m.notifications_discord_token_label()}
+ placeholder={m.notifications_discord_token_placeholder()}
+ type="password"
+ autocomplete="off"
+ helpText={m.notifications_discord_token_help()}
+ />
+ {#if fieldErrors.token}
+ <p class="text-destructive -mt-2 text-sm">{fieldErrors.token}</p>
+ {/if}
+
+ <TextInputWithLabel
+ bind:value={values.username}
+ {disabled}
+ label={m.notifications_discord_username_label()}
+ placeholder={m.notifications_discord_username_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_discord_username_help()}
+ />
+
+ <TextInputWithLabel
+ bind:value={values.avatarUrl}
+ {disabled}
+ label={m.notifications_discord_avatar_url_label()}
+ placeholder={m.notifications_discord_avatar_url_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_discord_avatar_url_help()}
+ />
+
+ <EventSubscriptions
+ providerId="discord"
+ bind:eventImageUpdate={values.eventImageUpdate}
+ bind:eventContainerUpdate={values.eventContainerUpdate}
+ {disabled}
+ />
+
+ {#if onTest}
+ <div class="pt-2">
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ onclick={onTest}
+ disabled={disabled || isTesting}
+ loading={isTesting}
+ icon={SendEmailIcon}
+ customLabel={m.notifications_test_notification()}
+ />
+ </div>
+ {/if}
+</ProviderFormWrapper>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/EmailProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/EmailProviderForm.svelte
new file mode 100644
index 000000000..6a6365cb2
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/notifications/providers/EmailProviderForm.svelte
@@ -0,0 +1,236 @@
+<script lang="ts">
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
+ import SelectWithLabel from '$lib/components/form/select-with-label.svelte';
+ import { Label } from '$lib/components/ui/label';
+ import Textarea from '$lib/components/ui/textarea/textarea.svelte';
+ import { m } from '$lib/paraglide/messages';
+ import { ArrowDownIcon, SendEmailIcon } from '$lib/icons';
+ import { z } from 'zod/v4';
+ import type { EmailFormValues } from '$lib/types/notification-providers';
+ import ProviderFormWrapper from './ProviderFormWrapper.svelte';
+ import EventSubscriptions from './EventSubscriptions.svelte';
+
+ interface Props {
+ values: EmailFormValues;
+ disabled?: boolean;
+ isTesting?: boolean;
+ onTest?: (testType: string) => void;
+ }
+
+ let { values = $bindable(), disabled = false, isTesting = false, onTest }: Props = $props();
+
+ const schema = z
+ .object({
+ enabled: z.boolean(),
+ smtpHost: z.string(),
+ smtpPort: z.coerce.number().int().min(1).max(65535),
+ smtpUsername: z.string(),
+ smtpPassword: z.string(),
+ fromAddress: z.string(),
+ toAddresses: z.string(),
+ tlsMode: z.enum(['none', 'starttls', 'ssl']),
+ eventImageUpdate: z.boolean(),
+ eventContainerUpdate: z.boolean()
+ })
+ .superRefine((d, ctx) => {
+ if (!d.enabled) return;
+ if (!d.smtpHost.trim()) {
+ ctx.addIssue({ code: 'custom', message: 'SMTP host is required when email is enabled', path: ['smtpHost'] });
+ }
+ if (!d.fromAddress.trim()) {
+ ctx.addIssue({ code: 'custom', message: 'From address is required when email is enabled', path: ['fromAddress'] });
+ } else {
+ const v = z.string().email().safeParse(d.fromAddress.trim());
+ if (!v.success) {
+ ctx.addIssue({ code: 'custom', message: 'Invalid email address format', path: ['fromAddress'] });
+ }
+ }
+ if (!d.toAddresses.trim()) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'At least one recipient address is required when email is enabled',
+ path: ['toAddresses']
+ });
+ } else {
+ const addresses = d.toAddresses
+ .split(',')
+ .map((addr) => addr.trim())
+ .filter((addr) => addr.length > 0);
+ const invalid: string[] = [];
+ addresses.forEach((addr) => {
+ const v = z.string().email().safeParse(addr);
+ if (!v.success) invalid.push(addr);
+ });
+ if (invalid.length > 0) {
+ ctx.addIssue({
+ code: 'custom',
+ message: `Invalid email addresses: ${invalid.join(', ')}`,
+ path: ['toAddresses']
+ });
+ }
+ }
+ });
+
+ const validation = $derived.by(() => schema.safeParse(values));
+
+ const fieldErrors = $derived.by(() => {
+ const errs: Partial<Record<keyof EmailFormValues, string>> = {};
+ if (validation.success) return errs;
+ for (const issue of validation.error.issues) {
+ const key = issue.path?.[0] as keyof EmailFormValues | undefined;
+ if (!key || errs[key]) continue;
+ errs[key] = issue.message;
+ }
+ return errs;
+ });
+
+ export function isValid(): boolean {
+ return validation.success;
+ }
+</script>
+
+<ProviderFormWrapper
+ id="email"
+ title="Email"
+ description={m.notifications_email_description()}
+ enabledLabel={m.notifications_email_enabled_label()}
+ bind:enabled={values.enabled}
+ {disabled}
+>
+ <div class="grid grid-cols-2 gap-4">
+ <TextInputWithLabel
+ bind:value={values.smtpHost}
+ {disabled}
+ label={m.notifications_email_smtp_host_label()}
+ placeholder={m.notifications_email_smtp_host_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_email_smtp_host_help()}
+ />
+ {#if fieldErrors.smtpHost}
+ <p class="text-destructive col-span-2 -mt-2 text-sm">{fieldErrors.smtpHost}</p>
+ {/if}
+
+ <div class="space-y-2">
+ <Label for="smtp-port">{m.notifications_email_smtp_port_label()}</Label>
+ <input
+ id="smtp-port"
+ type="number"
+ class="border-input file:text-foreground placeholder:text-muted-foreground focus-visible:ring-ring flex h-9 w-full rounded-md border bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium focus-visible:ring-1 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm"
+ bind:value={values.smtpPort}
+ {disabled}
+ autocomplete="off"
+ placeholder={m.notifications_email_smtp_port_placeholder()}
+ />
+ <p class="text-muted-foreground text-sm">{m.notifications_email_smtp_port_help()}</p>
+ </div>
+ </div>
+
+ <div class="grid grid-cols-2 gap-4">
+ <TextInputWithLabel
+ bind:value={values.smtpUsername}
+ {disabled}
+ label={m.notifications_email_username_label()}
+ placeholder={m.notifications_email_username_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_email_username_help()}
+ />
+
+ <TextInputWithLabel
+ bind:value={values.smtpPassword}
+ {disabled}
+ label={m.notifications_email_password_label()}
+ placeholder={m.notifications_email_password_placeholder()}
+ type="password"
+ autocomplete="new-password"
+ helpText={m.notifications_email_password_help()}
+ />
+ </div>
+
+ <TextInputWithLabel
+ bind:value={values.fromAddress}
+ {disabled}
+ label={m.notifications_email_from_address_label()}
+ placeholder={m.notifications_email_from_address_placeholder()}
+ type="email"
+ autocomplete="off"
+ helpText={m.notifications_email_from_address_help()}
+ />
+ {#if fieldErrors.fromAddress}
+ <p class="text-destructive -mt-2 text-sm">{fieldErrors.fromAddress}</p>
+ {/if}
+
+ <div class="space-y-2">
+ <Label for="to-addresses">{m.notifications_email_to_addresses_label()}</Label>
+ <Textarea
+ id="to-addresses"
+ bind:value={values.toAddresses}
+ {disabled}
+ autocomplete="off"
+ placeholder={m.notifications_email_to_addresses_placeholder()}
+ rows={2}
+ />
+ {#if fieldErrors.toAddresses}
+ <p class="text-destructive text-sm">{fieldErrors.toAddresses}</p>
+ {:else}
+ <p class="text-muted-foreground text-sm">{m.notifications_email_to_addresses_help()}</p>
+ {/if}
+ </div>
+
+ <SelectWithLabel
+ id="email-tls-mode"
+ label={m.notifications_email_tls_mode_label()}
+ bind:value={values.tlsMode}
+ {disabled}
+ placeholder={m.notifications_email_tls_mode_placeholder()}
+ options={[
+ { value: 'none', label: 'None' },
+ { value: 'starttls', label: 'StartTLS' },
+ { value: 'ssl', label: 'SSL/TLS' }
+ ]}
+ description={m.notifications_email_tls_mode_description()}
+ />
+
+ <EventSubscriptions
+ providerId="email"
+ bind:eventImageUpdate={values.eventImageUpdate}
+ bind:eventContainerUpdate={values.eventContainerUpdate}
+ {disabled}
+ />
+
+ {#if onTest}
+ <div class="pt-2">
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger>
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ disabled={disabled || isTesting}
+ loading={isTesting}
+ icon={SendEmailIcon}
+ customLabel={m.notifications_test_notification()}
+ >
+ <ArrowDownIcon class="ml-2 size-4" />
+ </ArcaneButton>
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="start">
+ <DropdownMenu.Item onclick={() => onTest('simple')}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_email_test_simple()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => onTest('image-update')}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_email_test_image_update()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => onTest('batch-image-update')}>
+ <SendEmailIcon class="size-4" />
+ {m.notifications_email_test_batch_image_update()}
+ </DropdownMenu.Item>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ </div>
+ {/if}
+</ProviderFormWrapper>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/EventSubscriptions.svelte b/frontend/src/routes/(app)/settings/notifications/providers/EventSubscriptions.svelte
new file mode 100644
index 000000000..6cf7c2b14
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/notifications/providers/EventSubscriptions.svelte
@@ -0,0 +1,40 @@
+<script lang="ts">
+ import { Label } from '$lib/components/ui/label';
+ import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
+ import { m } from '$lib/paraglide/messages';
+
+ interface Props {
+ providerId: string;
+ eventImageUpdate: boolean;
+ eventContainerUpdate: boolean;
+ disabled?: boolean;
+ }
+
+ let {
+ providerId,
+ eventImageUpdate = $bindable(),
+ eventContainerUpdate = $bindable(),
+ disabled = false
+ }: Props = $props();
+</script>
+
+<div class="space-y-3 pt-2">
+ <Label class="text-sm font-medium">{m.notifications_events_title()}</Label>
+ <p class="text-muted-foreground text-xs">{m.notifications_events_description()}</p>
+ <div class="space-y-2">
+ <SwitchWithLabel
+ id="{providerId}-event-image-update"
+ bind:checked={eventImageUpdate}
+ {disabled}
+ label={m.notifications_event_image_update_label()}
+ description={m.notifications_event_image_update_description()}
+ />
+ <SwitchWithLabel
+ id="{providerId}-event-container-update"
+ bind:checked={eventContainerUpdate}
+ {disabled}
+ label={m.notifications_event_container_update_label()}
+ description={m.notifications_event_container_update_description()}
+ />
+ </div>
+</div>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/GenericProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/GenericProviderForm.svelte
new file mode 100644
index 000000000..8000ffd59
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/notifications/providers/GenericProviderForm.svelte
@@ -0,0 +1,166 @@
+<script lang="ts">
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
+ import { m } from '$lib/paraglide/messages';
+ import { SendEmailIcon } from '$lib/icons';
+ import { z } from 'zod/v4';
+ import type { GenericFormValues } from '$lib/types/notification-providers';
+ import ProviderFormWrapper from './ProviderFormWrapper.svelte';
+ import EventSubscriptions from './EventSubscriptions.svelte';
+ import { Checkbox } from '$lib/components/ui/checkbox';
+ import { Label } from '$lib/components/ui/label';
+
+ interface Props {
+ values: GenericFormValues;
+ disabled?: boolean;
+ isTesting?: boolean;
+ onTest?: () => void;
+ }
+
+ let { values = $bindable(), disabled = false, isTesting = false, onTest }: Props = $props();
+
+ const schema = z
+ .object({
+ enabled: z.boolean(),
+ webhookUrl: z.string(),
+ method: z.string(),
+ contentType: z.string(),
+ titleKey: z.string(),
+ messageKey: z.string(),
+ customHeaders: z.string(),
+ disableTls: z.boolean(),
+ eventImageUpdate: z.boolean(),
+ eventContainerUpdate: z.boolean()
+ })
+ .superRefine((d, ctx) => {
+ if (!d.enabled) return;
+ if (!d.webhookUrl.trim()) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'Webhook URL is required when Generic Webhook is enabled',
+ path: ['webhookUrl']
+ });
+ }
+ });
+
+ const validation = $derived.by(() => schema.safeParse(values));
+
+ const fieldErrors = $derived.by(() => {
+ const errs: Partial<Record<keyof GenericFormValues, string>> = {};
+ if (validation.success) return errs;
+ for (const issue of validation.error.issues) {
+ const key = issue.path?.[0] as keyof GenericFormValues | undefined;
+ if (!key || errs[key]) continue;
+ errs[key] = issue.message;
+ }
+ return errs;
+ });
+
+ export function isValid(): boolean {
+ return validation.success;
+ }
+</script>
+
+<ProviderFormWrapper
+ id="generic"
+ title={m.notifications_generic_title()}
+ description={m.notifications_generic_description()}
+ enabledLabel={m.notifications_generic_enabled_label()}
+ bind:enabled={values.enabled}
+ {disabled}
+>
+ <TextInputWithLabel
+ bind:value={values.webhookUrl}
+ {disabled}
+ label={m.notifications_generic_webhook_url_label()}
+ placeholder={m.notifications_generic_webhook_url_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_generic_webhook_url_help()}
+ />
+ {#if fieldErrors.webhookUrl}
+ <p class="text-destructive -mt-2 text-sm">{fieldErrors.webhookUrl}</p>
+ {/if}
+
+ <TextInputWithLabel
+ bind:value={values.method}
+ {disabled}
+ label={m.notifications_generic_method_label()}
+ placeholder={m.notifications_generic_method_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_generic_method_help()}
+ />
+
+ <TextInputWithLabel
+ bind:value={values.contentType}
+ {disabled}
+ label={m.notifications_generic_content_type_label()}
+ placeholder={m.notifications_generic_content_type_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_generic_content_type_help()}
+ />
+
+ <TextInputWithLabel
+ bind:value={values.titleKey}
+ {disabled}
+ label={m.notifications_generic_title_key_label()}
+ placeholder={m.notifications_generic_title_key_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_generic_title_key_help()}
+ />
+
+ <TextInputWithLabel
+ bind:value={values.messageKey}
+ {disabled}
+ label={m.notifications_generic_message_key_label()}
+ placeholder={m.notifications_generic_message_key_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_generic_message_key_help()}
+ />
+
+ <TextInputWithLabel
+ bind:value={values.customHeaders}
+ {disabled}
+ label={m.notifications_generic_custom_headers_label()}
+ placeholder={m.notifications_generic_custom_headers_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_generic_custom_headers_help()}
+ />
+
+ <div class="flex items-center space-x-2">
+ <Checkbox id="generic-disable-tls" bind:checked={values.disableTls} {disabled} />
+ <Label
+ for="generic-disable-tls"
+ class="text-sm leading-none font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ >
+ {m.notifications_generic_disable_tls_label()}
+ </Label>
+ </div>
+ <p class="text-muted-foreground -mt-1 text-xs">{m.notifications_generic_disable_tls_help()}</p>
+
+ <EventSubscriptions
+ providerId="generic"
+ bind:eventImageUpdate={values.eventImageUpdate}
+ bind:eventContainerUpdate={values.eventContainerUpdate}
+ {disabled}
+ />
+
+ {#if onTest}
+ <div class="pt-2">
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ onclick={onTest}
+ disabled={disabled || isTesting}
+ loading={isTesting}
+ icon={SendEmailIcon}
+ customLabel={m.notifications_test_notification()}
+ />
+ </div>
+ {/if}
+</ProviderFormWrapper>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/NtfyProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/NtfyProviderForm.svelte
new file mode 100644
index 000000000..a665fe259
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/notifications/providers/NtfyProviderForm.svelte
@@ -0,0 +1,213 @@
+<script lang="ts">
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
+ import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
+ import { Label } from '$lib/components/ui/label';
+ import Textarea from '$lib/components/ui/textarea/textarea.svelte';
+ import { m } from '$lib/paraglide/messages';
+ import { SendEmailIcon } from '$lib/icons';
+ import { z } from 'zod/v4';
+ import type { NtfyFormValues } from '$lib/types/notification-providers';
+ import ProviderFormWrapper from './ProviderFormWrapper.svelte';
+ import EventSubscriptions from './EventSubscriptions.svelte';
+
+ interface Props {
+ values: NtfyFormValues;
+ disabled?: boolean;
+ isTesting?: boolean;
+ onTest?: () => void;
+ }
+
+ let { values = $bindable(), disabled = false, isTesting = false, onTest }: Props = $props();
+
+ const schema = z
+ .object({
+ enabled: z.boolean(),
+ host: z.string(),
+ port: z.number().min(0).max(65535),
+ topic: z.string(),
+ username: z.string(),
+ password: z.string(),
+ priority: z.string(),
+ tags: z.string(),
+ icon: z.string(),
+ cache: z.boolean(),
+ firebase: z.boolean(),
+ disableTlsVerification: z.boolean(),
+ eventImageUpdate: z.boolean(),
+ eventContainerUpdate: z.boolean()
+ })
+ .superRefine((d, ctx) => {
+ if (!d.enabled) return;
+ if (!d.topic.trim()) {
+ ctx.addIssue({ code: 'custom', message: 'Topic is required when Ntfy is enabled', path: ['topic'] });
+ }
+ if (d.port > 0 && (d.port < 1 || d.port > 65535)) {
+ ctx.addIssue({ code: 'custom', message: 'Port must be between 1 and 65535', path: ['port'] });
+ }
+ });
+
+ const validation = $derived.by(() => schema.safeParse(values));
+
+ const fieldErrors = $derived.by(() => {
+ const errs: Partial<Record<keyof NtfyFormValues, string>> = {};
+ if (validation.success) return errs;
+ for (const issue of validation.error.issues) {
+ const key = issue.path?.[0] as keyof NtfyFormValues | undefined;
+ if (!key || errs[key]) continue;
+ errs[key] = issue.message;
+ }
+ return errs;
+ });
+
+ export function isValid(): boolean {
+ return validation.success;
+ }
+</script>
+
+<ProviderFormWrapper
+ id="ntfy"
+ title="Ntfy"
+ description={m.notifications_ntfy_description()}
+ enabledLabel={m.notifications_ntfy_enabled_label()}
+ bind:enabled={values.enabled}
+ {disabled}
+>
+ <TextInputWithLabel
+ bind:value={values.host}
+ {disabled}
+ label={m.notifications_ntfy_host_label()}
+ placeholder={m.notifications_ntfy_host_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_ntfy_host_help()}
+ />
+
+ <TextInputWithLabel
+ bind:value={values.port}
+ {disabled}
+ label={m.notifications_ntfy_port_label()}
+ placeholder={m.notifications_ntfy_port_placeholder()}
+ type="number"
+ autocomplete="off"
+ helpText={m.notifications_ntfy_port_help()}
+ />
+
+ <TextInputWithLabel
+ bind:value={values.topic}
+ {disabled}
+ label={m.notifications_ntfy_topic_label()}
+ placeholder={m.notifications_ntfy_topic_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_ntfy_topic_help()}
+ />
+ {#if fieldErrors.topic}
+ <p class="text-destructive -mt-2 text-sm">{fieldErrors.topic}</p>
+ {/if}
+
+ <TextInputWithLabel
+ bind:value={values.username}
+ {disabled}
+ label={m.notifications_ntfy_username_label()}
+ placeholder={m.notifications_ntfy_username_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_ntfy_username_help()}
+ />
+
+ <TextInputWithLabel
+ bind:value={values.password}
+ {disabled}
+ label={m.notifications_ntfy_password_label()}
+ placeholder={m.notifications_ntfy_password_placeholder()}
+ type="password"
+ autocomplete="off"
+ helpText={m.notifications_ntfy_password_help()}
+ />
+
+ <div class="space-y-2">
+ <Label for="ntfy-priority">{m.notifications_ntfy_priority_label()}</Label>
+ <select
+ id="ntfy-priority"
+ bind:value={values.priority}
+ {disabled}
+ class="border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring flex h-10 rounded-md border px-3 py-2 text-base focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm"
+ >
+ <option value="min">Min (1)</option>
+ <option value="low">Low (2)</option>
+ <option value="default">Default (3)</option>
+ <option value="high">High (4)</option>
+ <option value="max">Max/Urgent (5)</option>
+ </select>
+ <p class="text-muted-foreground text-sm">{m.notifications_ntfy_priority_help()}</p>
+ </div>
+
+ <div class="space-y-2">
+ <Label for="ntfy-tags">{m.notifications_ntfy_tags_label()}</Label>
+ <Textarea
+ id="ntfy-tags"
+ bind:value={values.tags}
+ {disabled}
+ autocomplete="off"
+ placeholder={m.notifications_ntfy_tags_placeholder()}
+ rows={2}
+ />
+ <p class="text-muted-foreground text-sm">{m.notifications_ntfy_tags_help()}</p>
+ </div>
+
+ <TextInputWithLabel
+ bind:value={values.icon}
+ {disabled}
+ label={m.notifications_ntfy_icon_label()}
+ placeholder={m.notifications_ntfy_icon_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_ntfy_icon_help()}
+ />
+
+ <div class="space-y-3">
+ <SwitchWithLabel
+ id="ntfy-cache"
+ bind:checked={values.cache}
+ {disabled}
+ label={m.notifications_ntfy_cache_label()}
+ description={m.notifications_ntfy_cache_help()}
+ />
+ <SwitchWithLabel
+ id="ntfy-firebase"
+ bind:checked={values.firebase}
+ {disabled}
+ label={m.notifications_ntfy_firebase_label()}
+ description={m.notifications_ntfy_firebase_help()}
+ />
+ <SwitchWithLabel
+ id="ntfy-disable-tls"
+ bind:checked={values.disableTlsVerification}
+ {disabled}
+ label={m.notifications_ntfy_disable_tls_label()}
+ description={m.notifications_ntfy_disable_tls_help()}
+ />
+ </div>
+
+ <EventSubscriptions
+ providerId="ntfy"
+ bind:eventImageUpdate={values.eventImageUpdate}
+ bind:eventContainerUpdate={values.eventContainerUpdate}
+ {disabled}
+ />
+
+ {#if onTest}
+ <div class="pt-2">
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ onclick={onTest}
+ disabled={disabled || isTesting}
+ loading={isTesting}
+ icon={SendEmailIcon}
+ customLabel={m.notifications_test_notification()}
+ />
+ </div>
+ {/if}
+</ProviderFormWrapper>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/ProviderFormWrapper.svelte b/frontend/src/routes/(app)/settings/notifications/providers/ProviderFormWrapper.svelte
new file mode 100644
index 000000000..39d89a1cd
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/notifications/providers/ProviderFormWrapper.svelte
@@ -0,0 +1,44 @@
+<script lang="ts">
+ import { Label } from '$lib/components/ui/label';
+ import { Switch } from '$lib/components/ui/switch/index.js';
+
+ interface Props {
+ id: string;
+ title: string;
+ description: string;
+ enabledLabel: string;
+ enabled: boolean;
+ disabled?: boolean;
+ children?: import('svelte').Snippet;
+ }
+
+ let { id, title, description, enabledLabel, enabled = $bindable(), disabled = false, children }: Props = $props();
+</script>
+
+<div class="space-y-4">
+ <h3 class="text-lg font-medium">{title}</h3>
+ <div class="bg-card rounded-lg border shadow-sm">
+ <div class="space-y-6 p-6">
+ <div class="grid gap-4 md:grid-cols-[1fr_1.5fr] md:gap-8">
+ <div>
+ <Label class="text-base">{title}</Label>
+ <p class="text-muted-foreground mt-1 text-sm">{description}</p>
+ </div>
+ <div class="space-y-4">
+ <div class="flex items-center gap-2">
+ <Switch id="{id}-enabled" bind:checked={enabled} {disabled} />
+ <Label for="{id}-enabled" class="font-normal">
+ {enabledLabel}
+ </Label>
+ </div>
+
+ {#if enabled && children}
+ <div class="space-y-4 pt-2">
+ {@render children()}
+ </div>
+ {/if}
+ </div>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/SignalProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/SignalProviderForm.svelte
new file mode 100644
index 000000000..7a8d2476c
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/notifications/providers/SignalProviderForm.svelte
@@ -0,0 +1,245 @@
+<script lang="ts">
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
+ import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
+ import { Label } from '$lib/components/ui/label';
+ import Textarea from '$lib/components/ui/textarea/textarea.svelte';
+ import { m } from '$lib/paraglide/messages';
+ import { SendEmailIcon } from '$lib/icons';
+ import { z } from 'zod/v4';
+ import type { SignalFormValues } from '$lib/types/notification-providers';
+ import ProviderFormWrapper from './ProviderFormWrapper.svelte';
+ import EventSubscriptions from './EventSubscriptions.svelte';
+
+ interface Props {
+ values: SignalFormValues;
+ disabled?: boolean;
+ isTesting?: boolean;
+ onTest?: () => void;
+ }
+
+ let { values = $bindable(), disabled = false, isTesting = false, onTest }: Props = $props();
+
+ const schema = z
+ .object({
+ enabled: z.boolean(),
+ host: z.string(),
+ port: z.number().min(1).max(65535),
+ user: z.string(),
+ password: z.string(),
+ token: z.string(),
+ source: z.string(),
+ recipients: z.string(),
+ disableTls: z.boolean(),
+ eventImageUpdate: z.boolean(),
+ eventContainerUpdate: z.boolean()
+ })
+ .superRefine((d, ctx) => {
+ if (!d.enabled) return;
+
+ // Host is required when enabled
+ if (!d.host.trim()) {
+ ctx.addIssue({ code: 'custom', message: m.notifications_signal_host_required(), path: ['host'] });
+ }
+
+ // Port validation
+ if (d.port < 1 || d.port > 65535) {
+ ctx.addIssue({ code: 'custom', message: m.notifications_signal_port_invalid(), path: ['port'] });
+ }
+
+ // Source phone number is required
+ if (!d.source.trim()) {
+ ctx.addIssue({ code: 'custom', message: m.notifications_signal_source_required(), path: ['source'] });
+ } else if (!d.source.startsWith('+')) {
+ ctx.addIssue({ code: 'custom', message: m.notifications_signal_source_format(), path: ['source'] });
+ }
+
+ // Recipients are required
+ if (!d.recipients.trim()) {
+ ctx.addIssue({ code: 'custom', message: m.notifications_signal_recipients_required(), path: ['recipients'] });
+ }
+
+ // Either user+password or token is required
+ const hasBasicAuth = d.user.trim() && d.password.trim();
+ const hasTokenAuth = d.token.trim();
+ if (!hasBasicAuth && !hasTokenAuth) {
+ ctx.addIssue({
+ code: 'custom',
+ message: m.notifications_signal_auth_required(),
+ path: ['user']
+ });
+ }
+ if (hasBasicAuth && hasTokenAuth) {
+ ctx.addIssue({
+ code: 'custom',
+ message: m.notifications_signal_auth_conflict(),
+ path: ['token']
+ });
+ }
+ });
+
+ const validation = $derived.by(() => schema.safeParse(values));
+
+ const fieldErrors = $derived.by(() => {
+ const errs: Partial<Record<keyof SignalFormValues, string>> = {};
+ if (validation.success) return errs;
+ for (const issue of validation.error.issues) {
+ const key = issue.path?.[0] as keyof SignalFormValues | undefined;
+ if (!key || errs[key]) continue;
+ errs[key] = issue.message;
+ }
+ return errs;
+ });
+
+ export function isValid(): boolean {
+ return validation.success;
+ }
+</script>
+
+<ProviderFormWrapper
+ id="signal"
+ title={m.notifications_signal_title()}
+ description={m.notifications_signal_description()}
+ enabledLabel={m.notifications_signal_enabled_label()}
+ bind:enabled={values.enabled}
+ {disabled}
+>
+ <div class="grid grid-cols-2 gap-4">
+ <TextInputWithLabel
+ bind:value={values.host}
+ {disabled}
+ label={m.notifications_signal_host_label()}
+ placeholder={m.notifications_signal_host_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_signal_host_help()}
+ />
+ {#if fieldErrors.host}
+ <p class="text-destructive col-span-2 -mt-2 text-sm">{fieldErrors.host}</p>
+ {/if}
+
+ <TextInputWithLabel
+ bind:value={values.port}
+ {disabled}
+ label={m.notifications_signal_port_label()}
+ placeholder={m.notifications_signal_port_placeholder()}
+ type="number"
+ autocomplete="off"
+ helpText={m.notifications_signal_port_help()}
+ />
+ {#if fieldErrors.port}
+ <p class="text-destructive col-span-2 -mt-2 text-sm">{fieldErrors.port}</p>
+ {/if}
+ </div>
+
+ <div class="space-y-4">
+ <div class="rounded-lg border p-4">
+ <h4 class="mb-3 text-sm font-medium">{m.notifications_signal_auth_section()}</h4>
+ <p class="text-muted-foreground mb-4 text-sm">{m.notifications_signal_auth_help()}</p>
+
+ <div class="space-y-4">
+ <TextInputWithLabel
+ bind:value={values.user}
+ {disabled}
+ label={m.notifications_signal_user_label()}
+ placeholder={m.notifications_signal_user_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_signal_user_help()}
+ />
+
+ <TextInputWithLabel
+ bind:value={values.password}
+ {disabled}
+ label={m.notifications_signal_password_label()}
+ placeholder={m.notifications_signal_password_placeholder()}
+ type="password"
+ autocomplete="off"
+ helpText={m.notifications_signal_password_help()}
+ />
+
+ <div class="relative">
+ <div class="absolute inset-0 flex items-center">
+ <span class="w-full border-t" />
+ </div>
+ <div class="relative flex justify-center text-xs uppercase">
+ <span class="bg-background text-muted-foreground px-2">{m.notifications_signal_auth_or()}</span>
+ </div>
+ </div>
+
+ <TextInputWithLabel
+ bind:value={values.token}
+ {disabled}
+ label={m.notifications_signal_token_label()}
+ placeholder={m.notifications_signal_token_placeholder()}
+ type="password"
+ autocomplete="off"
+ helpText={m.notifications_signal_token_help()}
+ />
+ </div>
+
+ {#if fieldErrors.user || fieldErrors.token}
+ <p class="text-destructive mt-2 text-sm">{fieldErrors.user || fieldErrors.token}</p>
+ {/if}
+ </div>
+ </div>
+
+ <TextInputWithLabel
+ bind:value={values.source}
+ {disabled}
+ label={m.notifications_signal_source_label()}
+ placeholder={m.notifications_signal_source_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_signal_source_help()}
+ />
+ {#if fieldErrors.source}
+ <p class="text-destructive -mt-2 text-sm">{fieldErrors.source}</p>
+ {/if}
+
+ <div class="space-y-2">
+ <Label for="signal-recipients">{m.notifications_signal_recipients_label()}</Label>
+ <Textarea
+ id="signal-recipients"
+ bind:value={values.recipients}
+ {disabled}
+ autocomplete="off"
+ placeholder={m.notifications_signal_recipients_placeholder()}
+ rows={3}
+ />
+ {#if fieldErrors.recipients}
+ <p class="text-destructive text-sm">{fieldErrors.recipients}</p>
+ {:else}
+ <p class="text-muted-foreground text-sm">{m.notifications_signal_recipients_help()}</p>
+ {/if}
+ </div>
+
+ <SwitchWithLabel
+ id="signal-disable-tls"
+ bind:checked={values.disableTls}
+ {disabled}
+ label={m.notifications_signal_disable_tls_label()}
+ description={m.notifications_signal_disable_tls_description()}
+ />
+
+ <EventSubscriptions
+ providerId="signal"
+ bind:eventImageUpdate={values.eventImageUpdate}
+ bind:eventContainerUpdate={values.eventContainerUpdate}
+ {disabled}
+ />
+
+ {#if onTest}
+ <div class="pt-2">
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ onclick={onTest}
+ disabled={disabled || isTesting}
+ loading={isTesting}
+ icon={SendEmailIcon}
+ customLabel={m.notifications_test_notification()}
+ />
+ </div>
+ {/if}
+</ProviderFormWrapper>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/SlackProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/SlackProviderForm.svelte
new file mode 100644
index 000000000..619d951fe
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/notifications/providers/SlackProviderForm.svelte
@@ -0,0 +1,167 @@
+<script lang="ts">
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
+ import { m } from '$lib/paraglide/messages';
+ import { SendEmailIcon } from '$lib/icons';
+ import { z } from 'zod/v4';
+ import type { SlackFormValues } from '$lib/types/notification-providers';
+ import ProviderFormWrapper from './ProviderFormWrapper.svelte';
+ import EventSubscriptions from './EventSubscriptions.svelte';
+
+ interface Props {
+ values: SlackFormValues;
+ disabled?: boolean;
+ isTesting?: boolean;
+ onTest?: () => void;
+ }
+
+ let { values = $bindable(), disabled = false, isTesting = false, onTest }: Props = $props();
+
+ const schema = z
+ .object({
+ enabled: z.boolean(),
+ token: z.string(),
+ botName: z.string(),
+ icon: z.string(),
+ color: z.string(),
+ title: z.string(),
+ channel: z.string(),
+ threadTs: z.string(),
+ eventImageUpdate: z.boolean(),
+ eventContainerUpdate: z.boolean()
+ })
+ .superRefine((d, ctx) => {
+ if (!d.enabled) return;
+
+ // Token is required when enabled
+ if (!d.token.trim()) {
+ ctx.addIssue({ code: 'custom', message: m.notifications_slack_token_required(), path: ['token'] });
+ }
+ });
+
+ const validation = $derived.by(() => schema.safeParse(values));
+
+ const fieldErrors = $derived.by(() => {
+ const errs: Partial<Record<keyof SlackFormValues, string>> = {};
+ if (validation.success) return errs;
+ for (const issue of validation.error.issues) {
+ const key = issue.path?.[0] as keyof SlackFormValues | undefined;
+ if (!key || errs[key]) continue;
+ errs[key] = issue.message;
+ }
+ return errs;
+ });
+
+ export function isValid(): boolean {
+ return validation.success;
+ }
+</script>
+
+<ProviderFormWrapper
+ id="slack"
+ title={m.notifications_slack_title()}
+ description={m.notifications_slack_description()}
+ enabledLabel={m.notifications_slack_enabled_label()}
+ bind:enabled={values.enabled}
+ {disabled}
+>
+ <TextInputWithLabel
+ bind:value={values.token}
+ {disabled}
+ label={m.notifications_slack_token_label()}
+ placeholder={m.notifications_slack_token_placeholder()}
+ type="password"
+ autocomplete="off"
+ helpText={m.notifications_slack_token_help()}
+ />
+ {#if fieldErrors.token}
+ <p class="text-destructive -mt-2 text-sm">{fieldErrors.token}</p>
+ {/if}
+
+ <div class="grid grid-cols-2 gap-4">
+ <TextInputWithLabel
+ bind:value={values.botName}
+ {disabled}
+ label={m.notifications_slack_bot_name_label()}
+ placeholder={m.notifications_slack_bot_name_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_slack_bot_name_help()}
+ />
+
+ <TextInputWithLabel
+ bind:value={values.channel}
+ {disabled}
+ label={m.notifications_slack_channel_label()}
+ placeholder={m.notifications_slack_channel_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_slack_channel_help()}
+ />
+ </div>
+
+ <div class="grid grid-cols-2 gap-4">
+ <TextInputWithLabel
+ bind:value={values.icon}
+ {disabled}
+ label={m.notifications_slack_icon_label()}
+ placeholder={m.notifications_slack_icon_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_slack_icon_help()}
+ />
+
+ <TextInputWithLabel
+ bind:value={values.color}
+ {disabled}
+ label={m.notifications_slack_color_label()}
+ placeholder={m.notifications_slack_color_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_slack_color_help()}
+ />
+ </div>
+
+ <div class="grid grid-cols-2 gap-4">
+ <TextInputWithLabel
+ bind:value={values.title}
+ {disabled}
+ label={m.notifications_slack_title_label()}
+ placeholder={m.notifications_slack_title_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_slack_title_help()}
+ />
+
+ <TextInputWithLabel
+ bind:value={values.threadTs}
+ {disabled}
+ label={m.notifications_slack_thread_ts_label()}
+ placeholder={m.notifications_slack_thread_ts_placeholder()}
+ type="text"
+ autocomplete="off"
+ helpText={m.notifications_slack_thread_ts_help()}
+ />
+ </div>
+
+ <EventSubscriptions
+ providerId="slack"
+ bind:eventImageUpdate={values.eventImageUpdate}
+ bind:eventContainerUpdate={values.eventContainerUpdate}
+ {disabled}
+ />
+
+ {#if onTest}
+ <div class="pt-2">
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ onclick={onTest}
+ disabled={disabled || isTesting}
+ loading={isTesting}
+ icon={SendEmailIcon}
+ customLabel={m.notifications_test_notification()}
+ />
+ </div>
+ {/if}
+</ProviderFormWrapper>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/TelegramProviderForm.svelte b/frontend/src/routes/(app)/settings/notifications/providers/TelegramProviderForm.svelte
new file mode 100644
index 000000000..8d181ea6b
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/notifications/providers/TelegramProviderForm.svelte
@@ -0,0 +1,147 @@
+<script lang="ts">
+ import { ArcaneButton } from '$lib/components/arcane-button/index.js';
+ import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
+ import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
+ import { Label } from '$lib/components/ui/label';
+ import Textarea from '$lib/components/ui/textarea/textarea.svelte';
+ import { m } from '$lib/paraglide/messages';
+ import { SendEmailIcon } from '$lib/icons';
+ import { z } from 'zod/v4';
+ import type { TelegramFormValues } from '$lib/types/notification-providers';
+ import ProviderFormWrapper from './ProviderFormWrapper.svelte';
+ import EventSubscriptions from './EventSubscriptions.svelte';
+
+ interface Props {
+ values: TelegramFormValues;
+ disabled?: boolean;
+ isTesting?: boolean;
+ onTest?: () => void;
+ }
+
+ let { values = $bindable(), disabled = false, isTesting = false, onTest }: Props = $props();
+
+ const schema = z
+ .object({
+ enabled: z.boolean(),
+ botToken: z.string(),
+ chatIds: z.string(),
+ preview: z.boolean(),
+ notification: z.boolean(),
+ title: z.string(),
+ eventImageUpdate: z.boolean(),
+ eventContainerUpdate: z.boolean()
+ })
+ .superRefine((d, ctx) => {
+ if (!d.enabled) return;
+ if (!d.botToken.trim()) {
+ ctx.addIssue({ code: 'custom', message: 'Bot Token is required when Telegram is enabled', path: ['botToken'] });
+ }
+ if (!d.chatIds.trim()) {
+ ctx.addIssue({ code: 'custom', message: 'At least one Chat ID is required when Telegram is enabled', path: ['chatIds'] });
+ }
+ });
+
+ const validation = $derived.by(() => schema.safeParse(values));
+
+ const fieldErrors = $derived.by(() => {
+ const errs: Partial<Record<keyof TelegramFormValues, string>> = {};
+ if (validation.success) return errs;
+ for (const issue of validation.error.issues) {
+ const key = issue.path?.[0] as keyof TelegramFormValues | undefined;
+ if (!key || errs[key]) continue;
+ errs[key] = issue.message;
+ }
+ return errs;
+ });
+
+ export function isValid(): boolean {
+ return validation.success;
+ }
+</script>
+
+<ProviderFormWrapper
+ id="telegram"
+ title="Telegram"
+ description="Send notifications via Telegram bot"
+ enabledLabel="Enable Telegram Notifications"
+ bind:enabled={values.enabled}
+ {disabled}
+>
+ <TextInputWithLabel
+ bind:value={values.botToken}
+ {disabled}
+ label="Bot Token"
+ placeholder="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
+ type="password"
+ autocomplete="off"
+ helpText="The bot token from @BotFather"
+ />
+ {#if fieldErrors.botToken}
+ <p class="text-destructive -mt-2 text-sm">{fieldErrors.botToken}</p>
+ {/if}
+
+ <div class="space-y-2">
+ <Label for="telegram-chat-ids">Chat IDs</Label>
+ <Textarea
+ id="telegram-chat-ids"
+ bind:value={values.chatIds}
+ {disabled}
+ autocomplete="off"
+ placeholder="@channel, 123456789, @another_channel"
+ rows={2}
+ />
+ {#if fieldErrors.chatIds}
+ <p class="text-destructive text-sm">{fieldErrors.chatIds}</p>
+ {:else}
+ <p class="text-muted-foreground text-sm">Comma-separated list of chat IDs or @channel names</p>
+ {/if}
+ </div>
+
+ <TextInputWithLabel
+ bind:value={values.title}
+ {disabled}
+ label="Title (Optional)"
+ placeholder="Arcane Notifications"
+ type="text"
+ autocomplete="off"
+ helpText="Custom title for notifications"
+ />
+
+ <div class="space-y-3">
+ <SwitchWithLabel
+ id="telegram-preview"
+ bind:checked={values.preview}
+ {disabled}
+ label="Enable Link Previews"
+ description="Show web page previews for URLs in messages"
+ />
+ <SwitchWithLabel
+ id="telegram-notification"
+ bind:checked={values.notification}
+ {disabled}
+ label="Enable Notification Sound"
+ description="Play notification sound when messages are received"
+ />
+ </div>
+
+ <EventSubscriptions
+ providerId="telegram"
+ bind:eventImageUpdate={values.eventImageUpdate}
+ bind:eventContainerUpdate={values.eventContainerUpdate}
+ {disabled}
+ />
+
+ {#if onTest}
+ <div class="pt-2">
+ <ArcaneButton
+ action="base"
+ tone="outline"
+ onclick={onTest}
+ disabled={disabled || isTesting}
+ loading={isTesting}
+ icon={SendEmailIcon}
+ customLabel={m.notifications_test_notification()}
+ />
+ </div>
+ {/if}
+</ProviderFormWrapper>
diff --git a/frontend/src/routes/(app)/settings/notifications/providers/index.ts b/frontend/src/routes/(app)/settings/notifications/providers/index.ts
new file mode 100644
index 000000000..ad9a0cb14
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/notifications/providers/index.ts
@@ -0,0 +1,10 @@
+export { default as EmailProviderForm } from './EmailProviderForm.svelte';
+export { default as DiscordProviderForm } from './DiscordProviderForm.svelte';
+export { default as TelegramProviderForm } from './TelegramProviderForm.svelte';
+export { default as SignalProviderForm } from './SignalProviderForm.svelte';
+export { default as SlackProviderForm } from './SlackProviderForm.svelte';
+export { default as AppriseProviderForm } from './AppriseProviderForm.svelte';
+export { default as ProviderFormWrapper } from './ProviderFormWrapper.svelte';
+export { default as EventSubscriptions } from './EventSubscriptions.svelte';
+export { default as NtfyProviderForm } from './NtfyProviderForm.svelte';
+export { default as GenericProviderForm } from './GenericProviderForm.svelte';
diff --git a/go.work.sum b/go.work.sum
index 8e1a86c58..5d7f408fd 100644
--- a/go.work.sum
+++ b/go.work.sum
@@ -44,6 +44,8 @@ github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUM
github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU=
github.com/AzureAD/microsoft-authentication-library-for-go v1.4.2 h1:oygO0locgZJe7PpYPXT5A29ZkwJaPqcva7BVeemZOZs=
github.com/AzureAD/microsoft-authentication-library-for-go v1.4.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI=
+github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
+github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/ClickHouse/clickhouse-go v1.4.3 h1:iAFMa2UrQdR5bHJ2/yaSLffZkxpcOYQMCUuKeNXGdqc=
github.com/ClickHouse/clickhouse-go v1.4.3/go.mod h1:EaI/sW7Azgz9UATzd5ZdZHRUhHgv5+JMS9NSr2smCJI=
github.com/GoogleCloudPlatform/grpc-gcp-go/grpcgcp v1.5.3 h1:2afWGsMzkIcN8Qm4mgPJKZWyroE5QBszMiDMYEBrnfw=
@@ -54,8 +56,6 @@ github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0/go.mod h1:ZPpqegjbE99EPKsu3iUWV22A04wzGPcAY/ziSIQEEgs=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 h1:Ron4zCA/yk6U7WOBXhTJcDpsUBG9npumK6xw2auFltQ=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0/go.mod h1:cSgYe11MCNYunTnRXrKiR/tHc0eoKjICUuWpNZoVCOo=
-github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=
-github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
github.com/Microsoft/go-winio v0.4.21/go.mod h1:JPGBdM1cNvN/6ISo+n8V5iA4v8pBzdOpzfwIujj1a84=
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d h1:G0m3OIz70MZUWq3EgK3CesDbo8upS2Vm9/P3FtgI+Jk=
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d/go.mod h1:3eOhrUMpNV+6aFIbp5/iudMxNCF27Vw2OZgy4xEx0Fg=
@@ -371,6 +371,8 @@ github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
github.com/letsencrypt/boulder v0.0.0-20240620165639-de9c06129bec h1:2tTW6cDth2TSgRbAhD7yjZzTQmcN25sDRPEeinR51yQ=
github.com/letsencrypt/boulder v0.0.0-20240620165639-de9c06129bec/go.mod h1:TmwEoGCwIti7BCeJ9hescZgRtatxRE+A72pCoPfmcfk=
+github.com/magiconair/properties v1.8.9 h1:nWcCbLq1N2v/cpNsy5WvQ37Fb+YElfq20WJ/a8RkpQM=
+github.com/magiconair/properties v1.8.9/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/manifoldco/promptui v0.9.0 h1:3V4HzJk1TtXW1MTZMP7mdlwbBpIinw3HztaIlYthEiA=
@@ -397,6 +399,8 @@ github.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjc
github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg=
github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0=
+github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
+github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/moby/buildkit v0.26.2/go.mod h1:ylDa7IqzVJgLdi/wO7H1qLREFQpmhFbw2fbn4yoTw40=
github.com/moby/policy-helpers v0.0.0-20251105011237-bcaa71c99f14 h1:JO22uXMy3CN7wh7A/wrtYQWV1WYQMg2gh6d8YO325k4=
github.com/moby/policy-helpers v0.0.0-20251105011237-bcaa71c99f14/go.mod h1:HJfK0E8dR+Jpk5anJ3oADg2dRSom1gJK17sqEiiMS7w=
@@ -423,7 +427,6 @@ github.com/neo4j/neo4j-go-driver v1.8.1-0.20200803113522-b626aa943eba h1:fhFP5Rl
github.com/neo4j/neo4j-go-driver v1.8.1-0.20200803113522-b626aa943eba/go.mod h1:ncO5VaFWh0Nrt+4KT4mOZboaczBZcLuHrG+/sUeP8gI=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
-github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc=
github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=
github.com/onsi/gomega v1.15.0 h1:WjP/FQ/sk43MRmnEcT+MlDw2TFvkrXlprrPST/IudjU=
github.com/onsi/gomega v1.15.0/go.mod h1:cIuvLEne0aoVhAgh/O6ac0Op8WWw9H6eYCriF+tEHG0=
@@ -480,6 +483,7 @@ github.com/smallstep/pkcs7 v0.1.1 h1:x+rPdt2W088V9Vkjho4KtoggyktZJlMduZAtRHm68LU
github.com/smallstep/pkcs7 v0.1.1/go.mod h1:dL6j5AIz9GHjVEBTXtW+QliALcgM19RtXaTeyxI+AfA=
github.com/snowflakedb/gosnowflake v1.6.19 h1:KSHXrQ5o7uso25hNIzi/RObXtnSGkFgie91X82KcvMY=
github.com/snowflakedb/gosnowflake v1.6.19/go.mod h1:FM1+PWUdwB9udFDsXdfD58NONC0m+MlOSmQRvimobSM=
+github.com/spf13/jwalterweatherman v0.0.0-20141219030609-3d60171a6431 h1:XTHrT015sxHyJ5FnQ0AeemSspZWaDq7DoTRW0EVsDCE=
github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo=
github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs=
github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6 h1:pnnLyeX7o/5aX8qUQ69P/mLojDqwda8hFOCBTmP/6hw=
@@ -559,7 +563,6 @@ go.opentelemetry.io/otel/exporters/prometheus v0.42.0 h1:jwV9iQdvp38fxXi8ZC+lNpx
go.opentelemetry.io/otel/exporters/prometheus v0.42.0/go.mod h1:f3bYiqNqhoPxkvI2LrXqQVC546K7BuRDL/kKuxkujhA=
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.31.0 h1:UGZ1QwZWY67Z6BmckTU+9Rxn04m2bD3gD6Mk0OIOCPk=
go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.31.0/go.mod h1:fcwWuDuaObkkChiDlhEpSq9+X1C0omv+s5mBtToAQ64=
-go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
golang.org/x/crypto v0.44.0/go.mod h1:013i+Nw79BMiQiMsOPcVCB5ZIJbYkerPrGnOa00tvmc=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
@@ -612,6 +615,7 @@ gopkg.in/gemnasium/logrus-airbrake-hook.v2 v2.1.2 h1:OAj3g0cR6Dx/R07QgQe8wkA9RNj
gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
+gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
gotest.tools/v3 v3.4.0/go.mod h1:CtbdzLSsqVhDgMtKsx03ird5YTGB3ar27v0u/yKBW5g=
diff --git a/tests/spec/settings-notifications.spec.ts b/tests/spec/settings-notifications.spec.ts
index d71eb2785..bfb41229b 100644
--- a/tests/spec/settings-notifications.spec.ts
+++ b/tests/spec/settings-notifications.spec.ts
@@ -1,7 +1,8 @@
-import { test, expect } from '@playwright/test';
+import { test, expect, type Page } from '@playwright/test';
test.describe('Notification settings', () => {
- test('should allow testing email notifications without state_unsafe_mutation errors', async ({ page }) => {
+ // Shared setup for all notification tests
+ const setupNotificationTest = async (page: Page, provider: string) => {
const observedErrors: string[] = [];
page.on('pageerror', (err) => {
@@ -17,7 +18,7 @@ test.describe('Notification settings', () => {
let saveEndpointCalled = false;
let testEndpointCalled = false;
- // Stub "save settings" so we don't depend on a real backend/DB for this flow.
+ // Stub "save settings"
await page.route('**/api/environments/*/notifications/settings', async (route) => {
const req = route.request();
if (req.method() === 'POST') {
@@ -32,8 +33,8 @@ test.describe('Notification settings', () => {
await route.continue();
});
- // Stub the test endpoint so no SMTP server is required.
- await page.route('**/api/environments/*/notifications/test/email**', async (route) => {
+ // Stub the specific test endpoint
+ await page.route(`**/api/environments/*/notifications/test/${provider}**`, async (route) => {
testEndpointCalled = true;
await route.fulfill({
status: 200,
@@ -45,34 +46,161 @@ test.describe('Notification settings', () => {
await page.goto('/settings/notifications');
await page.waitForLoadState('networkidle');
- // Enable email notifications (the test button only appears when enabled).
+ return {
+ getErrorCheck: () => {
+ const stateUnsafe = observedErrors.filter((e) => e.includes('state_unsafe_mutation'));
+ expect(stateUnsafe, `Unexpected state_unsafe_mutation errors: ${stateUnsafe.join('\n')}`).toHaveLength(0);
+ },
+ wasTestEndpointCalled: () => testEndpointCalled,
+ wasSaveEndpointCalled: () => saveEndpointCalled,
+ };
+ };
+
+ test('should allow testing email notifications without state_unsafe_mutation errors', async ({ page }) => {
+ const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'email');
+
+ // Enable email notifications
await page.locator('#email-enabled').click();
- // Fill the minimum required fields so "Save and Test" is valid.
+ // Fill fields
await page.getByPlaceholder('smtp.example.com').fill('smtp.example.com');
await page.getByPlaceholder('[email protected]').fill('[email protected]');
await page.getByPlaceholder('[email protected], [email protected]').fill('[email protected]');
- // The dropdown trigger uses an internal button wrapper; target the trigger attribute to avoid strict-mode ambiguity.
- await page.locator('[data-dropdown-menu-trigger]').filter({ hasText: 'Test Email' }).click();
+ // Trigger test
+ await page.locator('[data-dropdown-menu-trigger]').filter({ hasText: 'Test' }).click();
await page.getByRole('menuitem', { name: 'Simple Test Email', exact: true }).click();
- // If we have unsaved changes, the page will prompt to save before testing.
+ // Handle Save & Test if needed
+ const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });
+ if (await saveAndTestButton.isVisible().catch(() => false)) {
+ await saveAndTestButton.click();
+ }
+
+ await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);
+ getErrorCheck();
+ });
+
+ test('should allow testing discord notifications', async ({ page }) => {
+ const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'discord');
+
+ await page.getByRole('tab', { name: 'Discord' }).click();
+ await page.locator('#discord-enabled').click();
+
+ // Discord split fields
+ await page.getByPlaceholder('Enter webhook ID').fill('123456789');
+ await page.getByPlaceholder('Enter webhook token').fill('abc-def-ghi');
+
+ await page.getByRole('button', { name: 'Test Provider' }).click();
+
const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });
- const didClickSaveAndTest = await saveAndTestButton.isVisible().catch(() => false);
- if (didClickSaveAndTest) {
+ if (await saveAndTestButton.isVisible().catch(() => false)) {
await saveAndTestButton.click();
}
- await expect.poll(() => testEndpointCalled, { timeout: 10_000 }).toBe(true);
+ await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);
+ getErrorCheck();
+ });
+
+ test('should allow testing slack notifications', async ({ page }) => {
+ const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'slack');
- // If the modal path was taken, we should have attempted to save.
- // (Not strictly required for this bug, but it's a helpful sanity check.)
- if (didClickSaveAndTest) {
- await expect.poll(() => saveEndpointCalled, { timeout: 10_000 }).toBe(true);
+ await page.getByRole('tab', { name: 'Slack' }).click();
+ await page.locator('#slack-enabled').click();
+
+ // Slack OAuth token (xoxb- or xoxp- format)
+ await page.getByPlaceholder('xoxb-... or xoxp-...').fill('xoxb-123456789012-1234567890123-abcdefghijklmnopqrstuvwx');
+
+ await page.getByRole('button', { name: 'Test Provider' }).click();
+
+ const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });
+ if (await saveAndTestButton.isVisible().catch(() => false)) {
+ await saveAndTestButton.click();
+ }
+
+ await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);
+ getErrorCheck();
+ });
+
+ test('should allow testing telegram notifications', async ({ page }) => {
+ const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'telegram');
+
+ await page.getByRole('tab', { name: 'Telegram' }).click();
+ await page.locator('#telegram-enabled').click();
+
+ // Telegram fields (placeholders are hardcoded in component)
+ await page.getByPlaceholder('123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11').fill('123456:TEST-TOKEN');
+ await page.getByPlaceholder('@channel, 123456789, @another_channel').fill('123456789');
+
+ await page.getByRole('button', { name: 'Test Provider' }).click();
+
+ const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });
+ if (await saveAndTestButton.isVisible().catch(() => false)) {
+ await saveAndTestButton.click();
+ }
+
+ await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);
+ getErrorCheck();
+ });
+
+ test('should allow testing generic webhook notifications', async ({ page }) => {
+ const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'generic');
+
+ await page.getByRole('tab', { name: 'Generic' }).click();
+ await page.locator('#generic-enabled').click();
+
+ await page.getByPlaceholder('https://example.com/webhook').fill('https://example.com/webhook');
+
+ await page.getByRole('button', { name: 'Test Provider' }).click();
+
+ const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });
+ if (await saveAndTestButton.isVisible().catch(() => false)) {
+ await saveAndTestButton.click();
+ }
+
+ await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);
+ getErrorCheck();
+ });
+
+ test('should allow testing signal notifications', async ({ page }) => {
+ const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'signal');
+
+ await page.getByRole('tab', { name: 'Signal' }).click();
+ await page.locator('#signal-enabled').click();
+
+ await page.getByPlaceholder('localhost').fill('signal-api.example.com');
+ await page.getByPlaceholder('8080').fill('8080');
+ await page.getByRole('textbox', { name: '+' }).fill('+1234567890');
+ await page.getByRole('textbox', { name: 'Recipients' }).fill('+1987654321');
+
+ await page.getByRole('button', { name: 'Test Provider' }).click();
+
+ const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });
+ if (await saveAndTestButton.isVisible().catch(() => false)) {
+ await saveAndTestButton.click();
+ }
+
+ await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);
+ getErrorCheck();
+ });
+
+ test('should allow testing ntfy notifications', async ({ page }) => {
+ const { getErrorCheck, wasTestEndpointCalled } = await setupNotificationTest(page, 'ntfy');
+
+ await page.getByRole('tab', { name: 'Ntfy' }).click();
+ await page.locator('#ntfy-enabled').click();
+
+ await page.getByPlaceholder('ntfy.sh').fill('ntfy.sh');
+ await page.getByPlaceholder('my-updates').fill('arcane-updates');
+
+ await page.getByRole('button', { name: 'Test Provider' }).click();
+
+ const saveAndTestButton = page.getByRole('button', { name: 'Save & Test', exact: true });
+ if (await saveAndTestButton.isVisible().catch(() => false)) {
+ await saveAndTestButton.click();
}
- const stateUnsafe = observedErrors.filter((e) => e.includes('state_unsafe_mutation'));
- expect(stateUnsafe, `Unexpected state_unsafe_mutation errors: ${stateUnsafe.join('\n')}`).toHaveLength(0);
+ await expect.poll(wasTestEndpointCalled, { timeout: 10_000 }).toBe(true);
+ getErrorCheck();
});
});
diff --git a/types/notification/notification.go b/types/notification/notification.go
index 8996f35a4..949dc16d0 100644
--- a/types/notification/notification.go
+++ b/types/notification/notification.go
@@ -11,6 +11,21 @@ const (
// NotificationProviderEmail is the builtin Email notification provider.
NotificationProviderEmail Provider = "email"
+
+ // NotificationProviderTelegram is the builtin Telegram notification provider.
+ NotificationProviderTelegram Provider = "telegram"
+
+ // NotificationProviderSignal is the builtin Signal notification provider.
+ NotificationProviderSignal Provider = "signal"
+
+ // NotificationProviderSlack is the builtin Slack notification provider.
+ NotificationProviderSlack Provider = "slack"
+
+ // NotificationProviderNtfy is the builtin Ntfy notification provider.
+ NotificationProviderNtfy Provider = "ntfy"
+
+ // NotificationProviderGeneric is the builtin Generic webhook notification provider.
+ NotificationProviderGeneric Provider = "generic"
)
type Update struct {