feat(notification): add Bark push support

Add Bark as a notification-service delivery channel, including encrypted Device Key configuration, server URL/template settings, module status integration, and admin UI support.
This commit is contained in:
AAEE86
2026-05-22 11:08:00 +08:00
parent 3714c211dc
commit ce44d35eb6
12 changed files with 713 additions and 12 deletions

View File

@@ -0,0 +1,173 @@
use crate::handlers::shared::{
decrypt_catalog_secret_with_fallbacks, system_config_bool, system_config_string,
};
use crate::{AppState, GatewayError};
use serde_json::{json, Value};
pub(crate) const BARK_PUSH_ENABLED_KEY: &str = "module.bark_push.enabled";
pub(crate) const BARK_PUSH_DEVICE_KEY_KEY: &str = "module.bark_push.device_key";
pub(crate) const BARK_PUSH_SERVER_URL_KEY: &str = "module.bark_push.server_url";
pub(crate) const BARK_PUSH_TEMPLATE_KEY: &str = "module.bark_push.template";
const DEFAULT_BARK_API_BASE: &str = "https://api.day.app";
#[derive(Debug, Clone)]
pub(crate) struct BarkPushConfig {
pub(crate) enabled: bool,
pub(crate) device_key: Option<String>,
pub(crate) server_url: String,
pub(crate) template: Option<String>,
}
pub(crate) async fn bark_push_module_enabled(state: &AppState) -> Result<bool, GatewayError> {
let value = state
.read_system_config_json_value(BARK_PUSH_ENABLED_KEY)
.await?;
Ok(system_config_bool(value.as_ref(), false))
}
pub(crate) async fn bark_push_configured(state: &AppState) -> Result<bool, GatewayError> {
let config = read_bark_push_config(state).await?;
Ok(config.device_key.is_some() && !config.server_url.trim().is_empty())
}
pub(crate) async fn read_bark_push_config(
state: &AppState,
) -> Result<BarkPushConfig, GatewayError> {
let enabled = bark_push_module_enabled(state).await?;
let device_key = state
.read_system_config_json_value(BARK_PUSH_DEVICE_KEY_KEY)
.await?
.and_then(|value| system_config_string(Some(&value)))
.map(|value| {
decrypt_catalog_secret_with_fallbacks(state.encryption_key(), &value).unwrap_or(value)
});
let server_url = state
.read_system_config_json_value(BARK_PUSH_SERVER_URL_KEY)
.await?
.and_then(|value| system_config_string(Some(&value)))
.filter(|value| !value.trim().is_empty())
.unwrap_or_else(|| DEFAULT_BARK_API_BASE.to_string());
let template = state
.read_system_config_json_value(BARK_PUSH_TEMPLATE_KEY)
.await?
.and_then(|value| system_config_string(Some(&value)));
Ok(BarkPushConfig {
enabled,
device_key,
server_url,
template,
})
}
pub(crate) async fn send_bark_push(
state: &AppState,
config: &BarkPushConfig,
title: &str,
markdown_body: &str,
) -> Result<(), GatewayError> {
let Some(device_key) = config.device_key.as_deref() else {
return Err(GatewayError::Internal("未配置 Bark Device Key".to_string()));
};
let device_key = device_key.trim();
if device_key.is_empty() {
return Err(GatewayError::Internal(
"Bark Device Key 不能为空".to_string(),
));
}
let server_url = normalized_bark_server_url(&config.server_url)?;
let body = render_bark_body(config.template.as_deref(), title, markdown_body);
let response = state
.client
.post(format!("{server_url}/push"))
.json(&json!({
"device_key": device_key,
"title": title,
"body": body,
}))
.send()
.await
.map_err(|err| GatewayError::Internal(err.to_string()))?;
let status = response.status();
let text = response
.text()
.await
.map_err(|err| GatewayError::Internal(err.to_string()))?;
if !status.is_success() {
return Err(GatewayError::Internal(format!(
"Bark 返回 HTTP {status}: {text}"
)));
}
if let Ok(payload) = serde_json::from_str::<Value>(&text) {
let code_is_ok = payload
.get("code")
.and_then(|value| {
value
.as_i64()
.map(|code| matches!(code, 0 | 200))
.or_else(|| {
value
.as_str()
.map(|code| matches!(code.trim(), "0" | "200"))
})
})
.unwrap_or(true);
if !code_is_ok {
return Err(GatewayError::Internal(format!("Bark 返回失败: {payload}")));
}
}
Ok(())
}
fn normalized_bark_server_url(server_url: &str) -> Result<String, GatewayError> {
let server_url = server_url.trim().trim_end_matches('/');
if server_url.is_empty() {
return Err(GatewayError::Internal(
"Bark 服务器地址不能为空".to_string(),
));
}
if !server_url.starts_with("https://") && !server_url.starts_with("http://") {
return Err(GatewayError::Internal(
"Bark 服务器地址必须以 http:// 或 https:// 开头".to_string(),
));
}
Ok(server_url.to_string())
}
fn render_bark_body(template: Option<&str>, title: &str, markdown_body: &str) -> String {
match template {
Some(template) if !template.trim().is_empty() => template
.replace("{title}", title)
.replace("{body}", markdown_body),
_ => markdown_body.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::{normalized_bark_server_url, render_bark_body};
#[test]
fn bark_body_uses_template_when_provided() {
let rendered = render_bark_body(Some("{title}\n\n{body}"), "告警", "原始正文");
assert_eq!(rendered, "告警\n\n原始正文");
}
#[test]
fn bark_body_falls_back_to_markdown_body_for_empty_template() {
assert_eq!(render_bark_body(None, "告警", "原始正文"), "原始正文");
assert_eq!(
render_bark_body(Some(" "), "告警", "原始正文"),
"原始正文"
);
}
#[test]
fn bark_server_url_trims_trailing_slashes() {
assert_eq!(
normalized_bark_server_url(" https://api.day.app/ ").expect("url should parse"),
"https://api.day.app"
);
}
}

View File

@@ -1,3 +1,4 @@
use crate::bark_push::bark_push_configured;
use crate::handlers::admin::request::AdminAppState;
use crate::handlers::shared::{module_available_from_env, system_config_bool};
use crate::important_notification::{
@@ -96,6 +97,18 @@ pub(crate) const ADMIN_MODULE_DEFINITIONS: &[AdminModuleDefinition] = &[
admin_menu_group: Some("system"),
admin_menu_order: 59,
},
AdminModuleDefinition {
name: "bark_push",
display_name: "Bark 推送",
description: "第三方推送服务,配置 Bark Device Key 并测试 iOS 推送",
category: "integration",
env_key: "BARK_PUSH_AVAILABLE",
default_available: true,
admin_route: Some("/admin/modules/bark"),
admin_menu_icon: Some("Send"),
admin_menu_group: Some("system"),
admin_menu_order: 59,
},
AdminModuleDefinition {
name: "model_directives",
display_name: "模型后缀参数",
@@ -169,6 +182,7 @@ pub(crate) struct AdminModuleRuntimeState {
gemini_files_has_capable_key: bool,
important_notification_configured: bool,
server_chan_push_configured: bool,
bark_push_configured: bool,
}
pub(crate) fn admin_module_by_name(name: &str) -> Option<&'static AdminModuleDefinition> {
@@ -257,6 +271,7 @@ pub(crate) async fn build_admin_module_runtime_state(
let notification_configured = important_notification_configured(state.app()).await?;
let server_chan_configured = server_chan_push_configured(state.app()).await?;
let bark_configured = bark_push_configured(state.app()).await?;
Ok(AdminModuleRuntimeState {
oauth_providers,
@@ -264,6 +279,7 @@ pub(crate) async fn build_admin_module_runtime_state(
gemini_files_has_capable_key,
important_notification_configured: notification_configured,
server_chan_push_configured: server_chan_configured,
bark_push_configured: bark_configured,
})
}
@@ -278,6 +294,7 @@ pub(crate) fn build_admin_module_validation_result(
runtime.gemini_files_has_capable_key,
runtime.important_notification_configured,
runtime.server_chan_push_configured,
runtime.bark_push_configured,
)
}

View File

@@ -1,4 +1,5 @@
use crate::admin_api::AdminAppState;
use crate::bark_push::{read_bark_push_config, send_bark_push, BarkPushConfig};
use crate::email_delivery::{
read_smtp_delivery_config, send_smtp_email, ComposedEmail, SmtpDeliveryConfig,
};
@@ -35,6 +36,7 @@ pub(crate) enum ImportantNotificationChannelFilter {
All,
Email,
ServerChan,
Bark,
}
#[derive(Debug, Clone)]
@@ -45,6 +47,7 @@ struct ImportantNotificationConfig {
default_channel: ImportantNotificationChannelFilter,
items: Vec<ImportantNotificationItemConfig>,
server_chan: ServerChanPushConfig,
bark: BarkPushConfig,
}
#[derive(Debug, Clone)]
@@ -63,6 +66,7 @@ struct ImportantNotificationItemConfig {
struct NotificationChannelReadiness {
email: bool,
server_chan: bool,
bark: bool,
}
#[derive(Debug, Clone, Serialize)]
@@ -226,6 +230,7 @@ async fn read_notification_channel_readiness(
Ok(NotificationChannelReadiness {
email: config.email_enabled && !config.email_recipients.is_empty() && smtp_config.is_some(),
server_chan: config.server_chan.enabled && config.server_chan.send_key.is_some(),
bark: config.bark.enabled && config.bark.device_key.is_some(),
})
}
@@ -234,9 +239,12 @@ fn channel_filter_has_ready_channel(
readiness: NotificationChannelReadiness,
) -> bool {
match filter {
ImportantNotificationChannelFilter::All => readiness.email || readiness.server_chan,
ImportantNotificationChannelFilter::All => {
readiness.email || readiness.server_chan || readiness.bark
}
ImportantNotificationChannelFilter::Email => readiness.email,
ImportantNotificationChannelFilter::ServerChan => readiness.server_chan,
ImportantNotificationChannelFilter::Bark => readiness.bark,
}
}
@@ -292,6 +300,20 @@ async fn dispatch_important_notification(
.await;
}
if matches!(
channel_filter,
ImportantNotificationChannelFilter::All | ImportantNotificationChannelFilter::Bark
) {
maybe_send_bark_notification(
state,
&config,
&notification,
bypass_enable_checks,
&mut reports,
)
.await;
}
if reports.is_empty() {
reports.push(ImportantNotificationChannelReport {
channel: "none",
@@ -385,6 +407,7 @@ async fn read_important_notification_config(
.unwrap_or(ImportantNotificationChannelFilter::All),
items: parse_notification_items(items.as_ref()),
server_chan: read_server_chan_push_config(state).await?,
bark: read_bark_push_config(state).await?,
})
}
@@ -395,6 +418,7 @@ fn parse_channel_filter(raw: &str) -> Option<ImportantNotificationChannelFilter>
"server_chan" | "serverchan" | "serve_chan" => {
Some(ImportantNotificationChannelFilter::ServerChan)
}
"bark" => Some(ImportantNotificationChannelFilter::Bark),
"global" | "" => None,
_ => None,
}
@@ -680,6 +704,48 @@ async fn maybe_send_server_chan_notification(
}
}
async fn maybe_send_bark_notification(
state: &AppState,
config: &ImportantNotificationConfig,
notification: &ImportantNotification,
bypass_channel_toggle: bool,
reports: &mut Vec<ImportantNotificationChannelReport>,
) {
if !bypass_channel_toggle && !config.bark.enabled {
return;
}
if config.bark.device_key.is_none() {
reports.push(ImportantNotificationChannelReport {
channel: "bark",
success: false,
message: "未配置 Bark Device Key".to_string(),
});
return;
};
match send_bark_push(
state,
&config.bark,
&notification.title,
&notification.markdown_body,
)
.await
{
Ok(()) => reports.push(ImportantNotificationChannelReport {
channel: "bark",
success: true,
message: "Bark 通知已发送".to_string(),
}),
Err(err) => {
warn!(error = ?err, "failed to send bark important notification");
reports.push(ImportantNotificationChannelReport {
channel: "bark",
success: false,
message: format!("Bark 通知发送失败: {err:?}"),
});
}
}
}
fn single_report(
channel: &'static str,
success: bool,
@@ -743,8 +809,8 @@ fn escape_html(value: &str) -> String {
#[cfg(test)]
mod tests {
use super::{
apply_notification_item_template, parse_notification_items, parse_recipient_list,
ImportantNotification, ImportantNotificationChannelFilter,
apply_notification_item_template, parse_channel_filter, parse_notification_items,
parse_recipient_list, ImportantNotification, ImportantNotificationChannelFilter,
};
use serde_json::json;
@@ -785,6 +851,14 @@ mod tests {
assert!(items[0].user_email_enabled);
}
#[test]
fn parse_channel_filter_accepts_bark() {
assert_eq!(
parse_channel_filter("bark"),
Some(ImportantNotificationChannelFilter::Bark)
);
}
#[test]
fn item_template_renders_fallback_and_variables() {
let items = parse_notification_items(Some(&json!([

View File

@@ -30,6 +30,7 @@ mod api;
mod async_task;
mod audit;
mod auth;
mod bark_push;
mod cache;
mod client_session_affinity;
mod clock;

View File

@@ -816,6 +816,8 @@ async fn gateway_handles_admin_modules_status_locally_with_trusted_admin_princip
payload["server_chan_push"]["admin_route"],
"/admin/modules/server-chan"
);
assert_eq!(payload["bark_push"]["display_name"], "Bark 推送");
assert_eq!(payload["bark_push"]["admin_route"], "/admin/modules/bark");
assert_eq!(*upstream_hits.lock().expect("mutex should lock"), 0);
gateway_handle.abort();

View File

@@ -705,11 +705,13 @@ struct AdminApiFormatDefinition {
const REQUEST_RECORD_LEVEL_KEY: &str = "request_record_level";
const LEGACY_REQUEST_LOG_LEVEL_KEY: &str = "request_log_level";
const DEFAULT_BARK_API_BASE: &str = "https://api.day.app";
const SENSITIVE_SYSTEM_CONFIG_KEYS: &[&str] = &[
"smtp_password",
"turnstile_secret_key",
"module.server_chan_push.send_key",
"module.important_notification.server_chan_send_key",
"module.bark_push.device_key",
];
const ADMIN_API_FORMAT_DEFINITIONS: &[AdminApiFormatDefinition] = &[
AdminApiFormatDefinition {
@@ -1207,6 +1209,7 @@ pub fn build_admin_module_validation_result(
gemini_files_has_capable_key: bool,
important_notification_configured: bool,
server_chan_push_configured: bool,
bark_push_configured: bool,
) -> (bool, Option<String>) {
match module_name {
"oauth" => {
@@ -1291,6 +1294,13 @@ pub fn build_admin_module_validation_result(
(false, Some("请先配置 Server 酱 SendKey".to_string()))
}
}
"bark_push" => {
if bark_push_configured {
(true, None)
} else {
(false, Some("请先配置 Bark Device Key".to_string()))
}
}
"gemini_files" => {
if gemini_files_has_capable_key {
(true, None)
@@ -1315,6 +1325,7 @@ pub fn build_admin_module_health(
| "model_directives"
| "proxy_nodes"
| "important_notification"
| "bark_push"
| "server_chan_push" => "healthy",
"gemini_files" => {
if gemini_files_has_capable_key {
@@ -1661,6 +1672,10 @@ pub fn admin_system_config_default_value(key: &str) -> Option<serde_json::Value>
"module.server_chan_push.enabled" => Some(json!(false)),
"module.server_chan_push.send_key" => Some(serde_json::Value::Null),
"module.server_chan_push.template" => Some(json!("")),
"module.bark_push.enabled" => Some(json!(false)),
"module.bark_push.device_key" => Some(serde_json::Value::Null),
"module.bark_push.server_url" => Some(json!(DEFAULT_BARK_API_BASE)),
"module.bark_push.template" => Some(json!("")),
"module.chat_pii_redaction.enabled" => Some(json!(false)),
"module.chat_pii_redaction.rules" => Some(chat_pii_redaction_default_rules()),
"module.chat_pii_redaction.cache_ttl_seconds" => Some(json!(300)),
@@ -1849,6 +1864,25 @@ fn normalize_nullable_string_config_value(
}
}
fn normalize_bark_server_url_config_value(
value: serde_json::Value,
) -> Result<serde_json::Value, ()> {
match value {
Value::Null => Ok(json!(DEFAULT_BARK_API_BASE)),
Value::String(raw) => {
let raw = raw.trim().trim_end_matches('/');
if raw.is_empty() {
return Ok(json!(DEFAULT_BARK_API_BASE));
}
if !raw.starts_with("https://") && !raw.starts_with("http://") {
return Err(());
}
Ok(json!(raw))
}
_ => Err(()),
}
}
fn normalize_notification_channel_value(value: serde_json::Value) -> Result<serde_json::Value, ()> {
match value {
Value::Null => Ok(json!("all")),
@@ -1865,6 +1899,7 @@ fn normalize_notification_channel(raw: &str, allow_global: bool) -> Result<&'sta
"all" => Ok("all"),
"email" => Ok("email"),
"server_chan" | "serverchan" | "serve_chan" => Ok("server_chan"),
"bark" => Ok("bark"),
"global" | "" if allow_global => Ok("global"),
_ => Err(()),
}
@@ -2023,7 +2058,8 @@ pub fn parse_admin_system_config_update(
match normalized_key.as_str() {
"module.important_notification.enabled"
| "module.important_notification.email_enabled"
| "module.server_chan_push.enabled" => match value.as_bool() {
| "module.server_chan_push.enabled"
| "module.bark_push.enabled" => match value.as_bool() {
Some(enabled) => value = json!(enabled),
None if value.is_null() => {
value = admin_system_config_default_value(&normalized_key).unwrap_or(json!(false));
@@ -2083,6 +2119,34 @@ pub fn parse_admin_system_config_update(
}
};
}
"module.bark_push.device_key" => {
value = normalize_nullable_string_config_value(value).map_err(|_| {
(
http::StatusCode::BAD_REQUEST,
json!({ "detail": "请求数据验证失败" }),
)
})?;
}
"module.bark_push.server_url" => {
value = normalize_bark_server_url_config_value(value).map_err(|_| {
(
http::StatusCode::BAD_REQUEST,
json!({ "detail": "请求数据验证失败" }),
)
})?;
}
"module.bark_push.template" => {
value = match value {
Value::Null => json!(""),
Value::String(raw) => json!(raw),
_ => {
return Err((
http::StatusCode::BAD_REQUEST,
json!({ "detail": "请求数据验证失败" }),
));
}
};
}
"module.chat_pii_redaction.enabled" => match value.as_bool() {
Some(enabled) => value = json!(enabled),
None if value.is_null() => {
@@ -3145,6 +3209,9 @@ mod tests {
assert!(is_sensitive_admin_system_config_key(
"module.important_notification.server_chan_send_key"
));
assert!(is_sensitive_admin_system_config_key(
"module.bark_push.device_key"
));
assert!(!is_sensitive_admin_system_config_key("site_name"));
}
@@ -3208,6 +3275,25 @@ mod tests {
assert_eq!(update.value[0]["user_email_enabled"], json!(true));
}
#[test]
fn bark_push_config_values_are_normalized() {
let update = parse_admin_system_config_update(
"module.bark_push.server_url",
r#"{ "value": " https://api.day.app/ " }"#.as_bytes(),
)
.expect("server url should parse");
assert_eq!(update.normalized_key, "module.bark_push.server_url");
assert_eq!(update.value, json!("https://api.day.app"));
let err = parse_admin_system_config_update(
"module.bark_push.server_url",
r#"{ "value": "api.day.app" }"#.as_bytes(),
)
.expect_err("server url without scheme should fail");
assert_eq!(err.0, http::StatusCode::BAD_REQUEST);
}
#[test]
fn build_admin_system_config_detail_masks_turnstile_secret_key() {
let payload = build_admin_system_config_detail_payload(

View File

@@ -918,8 +918,8 @@ export const adminApi = {
return response.data
},
async testImportantNotification(options: 'all' | 'email' | 'server_chan' | {
channel?: 'all' | 'email' | 'server_chan'
async testImportantNotification(options: 'all' | 'email' | 'server_chan' | 'bark' | {
channel?: 'all' | 'email' | 'server_chan' | 'bark'
item_key?: string
} = 'all'): Promise<{
success: boolean

View File

@@ -956,6 +956,10 @@ export const MOCK_SYSTEM_CONFIGS: Array<{ key: string; value: unknown; descripti
{ key: 'module.server_chan_push.enabled', value: false, description: 'Server 酱推送开关' },
{ key: 'module.server_chan_push.send_key', value: null, description: 'Server 酱 SendKey' },
{ key: 'module.server_chan_push.template', value: '', description: 'Server 酱推送模板' },
{ key: 'module.bark_push.enabled', value: false, description: 'Bark 推送开关' },
{ key: 'module.bark_push.device_key', value: null, description: 'Bark Device Key' },
{ key: 'module.bark_push.server_url', value: 'https://api.day.app', description: 'Bark 服务器地址' },
{ key: 'module.bark_push.template', value: '', description: 'Bark 推送模板' },
{ key: 'proxy_node_metrics_1m_retention_days', value: 30, description: '代理节点 1m 指标保留天数' },
{ key: 'proxy_node_metrics_1h_retention_days', value: 180, description: '代理节点 1h 指标保留天数' },
{ key: 'proxy_node_metrics_cleanup_batch_size', value: 5000, description: '代理节点指标每批次清理条数' }
@@ -1032,6 +1036,20 @@ const MOCK_MODULE_DEFINITIONS: Array<Omit<ModuleStatus, 'active' | 'health'> & {
admin_menu_group: 'system',
admin_menu_order: 59,
},
{
name: 'bark_push',
display_name: 'Bark 推送',
description: '第三方推送服务,配置 Bark Device Key 并测试 iOS 推送',
category: 'integration',
available: true,
enabled: false,
config_validated: false,
config_error: '请先配置 Bark Device Key',
admin_route: '/admin/modules/bark',
admin_menu_icon: 'Send',
admin_menu_group: 'system',
admin_menu_order: 59,
},
{
name: 'chat_pii_redaction',
display_name: '敏感信息保护',

View File

@@ -1805,7 +1805,7 @@ registerDynamicRoute('GET', '/api/admin/system/configs/:configKey', async (_conf
if (!entry) {
throw { response: createMockResponse({ detail: `配置项 '${key}' 不存在` }, 404) }
}
if (key === 'module.server_chan_push.send_key') {
if (key === 'module.server_chan_push.send_key' || key === 'module.bark_push.device_key') {
return createMockResponse({
key: entry.key,
value: null,

View File

@@ -294,6 +294,16 @@ const routes: RouteRecordRaw[] = [
component: () => importWithRetry(() => import('@/views/admin/modules/ServerChanSettings.vue')),
meta: { module: 'server_chan_push' }
},
{
path: 'bark',
redirect: '/admin/modules/bark'
},
{
path: 'modules/bark',
name: 'BarkSettings',
component: () => importWithRetry(() => import('@/views/admin/modules/BarkSettings.vue')),
meta: { module: 'bark_push' }
},
{
path: 'email',
name: 'EmailSettings',

View File

@@ -0,0 +1,271 @@
<template>
<PageContainer>
<PageHeader
title="Bark 推送"
description="第三方推送服务,用于通知服务的 Bark 渠道"
/>
<div class="mt-6 space-y-6">
<CardSection
title="服务配置"
description="配置 Bark Device Key、服务器地址和服务启用状态"
>
<template #actions>
<Button
size="sm"
:disabled="saving"
@click="saveConfig"
>
{{ saving ? '保存中...' : '保存' }}
</Button>
</template>
<div class="space-y-5">
<div class="flex items-center justify-between gap-4 rounded-lg border border-border/70 px-4 py-3">
<div>
<Label class="text-sm font-medium">
启用 Bark 推送
</Label>
<p class="mt-1 text-xs text-muted-foreground">
通知服务选择 Bark 时会检查此开关
</p>
</div>
<Switch
v-model="enabled"
:disabled="!canEnable"
/>
</div>
<div class="grid gap-4 lg:grid-cols-2">
<div>
<Label
for="bark-device-key"
class="block text-sm font-medium"
>
Device Key
</Label>
<Input
id="bark-device-key"
v-model="deviceKeyInput"
masked
:placeholder="deviceKeyIsSet ? '已设置(留空保持不变)' : '从 Bark App 推送地址中获取'"
class="mt-1"
/>
<p class="mt-1 text-xs text-muted-foreground">
Bark App 中推送地址
<span class="font-mono">https://api.day.app/xxxx</span>
<span class="font-mono">xxxx</span> 部分
</p>
</div>
<div>
<Label
for="bark-server-url"
class="block text-sm font-medium"
>
服务器地址
</Label>
<Input
id="bark-server-url"
v-model="serverUrlInput"
placeholder="https://api.day.app"
class="mt-1"
/>
<p class="mt-1 text-xs text-muted-foreground">
支持官方服务或自建 Bark Server保存时会去掉末尾斜杠
</p>
</div>
</div>
</div>
</CardSection>
<CardSection
title="通知模板"
description="模板支持 {title} 和 {body} 变量"
>
<div>
<Label
for="bark-template"
class="block text-sm font-medium"
>
模板内容
</Label>
<Textarea
id="bark-template"
v-model="templateInput"
rows="10"
class="mt-1 font-mono text-sm"
placeholder="{body}"
spellcheck="false"
/>
</div>
</CardSection>
<CardSection
title="测试服务"
description="按已保存配置发送一条 Bark 测试通知"
>
<div class="flex flex-wrap gap-2">
<Button
variant="outline"
:disabled="testing || !deviceKeyIsSet"
@click="handleTest"
>
{{ testing ? '发送中...' : '发送测试' }}
</Button>
<RouterLink
to="/admin/notification-service"
class="inline-flex h-11 items-center rounded-xl px-3 text-sm text-primary hover:underline"
>
打开通知服务
</RouterLink>
</div>
<div
v-if="lastTestResult.length > 0"
class="mt-4 space-y-2"
>
<div
v-for="item in lastTestResult"
:key="item.channel"
class="flex items-center justify-between gap-4 rounded-md border border-border px-3 py-2 text-sm"
>
<span>{{ formatChannel(item.channel) }}</span>
<span :class="item.success ? 'text-green-600 dark:text-green-400' : 'text-destructive'">
{{ item.message }}
</span>
</div>
</div>
</CardSection>
</div>
</PageContainer>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { RouterLink } from 'vue-router'
import { Button, Input, Label, Switch, Textarea } from '@/components/ui'
import { PageHeader, PageContainer, CardSection } from '@/components/layout'
import { adminApi } from '@/api/admin'
import { modulesApi } from '@/api/modules'
import { useToast } from '@/composables/useToast'
import { parseApiError } from '@/utils/errorParser'
import { log } from '@/utils/logger'
const CONFIG_KEYS = {
enabled: 'module.bark_push.enabled',
device_key: 'module.bark_push.device_key',
server_url: 'module.bark_push.server_url',
template: 'module.bark_push.template',
} as const
const DEFAULT_SERVER_URL = 'https://api.day.app'
const { success, error } = useToast()
const saving = ref(false)
const testing = ref(false)
const enabled = ref(false)
const deviceKeyIsSet = ref(false)
const deviceKeyInput = ref('')
const serverUrlInput = ref(DEFAULT_SERVER_URL)
const templateInput = ref('')
const lastTestResult = ref<Array<{ channel: string; success: boolean; message: string }>>([])
const canEnable = computed(() => deviceKeyIsSet.value || deviceKeyInput.value.trim() !== '')
onMounted(() => {
loadConfig()
})
async function loadConfig() {
try {
const [moduleStatus, deviceKey, serverUrl, template] = await Promise.all([
modulesApi.getStatus('bark_push'),
adminApi.getSystemConfig(CONFIG_KEYS.device_key),
adminApi.getSystemConfig(CONFIG_KEYS.server_url),
adminApi.getSystemConfig(CONFIG_KEYS.template),
])
enabled.value = moduleStatus.enabled === true
deviceKeyIsSet.value = deviceKey.is_set === true
deviceKeyInput.value = ''
serverUrlInput.value = typeof serverUrl.value === 'string' && serverUrl.value.trim()
? serverUrl.value
: DEFAULT_SERVER_URL
templateInput.value = typeof template.value === 'string' ? template.value : ''
} catch (err) {
error(parseApiError(err, '加载 Bark 推送配置失败'))
log.error('加载 Bark 推送配置失败:', err)
}
}
async function saveConfig() {
saving.value = true
try {
const updates: Array<Promise<unknown>> = [
adminApi.updateSystemConfig(
CONFIG_KEYS.server_url,
normalizeServerUrl(serverUrlInput.value),
'Bark 服务器地址'
),
adminApi.updateSystemConfig(CONFIG_KEYS.template, templateInput.value, 'Bark 推送模板'),
]
const trimmedKey = deviceKeyInput.value.trim()
if (trimmedKey) {
updates.push(adminApi.updateSystemConfig(
CONFIG_KEYS.device_key,
trimmedKey,
'Bark Device Key'
))
}
await Promise.all(updates)
if (trimmedKey) {
deviceKeyIsSet.value = true
deviceKeyInput.value = ''
}
if (!canEnable.value) {
enabled.value = false
}
await modulesApi.setEnabled('bark_push', enabled.value)
success('Bark 推送配置已保存')
} catch (err) {
error(parseApiError(err, '保存 Bark 推送配置失败'))
log.error('保存 Bark 推送配置失败:', err)
} finally {
saving.value = false
}
}
async function handleTest() {
testing.value = true
try {
const result = await adminApi.testImportantNotification({ channel: 'bark' })
lastTestResult.value = result.channels || []
if (result.success) {
success(result.message || '测试通知已发送')
} else {
error(result.message || '测试通知发送失败')
}
} catch (err) {
error(parseApiError(err, '测试通知发送失败'))
log.error('测试 Bark 推送失败:', err)
} finally {
testing.value = false
}
}
function normalizeServerUrl(value: string): string {
const trimmed = value.trim().replace(/\/+$/, '')
return trimmed || DEFAULT_SERVER_URL
}
function formatChannel(channel: string): string {
if (channel === 'bark') return 'Bark'
if (channel === 'server_chan') return 'Server 酱'
if (channel === 'email') return '邮件'
if (channel === 'module') return '模块'
if (channel === 'none') return '无可用服务'
return channel
}
</script>

View File

@@ -40,6 +40,9 @@
<SelectItem value="server_chan">
Server
</SelectItem>
<SelectItem value="bark">
Bark
</SelectItem>
</SelectContent>
</Select>
</div>
@@ -60,7 +63,7 @@
</div>
</div>
<div class="grid gap-6 border-t border-border/60 pt-5 lg:grid-cols-2">
<div class="grid gap-6 border-t border-border/60 pt-5 lg:grid-cols-3">
<section class="space-y-4">
<div class="flex items-center justify-between gap-3">
<div>
@@ -130,6 +133,31 @@
配置 Server 酱推送
</RouterLink>
</section>
<section class="space-y-4">
<div class="flex items-center justify-between gap-3">
<div>
<div class="flex items-center gap-2">
<Label class="text-sm font-medium">
Bark
</Label>
<Badge :variant="barkReady ? 'success' : 'outline'">
{{ barkReady ? '可用' : '未就绪' }}
</Badge>
</div>
<p class="mt-1 text-xs text-muted-foreground">
通过 Bark iOS 设备推送通知
</p>
</div>
</div>
<RouterLink
to="/admin/modules/bark"
class="inline-flex h-11 items-center rounded-xl border border-border/60 bg-card/60 px-4 text-sm font-semibold text-foreground hover:border-primary/60 hover:bg-primary/10 hover:text-primary"
>
配置 Bark 推送
</RouterLink>
</section>
</div>
</div>
</CardSection>
@@ -231,6 +259,9 @@
<SelectItem value="server_chan">
Server
</SelectItem>
<SelectItem value="bark">
Bark
</SelectItem>
</SelectContent>
</Select>
</div>
@@ -326,6 +357,9 @@
<SelectItem value="server_chan">
Server
</SelectItem>
<SelectItem value="bark">
Bark
</SelectItem>
</SelectContent>
</Select>
<Button
@@ -382,7 +416,7 @@ import { useToast } from '@/composables/useToast'
import { parseApiError } from '@/utils/errorParser'
import { log } from '@/utils/logger'
type DeliveryChannel = 'global' | 'all' | 'email' | 'server_chan'
type DeliveryChannel = 'global' | 'all' | 'email' | 'server_chan' | 'bark'
interface NotificationItem {
local_id: string
@@ -412,6 +446,7 @@ const CONFIG_KEYS = {
default_channel: 'module.important_notification.default_channel',
items: 'module.important_notification.items',
server_chan_send_key: 'module.server_chan_push.send_key',
bark_device_key: 'module.bark_push.device_key',
} as const
const DEFAULT_ITEMS: NotificationItem[] = [
@@ -460,6 +495,8 @@ const testing = ref(false)
const smtpConfigured = ref(false)
const serverChanKeyIsSet = ref(false)
const serverChanStatus = ref<ModuleStatus | null>(null)
const barkKeyIsSet = ref(false)
const barkStatus = ref<ModuleStatus | null>(null)
const testItemKey = ref('provider_quota_alert')
const testChannel = ref<DeliveryChannel>('global')
const lastTestResult = ref<Array<{ channel: string; success: boolean; message: string }>>([])
@@ -480,6 +517,10 @@ const serverChanReady = computed(() => {
return serverChanStatus.value?.enabled === true && serverChanKeyIsSet.value
})
const barkReady = computed(() => {
return barkStatus.value?.enabled === true && barkKeyIsSet.value
})
const canEnableService = computed(() => {
if (deliveryReady(config.value.default_channel)) return true
return config.value.items.some(item => item.enabled && isItemReady(item))
@@ -499,6 +540,8 @@ async function loadConfig() {
items,
serverChanModuleStatus,
serverChanKey,
barkModuleStatus,
barkDeviceKey,
smtpHost,
smtpFromEmail,
] = await Promise.all([
@@ -509,6 +552,8 @@ async function loadConfig() {
adminApi.getSystemConfig(CONFIG_KEYS.items),
modulesApi.getStatus('server_chan_push'),
adminApi.getSystemConfig(CONFIG_KEYS.server_chan_send_key),
modulesApi.getStatus('bark_push'),
adminApi.getSystemConfig(CONFIG_KEYS.bark_device_key),
adminApi.getSystemConfig('smtp_host'),
adminApi.getSystemConfig('smtp_from_email'),
])
@@ -520,6 +565,8 @@ async function loadConfig() {
config.value.items = normalizeItems(items.value)
serverChanStatus.value = serverChanModuleStatus
serverChanKeyIsSet.value = serverChanKey.is_set === true
barkStatus.value = barkModuleStatus
barkKeyIsSet.value = barkDeviceKey.is_set === true
smtpConfigured.value = isNonEmptyString(smtpHost.value) && isNonEmptyString(smtpFromEmail.value)
if (!config.value.items.some(item => item.key === testItemKey.value)) {
testItemKey.value = config.value.items[0]?.key || ''
@@ -604,9 +651,10 @@ function isItemReady(item: NotificationItem): boolean {
}
function deliveryReady(channel: Exclude<DeliveryChannel, 'global'>): boolean {
if (channel === 'all') return emailReady.value || serverChanReady.value
if (channel === 'all') return emailReady.value || serverChanReady.value || barkReady.value
if (channel === 'email') return emailReady.value
if (channel === 'server_chan') return serverChanReady.value
if (channel === 'bark') return barkReady.value
return false
}
@@ -661,12 +709,12 @@ function normalizeItemKey(value: unknown): string {
}
function normalizeItemChannel(value: unknown): DeliveryChannel {
if (value === 'all' || value === 'email' || value === 'server_chan') return value
if (value === 'all' || value === 'email' || value === 'server_chan' || value === 'bark') return value
return 'global'
}
function normalizeDefaultChannel(value: unknown): Exclude<DeliveryChannel, 'global'> {
if (value === 'email' || value === 'server_chan') return value
if (value === 'email' || value === 'server_chan' || value === 'bark') return value
return 'all'
}
@@ -691,6 +739,7 @@ function normalizeRecipients(value: unknown): string {
function formatChannel(channel: string): string {
if (channel === 'email') return '邮件'
if (channel === 'server_chan') return 'Server 酱'
if (channel === 'bark') return 'Bark'
if (channel === 'user_email') return '用户邮件'
if (channel === 'module') return '模块'
if (channel === 'item') return '通知项'