feat(wechat): add WeCom and webhook notifications (#7086)

Panel alerts and the scheduled status report could go to Telegram, Discord or email, but not to a WeCom group robot or a generic webhook.

Add a WeChat channel, off by default, with two modes: a WeCom group robot, or a webhook that receives a small signed-free JSON envelope with an optional bearer token. It carries the same events as the other channels (logins, CPU and memory, Xray crash, node and outbound state) and a scheduled text report. Delivery goes through the SSRF-guarded dialer, follows no redirects, and the URL and token are stored and redacted like the other notification secrets.
This commit is contained in:
17
2026-11-24 10:24:39 -08:00
committed by GitHub
parent d15b72a11a
commit 3cb5bb7187
59 changed files with 3976 additions and 68 deletions
@@ -8,6 +8,7 @@
"backup-restore",
"telegram-bot",
"discord-bot",
"wechat-notifications",
"security"
]
}
@@ -0,0 +1,62 @@
---
title: WeChat Notifications
description: Receive event alerts and scheduled reports through a WeCom group robot or a compatible WeChat webhook gateway.
icon: MessageCircle
---
WeChat is an independent, optional text-notification channel. It supports event alerts and scheduled status reports, with its own language, event selection, and CPU/memory thresholds. Existing notification channels retain their settings. WeChat notifications are disabled by default.
WeCom mode sends to an enterprise group robot. Personal WeChat requires a separately deployed bridge that implements the custom gateway protocol and has its own working WeChat connection. The panel does not include that bridge or provide a direct personal WeChat bot login.
## Setup
1. Open **Panel Settings → WeChat** and enable notifications.
2. Choose a delivery mode:
- **WeCom group robot**: add a message-push robot to your enterprise WeChat group and paste its HTTPS webhook URL. See the [official configuration guide](https://developer.work.weixin.qq.com/document/path/99110).
- **Custom webhook gateway**: enter your HTTPS receiver URL and, optionally, a Bearer token that the receiver verifies. A compatible gateway delivers messages to personal WeChat. This uses the protocol below; an arbitrary third-party push URL or a WeChat contact name is not a receiver.
3. Select the notification language. It is independent of the Telegram bot language.
4. Under **Notifications**, choose events and thresholds. A metric threshold of `0` disables that metric's alerts.
5. Optionally enable scheduled reports and choose a cron schedule. `@daily` uses the panel scheduler's time zone.
6. **Save**, then click **Send test notification**. The test uses saved settings and is disabled while the channel is off or any settings have unsaved changes.
URLs can contain robot credentials, so both the URL and token are redacted when settings are loaded. Leaving a secret blank retains its saved value; **Clear** followed by **Save** removes it. Disable the channel before clearing a required destination. Saving also updates report schedules and metric sampling without restarting the panel.
![WeChat notification settings with a saved custom gateway and redacted credentials](/images/wechat-settings.png)
## Alerts and reports
Event keys are `login.attempt`, `cpu.high`, `memory.high`, `xray.crash`, `node.down`, `node.up`, `outbound.down`, and `outbound.up`. The initial selection is login attempts and high CPU usage. Login notifications include the attempted username, client IP, outcome, and available failure reason, but not the password.
Repeated alerts for one event and source are limited to one successful send per minute. Failed and successful login outcomes have separate limits. A failed delivery does not consume the successful-send cooldown.
Reports summarize the host, panel and Xray versions, CPU, memory, disk, uptime, and inbound/client counts, including disabled, expired, and depleted entries. Reports also run when Xray is stopped. This channel has no remote commands or file-backup feature, and does not include subscription links or client configuration files in reports.
Traffic totals cover client statistics managed by this panel, deduplicated by client email. Used traffic is upload plus download. Remaining traffic sums each client's non-negative quota balance; when a runtime quota is unset, the client's configured quota is used. If there are no client statistics or any client has no configured quota, the remaining total reads **Quota not configured**. These values do not represent a VPS provider's billing allowance or traffic outside 3x-ui.
## Custom gateway protocol, version 1
The panel sends an HTTPS `POST` with `Content-Type: application/json` and, when configured, `Authorization: Bearer <your-token>`:
```json
{
"version": 1,
"id": "8f793626-a0e0-4a28-bddf-84c077a1bd21",
"type": "event",
"event": "cpu.high",
"hostname": "my-server",
"occurred_at": "2026-11-04T12:00:00Z",
"text": "3x-ui · my-server\nHigh CPU usage: 92.00%; threshold: 80%"
}
```
`type` is `event`, `report`, or `test`. For events, `event` is a selected event key; reports and tests use `report` and `test`. `occurred_at` preserves the event's occurrence time, falling back to send time only when no event time is available. `text` is plain UTF-8 text, at most 20,480 bytes.
The receiver should verify authentication and version, durably enqueue with a uniqueness constraint on `id`, and return `2xx` after accepting responsibility for delivery. This acknowledges the gateway's receipt, not necessarily delivery to the final WeChat user. The receiver handles final delivery and further retries.
Connection failures and `5xx` receive at most one retry with the **same ID and body**. Other rejected responses are not retried. Deduplicate by ID to handle lost acknowledgements. Each request has a 10-second timeout, responses are limited to 4 KiB, and redirects are refused. This contract has no dependency on a particular gateway service.
## WeCom and network requirements
WeCom mode requires the official `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...` endpoint and a successful `errcode: 0` response. Long text is split at UTF-8 boundaries into at most ten messages of 2,048 bytes, spaced at least 3.1 seconds apart. Requests are not automatically retried because the robot API has no ID-based deduplication for this channel.
Both modes use direct outbound HTTPS with certificate verification, independent of the panel outbound proxy. Custom receivers must resolve to public addresses. Private, loopback, link-local, and metadata-service addresses are blocked again at connection time. Provide a public HTTPS receiver when the final WeChat adapter runs on a private network.
@@ -56,6 +56,11 @@ _openapi:
title: Test Discord bot connection by sending a test embed to the configured
channel.
url: '#test-discord-bot-connection-by-sending-a-test-embed-to-the-configured-channel'
- depth: 2
title: Send a text test notification using the saved WeChat destination.
Supports WeCom group robots and compatible personal WeChat webhook
gateways. Requires WeChat notifications to be enabled.
url: '#send-a-text-test-notification-using-the-saved-wechat-destination-supports-wecom-group-robots-and-compatible-personal-wechat-webhook-gateways-requires-wechat-notifications-to-be-enabled'
- depth: 2
title: Return the built-in default Xray JSON config template that ships with
this panel version.
@@ -100,6 +105,10 @@ _openapi:
- content: Test Discord bot connection by sending a test embed to the configured
channel.
id: test-discord-bot-connection-by-sending-a-test-embed-to-the-configured-channel
- content: Send a text test notification using the saved WeChat destination.
Supports WeCom group robots and compatible personal WeChat webhook
gateways. Requires WeChat notifications to be enabled.
id: send-a-text-test-notification-using-the-saved-wechat-destination-supports-wecom-group-robots-and-compatible-personal-wechat-webhook-gateways-requires-wechat-notifications-to-be-enabled
- content: Return the built-in default Xray JSON config template that ships with
this panel version.
id: return-the-built-in-default-xray-json-config-template-that-ships-with-this-panel-version
@@ -113,7 +122,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/setting/all","method":"post"},{"path":"/panel/api/setting/defaultSettings","method":"post"},{"path":"/panel/api/setting/factoryDefaults","method":"post"},{"path":"/panel/api/setting/update","method":"post"},{"path":"/panel/api/setting/validateRegex","method":"post"},{"path":"/panel/api/setting/updateUser","method":"post"},{"path":"/panel/api/setting/restartPanel","method":"post"},{"path":"/panel/api/setting/testSmtp","method":"post"},{"path":"/panel/api/setting/testTgBot","method":"post"},{"path":"/panel/api/setting/tgBotCapabilities","method":"post"},{"path":"/panel/api/setting/testDiscord","method":"post"},{"path":"/panel/api/setting/getDefaultJsonConfig","method":"get"}]} showTitle />
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/setting/all","method":"post"},{"path":"/panel/api/setting/defaultSettings","method":"post"},{"path":"/panel/api/setting/factoryDefaults","method":"post"},{"path":"/panel/api/setting/update","method":"post"},{"path":"/panel/api/setting/validateRegex","method":"post"},{"path":"/panel/api/setting/updateUser","method":"post"},{"path":"/panel/api/setting/restartPanel","method":"post"},{"path":"/panel/api/setting/testSmtp","method":"post"},{"path":"/panel/api/setting/testTgBot","method":"post"},{"path":"/panel/api/setting/tgBotCapabilities","method":"post"},{"path":"/panel/api/setting/testDiscord","method":"post"},{"path":"/panel/api/setting/testWechat","method":"post"},{"path":"/panel/api/setting/getDefaultJsonConfig","method":"get"}]} showTitle />
</>
);
}
@@ -8,6 +8,7 @@
"backup-restore",
"telegram-bot",
"discord-bot",
"wechat-notifications",
"security"
]
}
@@ -0,0 +1,60 @@
---
title: 微信通知
description: 通过企业微信群机器人或兼容的个人微信网关接收面板告警和定时状态报告。
icon: MessageCircle
---
微信是独立、默认关闭的文字通知通道,可与 Telegram、Discord、邮件同时使用。它有自己的语言、事件选择、CPU 和内存阈值,以及独立的定时报告计划。
企业微信模式向企业微信群机器人发送消息。个人微信需要另外部署兼容下文协议的桥接服务,并由该服务维护可用的微信连接。面板不包含这个桥接服务,也不提供直接登录个人微信机器人的入口。
## 配置
1. 打开 **面板设置 → 微信**,启用通知。
2. 选择发送方式。
- **企业微信群机器人**:在企业微信群中添加消息推送机器人,填写其 HTTPS Webhook 地址。见[企业微信官方说明](https://developer.work.weixin.qq.com/document/path/99110)。
- **自定义 Webhook 网关**:填写自己实现的兼容 HTTPS 接口,按需配置接收端校验的 Bearer Token,再由该服务向个人微信投递。接口必须实现下文协议,微信联系人或任意第三方推送 URL 不能直接作为接收端。
3. 选择通知语言,该设置独立于 Telegram 机器人语言。
4. 在 **通知** 中选择事件和指标阈值。阈值为 `0` 时关闭对应指标告警。
5. 按需启用定时报告并设置计划。`@daily` 使用面板调度器的时区。
6. 先 **保存**,再 **发送测试通知**。测试使用已保存的配置;通道关闭或存在未保存的设置修改时,测试按钮不可用。
地址可能包含机器人密钥,因此地址和 Token 均在返回浏览器时隐藏。留空保留原值,点击 **清空** 后保存才会删除。清除必填地址前应先关闭通知。保存后会更新报告计划和指标采样任务,无需重启面板。
![已保存自定义网关、隐藏凭据的微信通知设置页面](/images/wechat-settings.png)
## 内容和频率
可选事件包括登录尝试、CPU 和内存超阈值、Xray 崩溃、节点离线与恢复、出站不可达与恢复。默认选择登录尝试和 CPU 告警。登录通知包含尝试的用户名、来源 IP、结果和可用的失败原因,不包含密码。
同类事件和来源每分钟最多成功发送一次;同一来源的登录失败和成功分别限频。发送失败不占用成功发送的冷却时间。
报告汇总主机、面板和 Xray 版本、CPU、内存、磁盘、运行时间,以及入站和客户端的总数、禁用、过期、流量耗尽数量。Xray 停止时仍能报告状态。此通道不提供远程命令或文件备份,报告不包含订阅链接和客户端配置文件。
流量只汇总本面板管理的客户端统计,按客户端邮箱去重。已用流量为上传与下载之和;剩余流量为每个客户端额度扣除已用量后的非负余额之和,运行统计中未设置额度时回退到客户端配置的额度。没有客户端统计,或任意客户端未配置额度时,剩余流量显示 **未配置额度**。这不是 VPS 服务商的计费额度,也不包含绕过 3x-ui 的流量。
## 自定义网关协议
HTTPS `POST`,`Content-Type: application/json`。配置 Token 时发送 `Authorization: Bearer <token>`。
```json
{
"version": 1,
"id": "8f793626-a0e0-4a28-bddf-84c077a1bd21",
"type": "event",
"event": "cpu.high",
"hostname": "my-server",
"occurred_at": "2026-11-04T12:00:00Z",
"text": "3x-ui · my-server\nCPU 使用率:92.00%;阈值:80%"
}
```
`type` 为 `event`、`report` 或 `test`。事件键为 `login.attempt`、`cpu.high`、`memory.high`、`xray.crash`、`node.down`、`node.up`、`outbound.down`、`outbound.up`;报告和测试分别使用 `report`、`test`。`occurred_at` 保留事件发生的 UTC 时间,缺失时才使用发送时间。正文最多 20,480 个 UTF-8 字节。
接收端应校验认证和版本,以 `id` 为唯一键可靠入队,再返回 `2xx`。这代表网关接受投递责任,最终微信消息的发送及重试由网关负责。
连接失败或 `5xx` 时,面板最多重试一次,沿用相同 ID 和正文;其他失败响应不重试。接收端应按 ID 去重,避免响应丢失造成重复消息。每次请求超时 10 秒,响应最多 4 KiB,不跟随重定向。协议不依赖特定的网关服务。
企业微信模式只接受官方机器人 HTTPS 地址,并要求响应 `errcode: 0`。长消息按 UTF-8 字节边界拆分,每段最多 2,048 字节、最多十段,发送间隔至少 3.1 秒。该接口不能按本通道的 ID 去重,因此不自动重试。
两种方式均直接通过 HTTPS 连接、校验证书,不继承面板出站代理。自定义地址必须指向公网,实际连接时再次阻止回环、私网、链路本地和元数据服务地址。微信适配器位于内网时,应提供公开的 HTTPS 接收网关。
Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

+128 -2
View File
@@ -646,6 +646,40 @@
"maximum": 65535,
"minimum": 1,
"type": "integer"
},
"wechatCpu": {
"maximum": 100,
"minimum": 0,
"type": "integer"
},
"wechatEnable": {
"type": "boolean"
},
"wechatEnabledEvents": {
"type": "string"
},
"wechatLang": {
"type": "string"
},
"wechatMemory": {
"maximum": 100,
"minimum": 0,
"type": "integer"
},
"wechatMode": {
"type": "string"
},
"wechatReportEnable": {
"type": "boolean"
},
"wechatRunTime": {
"type": "string"
},
"wechatToken": {
"type": "string"
},
"wechatWebhookURL": {
"type": "string"
}
},
"required": [
@@ -837,7 +871,17 @@
"webDomain",
"webKeyFile",
"webListen",
"webPort"
"webPort",
"wechatCpu",
"wechatEnable",
"wechatEnabledEvents",
"wechatLang",
"wechatMemory",
"wechatMode",
"wechatReportEnable",
"wechatRunTime",
"wechatToken",
"wechatWebhookURL"
],
"type": "object"
},
@@ -920,6 +964,12 @@
"hasWarpSecret": {
"type": "boolean"
},
"hasWechatToken": {
"type": "boolean"
},
"hasWechatWebhookURL": {
"type": "boolean"
},
"ipLimitAllowlist": {
"type": "string"
},
@@ -1485,6 +1535,40 @@
"maximum": 65535,
"minimum": 1,
"type": "integer"
},
"wechatCpu": {
"maximum": 100,
"minimum": 0,
"type": "integer"
},
"wechatEnable": {
"type": "boolean"
},
"wechatEnabledEvents": {
"type": "string"
},
"wechatLang": {
"type": "string"
},
"wechatMemory": {
"maximum": 100,
"minimum": 0,
"type": "integer"
},
"wechatMode": {
"type": "string"
},
"wechatReportEnable": {
"type": "boolean"
},
"wechatRunTime": {
"type": "string"
},
"wechatToken": {
"type": "string"
},
"wechatWebhookURL": {
"type": "string"
}
},
"required": [
@@ -1512,6 +1596,8 @@
"hasTgBotToken",
"hasTwoFactorToken",
"hasWarpSecret",
"hasWechatToken",
"hasWechatWebhookURL",
"ipLimitAllowlist",
"ldapAutoCreate",
"ldapAutoDelete",
@@ -1684,7 +1770,17 @@
"webDomain",
"webKeyFile",
"webListen",
"webPort"
"webPort",
"wechatCpu",
"wechatEnable",
"wechatEnabledEvents",
"wechatLang",
"wechatMemory",
"wechatMode",
"wechatReportEnable",
"wechatRunTime",
"wechatToken",
"wechatWebhookURL"
],
"type": "object"
},
@@ -14414,6 +14510,36 @@
}
}
},
"/panel/api/setting/testWechat": {
"post": {
"tags": [
"Settings"
],
"summary": "Send a text test notification using the saved WeChat destination. Supports WeCom group robots and compatible personal WeChat webhook gateways. Requires WeChat notifications to be enabled.",
"operationId": "post_panel_api_setting_testWechat",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {}
}
}
}
}
}
}
}
},
"/panel/api/setting/getDefaultJsonConfig": {
"get": {
"tags": [
+128 -2
View File
@@ -646,6 +646,40 @@
"maximum": 65535,
"minimum": 1,
"type": "integer"
},
"wechatCpu": {
"maximum": 100,
"minimum": 0,
"type": "integer"
},
"wechatEnable": {
"type": "boolean"
},
"wechatEnabledEvents": {
"type": "string"
},
"wechatLang": {
"type": "string"
},
"wechatMemory": {
"maximum": 100,
"minimum": 0,
"type": "integer"
},
"wechatMode": {
"type": "string"
},
"wechatReportEnable": {
"type": "boolean"
},
"wechatRunTime": {
"type": "string"
},
"wechatToken": {
"type": "string"
},
"wechatWebhookURL": {
"type": "string"
}
},
"required": [
@@ -837,7 +871,17 @@
"webDomain",
"webKeyFile",
"webListen",
"webPort"
"webPort",
"wechatCpu",
"wechatEnable",
"wechatEnabledEvents",
"wechatLang",
"wechatMemory",
"wechatMode",
"wechatReportEnable",
"wechatRunTime",
"wechatToken",
"wechatWebhookURL"
],
"type": "object"
},
@@ -920,6 +964,12 @@
"hasWarpSecret": {
"type": "boolean"
},
"hasWechatToken": {
"type": "boolean"
},
"hasWechatWebhookURL": {
"type": "boolean"
},
"ipLimitAllowlist": {
"type": "string"
},
@@ -1485,6 +1535,40 @@
"maximum": 65535,
"minimum": 1,
"type": "integer"
},
"wechatCpu": {
"maximum": 100,
"minimum": 0,
"type": "integer"
},
"wechatEnable": {
"type": "boolean"
},
"wechatEnabledEvents": {
"type": "string"
},
"wechatLang": {
"type": "string"
},
"wechatMemory": {
"maximum": 100,
"minimum": 0,
"type": "integer"
},
"wechatMode": {
"type": "string"
},
"wechatReportEnable": {
"type": "boolean"
},
"wechatRunTime": {
"type": "string"
},
"wechatToken": {
"type": "string"
},
"wechatWebhookURL": {
"type": "string"
}
},
"required": [
@@ -1512,6 +1596,8 @@
"hasTgBotToken",
"hasTwoFactorToken",
"hasWarpSecret",
"hasWechatToken",
"hasWechatWebhookURL",
"ipLimitAllowlist",
"ldapAutoCreate",
"ldapAutoDelete",
@@ -1684,7 +1770,17 @@
"webDomain",
"webKeyFile",
"webListen",
"webPort"
"webPort",
"wechatCpu",
"wechatEnable",
"wechatEnabledEvents",
"wechatLang",
"wechatMemory",
"wechatMode",
"wechatReportEnable",
"wechatRunTime",
"wechatToken",
"wechatWebhookURL"
],
"type": "object"
},
@@ -14414,6 +14510,36 @@
}
}
},
"/panel/api/setting/testWechat": {
"post": {
"tags": [
"Settings"
],
"summary": "Send a text test notification using the saved WeChat destination. Supports WeCom group robots and compatible personal WeChat webhook gateways. Requires WeChat notifications to be enabled.",
"operationId": "post_panel_api_setting_testWechat",
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"msg": {
"type": "string"
},
"obj": {}
}
}
}
}
}
}
}
},
"/panel/api/setting/getDefaultJsonConfig": {
"get": {
"tags": [
@@ -0,0 +1,96 @@
import { useState } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { AllSetting } from '@/models/setting';
import { WechatNotifications } from './WechatNotifications';
const meta = {
title: 'UI/Notifications/WechatNotifications',
component: WechatNotifications,
tags: ['autodocs'],
parameters: {
layout: 'padded',
docs: {
description: {
component:
'Grid of grouped event checkboxes on the settings page that picks which panel events (outbound/node health, Xray crashes, CPU/RAM thresholds, login attempts) trigger a WeChat notification, stored as a comma-separated list in wechatEnabledEvents.',
},
},
},
argTypes: {
allSetting: {
description:
'Panel settings snapshot; wechatEnabledEvents holds the selected event keys and wechatCpu/wechatMemory the alert threshold percentages.',
},
updateSetting: {
description:
'Receives a partial settings patch when an event is toggled or a threshold input changes.',
},
},
} satisfies Meta<typeof WechatNotifications>;
export default meta;
type Story = StoryObj<typeof meta>;
function StatefulDemo({ initial }: { initial: AllSetting }) {
const [settings, setSettings] = useState(initial);
return (
<WechatNotifications
allSetting={settings}
updateSetting={(patch) => setSettings((prev) => new AllSetting({ ...prev, ...patch }))}
/>
);
}
const placeholderArgs = {
allSetting: new AllSetting(),
updateSetting: () => undefined,
};
export const NothingSelected: Story = {
args: placeholderArgs,
render: () => <StatefulDemo initial={new AllSetting({ wechatEnabledEvents: '' })} />,
};
export const SystemThresholdAlerts: Story = {
args: placeholderArgs,
render: () => (
<StatefulDemo
initial={
new AllSetting({
wechatEnabledEvents: 'cpu.high,memory.high',
wechatCpu: 85,
wechatMemory: 90,
})
}
/>
),
};
export const InfrastructureOnly: Story = {
args: placeholderArgs,
render: () => (
<StatefulDemo
initial={
new AllSetting({ wechatEnabledEvents: 'outbound.down,node.down,node.up,xray.crash' })
}
/>
),
};
export const AllEventsEnabled: Story = {
args: placeholderArgs,
render: () => (
<StatefulDemo
initial={
new AllSetting({
wechatEnabledEvents:
'outbound.down,outbound.up,xray.crash,node.down,node.up,cpu.high,memory.high,login.attempt',
wechatCpu: 80,
wechatMemory: 80,
})
}
/>
),
};
@@ -0,0 +1,160 @@
import { InputNumber } from 'antd';
import {
CloudServerOutlined,
ThunderboltOutlined,
DesktopOutlined,
DashboardOutlined,
SafetyOutlined,
} from '@ant-design/icons';
import type { AllSetting } from '@/models/setting';
import { onNumber } from '@/utils/onNumber';
import { NotificationLayout } from './NotificationLayout';
import { NotificationGroup } from './NotificationGroup';
import type { NotificationGroupConfig } from './types';
const GROUPS: NotificationGroupConfig[] = [
{
icon: <CloudServerOutlined aria-hidden />,
title: 'eventGroupOutbound',
events: [
{
key: 'outbound.down',
label: 'eventOutboundDown',
settingKey: 'outboundDownThreshold',
hint: 'eventDownThresholdHint',
extra: ({ value, onChange, ariaLabel }) => (
<InputNumber
size="small"
min={1}
max={100}
precision={0}
value={value}
onChange={onNumber((next) => onChange(Math.round(next)))}
aria-label={ariaLabel}
style={{ width: 80 }}
/>
),
},
{ key: 'outbound.up', label: 'eventOutboundUp', settingKey: '' },
],
},
{
icon: <ThunderboltOutlined aria-hidden />,
title: 'eventGroupXray',
events: [{ key: 'xray.crash', label: 'eventXrayCrash', settingKey: '' }],
},
{
icon: <DesktopOutlined aria-hidden />,
title: 'eventGroupNode',
events: [
{
key: 'node.down',
label: 'eventNodeDown',
settingKey: 'nodeDownThreshold',
hint: 'eventDownThresholdHint',
extra: ({ value, onChange, ariaLabel }) => (
<InputNumber
size="small"
min={1}
max={100}
precision={0}
value={value}
onChange={onNumber((next) => onChange(Math.round(next)))}
aria-label={ariaLabel}
style={{ width: 80 }}
/>
),
},
{ key: 'node.up', label: 'eventNodeUp', settingKey: '' },
],
},
{
icon: <DashboardOutlined aria-hidden />,
title: 'eventGroupSystem',
events: [
{
key: 'cpu.high',
label: 'eventCPUHigh',
settingKey: 'wechatCpu',
extra: ({ value, onChange, ariaLabel }) => (
<InputNumber
size="small"
min={0}
max={100}
precision={0}
value={value}
onChange={onNumber((next) => onChange(Math.round(next)))}
aria-label={ariaLabel}
style={{ width: 80 }}
/>
),
},
{
key: 'memory.high',
label: 'eventMemoryHigh',
settingKey: 'wechatMemory',
extra: ({ value, onChange, ariaLabel }) => (
<InputNumber
size="small"
min={0}
max={100}
precision={0}
value={value}
onChange={onNumber((next) => onChange(Math.round(next)))}
aria-label={ariaLabel}
style={{ width: 80 }}
/>
),
},
],
},
{
icon: <SafetyOutlined aria-hidden />,
title: 'eventGroupSecurity',
events: [{ key: 'login.attempt', label: 'eventLoginAttempt', settingKey: '' }],
},
];
interface Props {
allSetting: AllSetting;
updateSetting: (patch: Partial<AllSetting>) => void;
}
export function WechatNotifications({ allSetting, updateSetting }: Props) {
const events = allSetting.wechatEnabledEvents || '';
const selected = events
? events
.split(',')
.map((s) => s.trim())
.filter(Boolean)
: [];
function toggle(key: string) {
const next = selected.includes(key) ? selected.filter((e) => e !== key) : [...selected, key];
updateSetting({ wechatEnabledEvents: next.join(',') });
}
function toggleAll(keys: string[]) {
const allSelected = keys.every((v) => selected.includes(v));
const next = allSelected
? selected.filter((v) => !keys.includes(v))
: [...new Set([...selected, ...keys])];
updateSetting({ wechatEnabledEvents: next.join(',') });
}
return (
<NotificationLayout>
{GROUPS.map((group, i) => (
<NotificationGroup
key={i}
config={group}
selected={selected}
onToggle={toggle}
onToggleAll={toggleAll}
allSetting={allSetting}
updateSetting={updateSetting}
/>
))}
</NotificationLayout>
);
}
+24 -2
View File
@@ -189,7 +189,17 @@ export const EXAMPLES: Record<string, unknown> = {
"webDomain": "",
"webKeyFile": "",
"webListen": "",
"webPort": 1
"webPort": 1,
"wechatCpu": 0,
"wechatEnable": false,
"wechatEnabledEvents": "",
"wechatLang": "",
"wechatMemory": 0,
"wechatMode": "",
"wechatReportEnable": false,
"wechatRunTime": "",
"wechatToken": "",
"wechatWebhookURL": ""
},
"AllSettingView": {
"datepicker": "",
@@ -216,6 +226,8 @@ export const EXAMPLES: Record<string, unknown> = {
"hasTgBotToken": false,
"hasTwoFactorToken": false,
"hasWarpSecret": false,
"hasWechatToken": false,
"hasWechatWebhookURL": false,
"ipLimitAllowlist": "",
"ldapAutoCreate": false,
"ldapAutoDelete": false,
@@ -388,7 +400,17 @@ export const EXAMPLES: Record<string, unknown> = {
"webDomain": "",
"webKeyFile": "",
"webListen": "",
"webPort": 1
"webPort": 1,
"wechatCpu": 0,
"wechatEnable": false,
"wechatEnabledEvents": "",
"wechatLang": "",
"wechatMemory": 0,
"wechatMode": "",
"wechatReportEnable": false,
"wechatRunTime": "",
"wechatToken": "",
"wechatWebhookURL": ""
},
"AmneziaWGLogs": {
"events": [
+98 -2
View File
@@ -620,6 +620,40 @@ export const SCHEMAS: Record<string, unknown> = {
"maximum": 65535,
"minimum": 1,
"type": "integer"
},
"wechatCpu": {
"maximum": 100,
"minimum": 0,
"type": "integer"
},
"wechatEnable": {
"type": "boolean"
},
"wechatEnabledEvents": {
"type": "string"
},
"wechatLang": {
"type": "string"
},
"wechatMemory": {
"maximum": 100,
"minimum": 0,
"type": "integer"
},
"wechatMode": {
"type": "string"
},
"wechatReportEnable": {
"type": "boolean"
},
"wechatRunTime": {
"type": "string"
},
"wechatToken": {
"type": "string"
},
"wechatWebhookURL": {
"type": "string"
}
},
"required": [
@@ -811,7 +845,17 @@ export const SCHEMAS: Record<string, unknown> = {
"webDomain",
"webKeyFile",
"webListen",
"webPort"
"webPort",
"wechatCpu",
"wechatEnable",
"wechatEnabledEvents",
"wechatLang",
"wechatMemory",
"wechatMode",
"wechatReportEnable",
"wechatRunTime",
"wechatToken",
"wechatWebhookURL"
],
"type": "object"
},
@@ -894,6 +938,12 @@ export const SCHEMAS: Record<string, unknown> = {
"hasWarpSecret": {
"type": "boolean"
},
"hasWechatToken": {
"type": "boolean"
},
"hasWechatWebhookURL": {
"type": "boolean"
},
"ipLimitAllowlist": {
"type": "string"
},
@@ -1459,6 +1509,40 @@ export const SCHEMAS: Record<string, unknown> = {
"maximum": 65535,
"minimum": 1,
"type": "integer"
},
"wechatCpu": {
"maximum": 100,
"minimum": 0,
"type": "integer"
},
"wechatEnable": {
"type": "boolean"
},
"wechatEnabledEvents": {
"type": "string"
},
"wechatLang": {
"type": "string"
},
"wechatMemory": {
"maximum": 100,
"minimum": 0,
"type": "integer"
},
"wechatMode": {
"type": "string"
},
"wechatReportEnable": {
"type": "boolean"
},
"wechatRunTime": {
"type": "string"
},
"wechatToken": {
"type": "string"
},
"wechatWebhookURL": {
"type": "string"
}
},
"required": [
@@ -1486,6 +1570,8 @@ export const SCHEMAS: Record<string, unknown> = {
"hasTgBotToken",
"hasTwoFactorToken",
"hasWarpSecret",
"hasWechatToken",
"hasWechatWebhookURL",
"ipLimitAllowlist",
"ldapAutoCreate",
"ldapAutoDelete",
@@ -1658,7 +1744,17 @@ export const SCHEMAS: Record<string, unknown> = {
"webDomain",
"webKeyFile",
"webListen",
"webPort"
"webPort",
"wechatCpu",
"wechatEnable",
"wechatEnabledEvents",
"wechatLang",
"wechatMemory",
"wechatMode",
"wechatReportEnable",
"wechatRunTime",
"wechatToken",
"wechatWebhookURL"
],
"type": "object"
},
+22
View File
@@ -195,6 +195,16 @@ export interface AllSetting {
webKeyFile: string;
webListen: string;
webPort: number;
wechatCpu: number;
wechatEnable: boolean;
wechatEnabledEvents: string;
wechatLang: string;
wechatMemory: number;
wechatMode: string;
wechatReportEnable: boolean;
wechatRunTime: string;
wechatToken: string;
wechatWebhookURL: string;
}
export interface AllSettingView {
@@ -222,6 +232,8 @@ export interface AllSettingView {
hasTgBotToken: boolean;
hasTwoFactorToken: boolean;
hasWarpSecret: boolean;
hasWechatToken: boolean;
hasWechatWebhookURL: boolean;
ipLimitAllowlist: string;
ldapAutoCreate: boolean;
ldapAutoDelete: boolean;
@@ -395,6 +407,16 @@ export interface AllSettingView {
webKeyFile: string;
webListen: string;
webPort: number;
wechatCpu: number;
wechatEnable: boolean;
wechatEnabledEvents: string;
wechatLang: string;
wechatMemory: number;
wechatMode: string;
wechatReportEnable: boolean;
wechatRunTime: string;
wechatToken: string;
wechatWebhookURL: string;
}
export interface AmneziaWGLogs {
+22
View File
@@ -205,6 +205,16 @@ export const AllSettingSchema = z.object({
webKeyFile: z.string(),
webListen: z.string(),
webPort: z.number().int().min(1).max(65535),
wechatCpu: z.number().int().min(0).max(100),
wechatEnable: z.boolean(),
wechatEnabledEvents: z.string(),
wechatLang: z.string(),
wechatMemory: z.number().int().min(0).max(100),
wechatMode: z.string(),
wechatReportEnable: z.boolean(),
wechatRunTime: z.string(),
wechatToken: z.string(),
wechatWebhookURL: z.string(),
});
export type AllSetting = z.infer<typeof AllSettingSchema>;
@@ -233,6 +243,8 @@ export const AllSettingViewSchema = z.object({
hasTgBotToken: z.boolean(),
hasTwoFactorToken: z.boolean(),
hasWarpSecret: z.boolean(),
hasWechatToken: z.boolean(),
hasWechatWebhookURL: z.boolean(),
ipLimitAllowlist: z.string(),
ldapAutoCreate: z.boolean(),
ldapAutoDelete: z.boolean(),
@@ -406,6 +418,16 @@ export const AllSettingViewSchema = z.object({
webKeyFile: z.string(),
webListen: z.string(),
webPort: z.number().int().min(1).max(65535),
wechatCpu: z.number().int().min(0).max(100),
wechatEnable: z.boolean(),
wechatEnabledEvents: z.string(),
wechatLang: z.string(),
wechatMemory: z.number().int().min(0).max(100),
wechatMode: z.string(),
wechatReportEnable: z.boolean(),
wechatRunTime: z.string(),
wechatToken: z.string(),
wechatWebhookURL: z.string(),
});
export type AllSettingView = z.infer<typeof AllSettingViewSchema>;
+6
View File
@@ -28,6 +28,7 @@ import {
SettingOutlined,
SunOutlined,
TelegramFilled,
WechatOutlined,
} from '@ant-design/icons';
import { HttpUtil } from '@/utils';
@@ -237,6 +238,11 @@ export default function AppSidebar() {
icon: <DiscordOutlined aria-hidden />,
label: t('pages.settings.discordSettings'),
},
{
key: '/settings#wechat',
icon: <WechatOutlined aria-hidden />,
label: t('pages.settings.wechatSettings'),
},
{
key: '/settings#subscription',
icon: <CloudServerOutlined aria-hidden />,
+20 -1
View File
@@ -1,5 +1,10 @@
import { ObjectUtil } from '@/utils';
import type { SubProfileMode, SubHostSortMode, NetworkTrafficMode } from '@/schemas/setting';
import type {
SubProfileMode,
SubHostSortMode,
NetworkTrafficMode,
WechatMode,
} from '@/schemas/setting';
export class AllSetting {
webListen = '';
@@ -207,6 +212,20 @@ export class AllSetting {
discordEnabledEvents = 'login.attempt,cpu.high';
hasDiscordBotToken = false;
clearDiscordBotToken = false;
wechatEnable = false;
wechatMode: WechatMode = 'wecom';
wechatWebhookURL = '';
hasWechatWebhookURL = false;
clearWechatWebhookURL = false;
wechatToken = '';
hasWechatToken = false;
clearWechatToken = false;
wechatLang = 'en-US';
wechatReportEnable = false;
wechatRunTime = '@daily';
wechatEnabledEvents = 'login.attempt,cpu.high';
wechatCpu = 80;
wechatMemory = 80;
constructor(data?: unknown) {
if (data != null) {
+6
View File
@@ -2161,6 +2161,12 @@ export const sections: readonly Section[] = [
summary: 'Test Discord bot connection by sending a test embed to the configured channel.',
response: '{\n "success": true,\n "msg": "Test notification sent successfully"\n}',
},
{
method: 'POST',
path: '/panel/api/setting/testWechat',
summary:
'Send a text test notification using the saved WeChat destination. Supports WeCom group robots and compatible personal WeChat webhook gateways. Requires WeChat notifications to be enabled.',
},
{
method: 'GET',
path: '/panel/api/setting/getDefaultJsonConfig',
+11 -1
View File
@@ -28,6 +28,7 @@ import SecurityTab from './SecurityTab';
import TelegramTab from './TelegramTab';
import EmailTab from './EmailTab';
import DiscordTab from './DiscordTab';
import WechatTab from './WechatTab';
import SubscriptionGeneralTab from './SubscriptionGeneralTab';
import SubscriptionFormatsTab from './SubscriptionFormatsTab';
import SubscriptionBalancersTab from './SubscriptionBalancersTab';
@@ -43,6 +44,7 @@ const tabSlugs = [
'telegram',
'email',
'discord',
'wechat',
'subscription',
'subscription-formats',
'subscription-balancers',
@@ -221,6 +223,14 @@ export default function SettingsPage() {
return <EmailTab allSetting={allSetting} updateSetting={updateSetting} />;
case 'discord':
return <DiscordTab allSetting={allSetting} updateSetting={updateSetting} />;
case 'wechat':
return (
<WechatTab
allSetting={allSetting}
updateSetting={updateSetting}
hasPendingChanges={!saveDisabled}
/>
);
case 'subscription':
return <SubscriptionGeneralTab allSetting={allSetting} updateSetting={updateSetting} />;
case 'subscription-formats':
@@ -230,7 +240,7 @@ export default function SettingsPage() {
default:
return <GeneralTab allSetting={allSetting} updateSetting={updateSetting} />;
}
}, [activeSlug, allSetting, updateSetting, savePayload]);
}, [activeSlug, allSetting, updateSetting, savePayload, saveDisabled]);
return (
<ConfigProvider theme={antdThemeConfig}>
@@ -0,0 +1,62 @@
import { useState } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { AllSetting } from '@/models/setting';
import WechatTab from './WechatTab';
const meta = {
title: 'Pages/Settings/WechatTab',
component: WechatTab,
tags: ['autodocs'],
parameters: { layout: 'padded' },
} satisfies Meta<typeof WechatTab>;
export default meta;
type Story = StoryObj<typeof meta>;
function SettingsPreview({ initial }: { initial: AllSetting }) {
const [setting, setSetting] = useState(initial);
return (
<WechatTab
allSetting={setting}
hasPendingChanges={!setting.equals(initial)}
updateSetting={(patch) => setSetting((current) => new AllSetting({ ...current, ...patch }))}
/>
);
}
const placeholderArgs = { allSetting: new AllSetting(), updateSetting: () => undefined };
export const WecomRobot: Story = {
args: placeholderArgs,
render: () => <SettingsPreview initial={new AllSetting()} />,
};
export const SavedCustomGateway: Story = {
args: placeholderArgs,
render: () => (
<SettingsPreview
initial={
new AllSetting({
wechatEnable: true,
wechatMode: 'webhook',
hasWechatWebhookURL: true,
hasWechatToken: true,
wechatReportEnable: true,
})
}
/>
),
};
export const UnsavedChanges: Story = {
args: {
allSetting: new AllSetting({
wechatEnable: true,
wechatMode: 'webhook',
wechatWebhookURL: 'https://receiver.example/notify',
}),
updateSetting: () => undefined,
hasPendingChanges: true,
},
};
+235
View File
@@ -0,0 +1,235 @@
import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Alert,
Button,
ConfigProvider,
Select,
Space,
Switch,
Tabs,
Typography,
theme,
} from 'antd';
import { BellOutlined, SendOutlined, SettingOutlined } from '@ant-design/icons';
import { HttpUtil, LanguageManager } from '@/utils';
import type { AllSetting } from '@/models/setting';
import type { WechatMode } from '@/schemas/setting';
import { SettingListItem } from '@/components/ui';
import { WechatNotifications } from '@/components/ui/notifications/WechatNotifications';
import { useMediaQuery } from '@/hooks/useMediaQuery';
import { catTabLabel } from './catTabLabel';
import { NotifyTimeField } from './NotifyTimeField';
import SecretInput from './SecretInput';
interface WechatTabProps {
allSetting: AllSetting;
updateSetting: (patch: Partial<AllSetting>) => void;
hasPendingChanges?: boolean;
}
export default function WechatTab({
allSetting,
updateSetting,
hasPendingChanges = false,
}: WechatTabProps) {
const { t } = useTranslation();
const { token } = theme.useToken();
const { isMobile } = useMediaQuery();
const [testing, setTesting] = useState(false);
const [testResult, setTestResult] = useState<{ success: boolean; msg: string } | null>(null);
const languageOptions = useMemo(
() =>
LanguageManager.supportedLanguages.map((lang) => ({
value: lang.value,
label: `${lang.icon} ${lang.name}`,
})),
[],
);
async function testWechat() {
setTesting(true);
setTestResult(null);
try {
const result = await HttpUtil.post('/panel/api/setting/testWechat', undefined, {
silent: true,
});
setTestResult({
success: !!result.success,
msg:
result.msg ||
t(result.success ? 'pages.settings.wechatTestSuccess' : 'pages.settings.requestFailed'),
});
} catch (error: unknown) {
setTestResult({
success: false,
msg: error instanceof Error ? error.message : t('pages.settings.requestFailed'),
});
} finally {
setTesting(false);
}
}
return (
<ConfigProvider theme={{ components: { Tabs: { itemSelectedColor: token.colorText } } }}>
<Tabs
defaultActiveKey="settings"
items={[
{
key: 'settings',
label: catTabLabel(
<SettingOutlined aria-hidden />,
t('pages.settings.panelSettings'),
isMobile,
),
children: (
<>
<SettingListItem
paddings="small"
title={t('pages.settings.wechatEnable')}
description={t('pages.settings.wechatEnableDesc')}
>
<Switch
checked={allSetting.wechatEnable}
onChange={(value) => updateSetting({ wechatEnable: value })}
/>
</SettingListItem>
<SettingListItem
paddings="small"
title={t('pages.settings.wechatMode')}
description={t('pages.settings.wechatModeDesc')}
>
<Select<WechatMode>
value={allSetting.wechatMode}
onChange={(value) => updateSetting({ wechatMode: value })}
style={{ width: '100%' }}
options={[
{ value: 'wecom', label: t('pages.settings.wechatModeWecom') },
{ value: 'webhook', label: t('pages.settings.wechatModeWebhook') },
]}
/>
</SettingListItem>
<Alert
type="info"
showIcon
title={t('pages.settings.wechatPersonalGateway')}
style={{ marginBottom: 12 }}
/>
<SettingListItem
paddings="small"
title={t('pages.settings.wechatWebhookURL')}
description={
allSetting.hasWechatWebhookURL && !allSetting.clearWechatWebhookURL
? t('pages.settings.wechatWebhookURLConfigured')
: t('pages.settings.wechatWebhookURLDesc')
}
>
<SecretInput
value={allSetting.wechatWebhookURL}
configured={allSetting.hasWechatWebhookURL}
clearArmed={allSetting.clearWechatWebhookURL}
placeholder={t('pages.settings.wechatSecretPlaceholder')}
onChange={(value) => updateSetting({ wechatWebhookURL: value })}
onClearArmedChange={(value) => updateSetting({ clearWechatWebhookURL: value })}
/>
</SettingListItem>
{allSetting.wechatMode === 'webhook' && (
<SettingListItem
paddings="small"
title={t('pages.settings.wechatToken')}
description={
allSetting.hasWechatToken && !allSetting.clearWechatToken
? t('pages.settings.wechatTokenConfigured')
: t('pages.settings.wechatTokenDesc')
}
>
<SecretInput
value={allSetting.wechatToken}
configured={allSetting.hasWechatToken}
clearArmed={allSetting.clearWechatToken}
placeholder={t('pages.settings.wechatSecretPlaceholder')}
onChange={(value) => updateSetting({ wechatToken: value })}
onClearArmedChange={(value) => updateSetting({ clearWechatToken: value })}
/>
</SettingListItem>
)}
<SettingListItem paddings="small" title={t('pages.settings.wechatLanguage')}>
<Select
value={allSetting.wechatLang}
onChange={(value) => updateSetting({ wechatLang: value })}
options={languageOptions}
style={{ width: '100%' }}
/>
</SettingListItem>
<Space orientation="vertical" size={8} style={{ width: '100%', marginTop: 16 }}>
<Typography.Text type="secondary">
{t('pages.settings.wechatSaveBeforeTest')}
</Typography.Text>
<Button
type="primary"
icon={<SendOutlined aria-hidden />}
loading={testing}
disabled={!allSetting.wechatEnable || hasPendingChanges}
onClick={testWechat}
>
{t('pages.settings.wechatTest')}
</Button>
{testResult && !hasPendingChanges && (
<Alert
type={testResult.success ? 'success' : 'error'}
title={testResult.msg}
showIcon
closable={{ onClose: () => setTestResult(null) }}
/>
)}
</Space>
</>
),
},
{
key: 'notifications',
label: catTabLabel(
<BellOutlined aria-hidden />,
t('pages.settings.notifications'),
isMobile,
),
children: (
<>
<SettingListItem
paddings="small"
title={t('pages.settings.wechatReportEnable')}
description={t('pages.settings.wechatReportEnableDesc')}
>
<Switch
checked={allSetting.wechatReportEnable}
onChange={(value) => updateSetting({ wechatReportEnable: value })}
/>
</SettingListItem>
{allSetting.wechatReportEnable && (
<SettingListItem
paddings="small"
title={t('pages.settings.wechatReportTime')}
description={t('pages.settings.wechatReportTimeDesc')}
>
<NotifyTimeField
value={allSetting.wechatRunTime}
onChange={(value) => updateSetting({ wechatRunTime: value })}
ariaLabel={t('pages.settings.wechatReportTime')}
/>
</SettingListItem>
)}
<SettingListItem
paddings="small"
title={t('pages.settings.wechatEvents')}
description={t('pages.settings.wechatEventsDesc')}
>
<WechatNotifications allSetting={allSetting} updateSetting={updateSetting} />
</SettingListItem>
</>
),
},
]}
/>
</ConfigProvider>
);
}
+17
View File
@@ -13,6 +13,9 @@ export type SubProfileMode = z.infer<typeof SubProfileModeSchema>;
export const SubHostSortModeSchema = z.enum(['inbound-first', 'hosts-first']);
export type SubHostSortMode = z.infer<typeof SubHostSortModeSchema>;
export const WechatModeSchema = z.enum(['wecom', 'webhook']);
export type WechatMode = z.infer<typeof WechatModeSchema>;
export const AllSettingFieldsSchema = z
.object({
webListen: z.string().optional(),
@@ -197,6 +200,20 @@ export const AllSettingFieldsSchema = z
discordMemory: z.number().int().min(0).max(100).optional(),
discordLang: z.string().optional(),
discordEnabledEvents: z.string().optional(),
wechatEnable: z.boolean().optional(),
wechatMode: WechatModeSchema.optional(),
wechatWebhookURL: z.string().optional(),
hasWechatWebhookURL: z.boolean().optional(),
clearWechatWebhookURL: z.boolean().optional(),
wechatToken: z.string().optional(),
hasWechatToken: z.boolean().optional(),
clearWechatToken: z.boolean().optional(),
wechatLang: z.string().optional(),
wechatReportEnable: z.boolean().optional(),
wechatRunTime: z.string().optional(),
wechatEnabledEvents: z.string().optional(),
wechatCpu: z.number().int().min(0).max(100).optional(),
wechatMemory: z.number().int().min(0).max(100).optional(),
})
.loose();
+146
View File
@@ -0,0 +1,146 @@
import { useState } from 'react';
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { AllSetting } from '@/models/setting';
import WechatTab from '@/pages/settings/WechatTab';
import { HttpUtil, Msg } from '@/utils';
import { renderWithProviders } from './test-utils';
function StatefulTab({ initial = new AllSetting() }: { initial?: AllSetting }) {
const [setting, setSetting] = useState(initial);
return (
<>
<WechatTab
allSetting={setting}
hasPendingChanges={!setting.equals(initial)}
updateSetting={(patch) => setSetting((current) => new AllSetting({ ...current, ...patch }))}
/>
<output data-testid="draft">{JSON.stringify(setting)}</output>
</>
);
}
describe('WeChat notification settings', () => {
it('retains saved webhook credentials until an explicit clear is saved', () => {
renderWithProviders(
<StatefulTab initial={new AllSetting({ wechatEnable: true, hasWechatWebhookURL: true })} />,
);
const input = screen.getByLabelText('Webhook URL') as HTMLInputElement;
expect(input.value).toBe('');
expect(
screen.getByText('A webhook URL is saved. Leave this field blank to keep it.'),
).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: 'Clear' }));
expect(JSON.parse(screen.getByTestId('draft').textContent || '{}').clearWechatWebhookURL).toBe(
true,
);
fireEvent.change(input, { target: { value: 'https://example.com/notify' } });
const draft = JSON.parse(screen.getByTestId('draft').textContent || '{}');
expect(draft.wechatWebhookURL).toBe('https://example.com/notify');
expect(draft.clearWechatWebhookURL).toBe(false);
});
it('shows optional bearer authentication only for a compatible custom gateway', async () => {
renderWithProviders(<StatefulTab />);
expect(screen.queryByLabelText('Bearer token')).toBeNull();
fireEvent.mouseDown(screen.getByRole('combobox', { name: 'Delivery mode' }));
fireEvent.click(await screen.findByText('Custom webhook gateway'));
expect(screen.getByLabelText('Bearer token')).toBeTruthy();
expect(screen.getByText(/Personal WeChat requires a compatible gateway/)).toBeTruthy();
});
it('keeps scheduled reports independent from event selection', async () => {
renderWithProviders(<StatefulTab />);
fireEvent.click(screen.getByRole('tab', { name: /Notifications/ }));
const reportToggle = screen.getByRole('switch', { name: 'Scheduled reports' });
expect(reportToggle.getAttribute('aria-checked')).toBe('false');
expect(screen.queryByRole('combobox', { name: 'Report schedule' })).toBeNull();
fireEvent.click(reportToggle);
expect(screen.getByRole('combobox', { name: 'Report schedule' })).toBeTruthy();
fireEvent.click(screen.getByRole('checkbox', { name: 'Crash' }));
await waitFor(() => {
const draft = JSON.parse(screen.getByTestId('draft').textContent || '{}');
expect(draft.wechatReportEnable).toBe(true);
expect(draft.wechatEnabledEvents).toBe('login.attempt,cpu.high,xray.crash');
});
});
it('tests the saved server configuration and shows the actual delivery result', async () => {
const post = vi
.spyOn(HttpUtil, 'post')
.mockResolvedValueOnce(new Msg(false, 'Destination rejected the message'));
renderWithProviders(
<StatefulTab initial={new AllSetting({ wechatEnable: true, hasWechatWebhookURL: true })} />,
);
expect(
screen.getByText('Save changes before testing. The test uses the saved configuration.'),
).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: 'Send test notification' }));
expect(await screen.findByText('Destination rejected the message')).toBeTruthy();
expect(post.mock.calls.some(([path]) => path === '/panel/api/setting/testWechat')).toBe(true);
});
it('updates WeChat thresholds without changing another notification provider', () => {
renderWithProviders(<StatefulTab initial={new AllSetting({ wechatCpu: 80, smtpCpu: 70 })} />);
fireEvent.click(screen.getByRole('tab', { name: /Notifications/ }));
fireEvent.change(screen.getByRole('spinbutton', { name: 'CPU high (%)' }), {
target: { value: '92' },
});
const draft = JSON.parse(screen.getByTestId('draft').textContent || '{}');
expect(draft.wechatCpu).toBe(92);
expect(draft.smtpCpu).toBe(70);
expect(draft.wechatEnabledEvents).toBe('login.attempt,cpu.high');
expect(draft.wechatReportEnable).toBe(false);
});
it('shows a successful saved-configuration test when the response has no detail', async () => {
vi.spyOn(HttpUtil, 'post').mockResolvedValueOnce(new Msg(true));
renderWithProviders(<StatefulTab initial={new AllSetting({ wechatEnable: true })} />);
fireEvent.click(screen.getByRole('button', { name: 'Send test notification' }));
expect(await screen.findByText('Test notification sent successfully')).toBeTruthy();
expect(screen.queryByText('Request failed')).toBeNull();
});
it('does not test a disabled channel or a destination with unsaved changes', () => {
const post = vi.spyOn(HttpUtil, 'post');
const callsBefore = post.mock.calls.length;
const { unmount } = renderWithProviders(<StatefulTab />);
let button = screen.getByRole('button', {
name: 'Send test notification',
}) as HTMLButtonElement;
expect(button.disabled).toBe(true);
fireEvent.click(button);
expect(post.mock.calls.length).toBe(callsBefore);
unmount();
renderWithProviders(
<StatefulTab initial={new AllSetting({ wechatEnable: true, hasWechatWebhookURL: true })} />,
);
button = screen.getByRole('button', { name: 'Send test notification' }) as HTMLButtonElement;
expect(button.disabled).toBe(false);
fireEvent.change(screen.getByLabelText('Webhook URL'), {
target: { value: 'https://receiver.example/notify' },
});
expect(button.disabled).toBe(true);
fireEvent.click(button);
expect(post.mock.calls.length).toBe(callsBefore);
});
it('keeps the saved integer threshold when its input is cleared', () => {
renderWithProviders(<StatefulTab initial={new AllSetting({ wechatCpu: 80 })} />);
fireEvent.click(screen.getByRole('tab', { name: /Notifications/ }));
fireEvent.change(screen.getByRole('spinbutton', { name: 'CPU high (%)' }), {
target: { value: '' },
});
expect(JSON.parse(screen.getByTestId('draft').textContent || '{}').wechatCpu).toBe(80);
});
it('stores metric thresholds as valid integer percentages', () => {
renderWithProviders(<StatefulTab initial={new AllSetting({ wechatCpu: 80 })} />);
fireEvent.click(screen.getByRole('tab', { name: /Notifications/ }));
const input = screen.getByRole('spinbutton', { name: 'CPU high (%)' });
fireEvent.change(input, { target: { value: '92.5' } });
fireEvent.blur(input);
expect(JSON.parse(screen.getByTestId('draft').textContent || '{}').wechatCpu).toBe(93);
});
});
+17 -9
View File
@@ -35,11 +35,13 @@ type updateUserForm struct {
// "unchanged", so clearing needs its own signal — see #5724).
type updateSettingForm struct {
entity.AllSetting
TwoFactorCode string `json:"twoFactorCode" form:"twoFactorCode"`
ClearTgBotToken bool `json:"clearTgBotToken" form:"clearTgBotToken"`
ClearLdapPassword bool `json:"clearLdapPassword" form:"clearLdapPassword"`
ClearSmtpPassword bool `json:"clearSmtpPassword" form:"clearSmtpPassword"`
ClearDiscordBotToken bool `json:"clearDiscordBotToken" form:"clearDiscordBotToken"`
TwoFactorCode string `json:"twoFactorCode" form:"twoFactorCode"`
ClearTgBotToken bool `json:"clearTgBotToken" form:"clearTgBotToken"`
ClearLdapPassword bool `json:"clearLdapPassword" form:"clearLdapPassword"`
ClearSmtpPassword bool `json:"clearSmtpPassword" form:"clearSmtpPassword"`
ClearDiscordBotToken bool `json:"clearDiscordBotToken" form:"clearDiscordBotToken"`
ClearWechatWebhookURL bool `json:"clearWechatWebhookURL" form:"clearWechatWebhookURL"`
ClearWechatToken bool `json:"clearWechatToken" form:"clearWechatToken"`
}
type validateRegexForm struct {
@@ -82,6 +84,7 @@ func (a *SettingController) initRouter(g *gin.RouterGroup) {
g.POST("/testTgBot", a.testTgBot)
g.POST("/tgBotCapabilities", a.tgBotCapabilities)
g.POST("/testDiscord", a.testDiscord)
g.POST("/testWechat", a.testWechat)
}
func (a *SettingController) validateRegex(c *gin.Context) {
@@ -152,10 +155,12 @@ func (a *SettingController) updateSetting(c *gin.Context) {
}
}
err := a.settingService.UpdateAllSetting(allSetting, service.SecretClears{
TgBotToken: form.ClearTgBotToken,
LdapPassword: form.ClearLdapPassword,
SmtpPassword: form.ClearSmtpPassword,
DiscordBotToken: form.ClearDiscordBotToken,
TgBotToken: form.ClearTgBotToken,
LdapPassword: form.ClearLdapPassword,
SmtpPassword: form.ClearSmtpPassword,
DiscordBotToken: form.ClearDiscordBotToken,
WechatWebhookURL: form.ClearWechatWebhookURL,
WechatToken: form.ClearWechatToken,
})
if err == nil && twoFactorErr == nil && !oldTwoFactor && allSetting.TwoFactorEnable {
if bumpErr := a.userService.BumpLoginEpoch(); bumpErr != nil {
@@ -189,6 +194,9 @@ func (a *SettingController) updateSetting(c *gin.Context) {
reloadDiscordFunc()
}
}
if err == nil && reloadWechatFunc != nil {
reloadWechatFunc()
}
jsonMsg(c, I18nWeb(c, "pages.settings.toasts.modifySettings"), err)
}
+34
View File
@@ -0,0 +1,34 @@
package controller
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/mhsanaei/3x-ui/v3/internal/web/service/wechat"
)
var (
wechatService *wechat.Service
reloadWechatFunc func()
)
func SetWechatService(s *wechat.Service) { wechatService = s }
func SetReloadWechatFunc(fn func()) { reloadWechatFunc = fn }
func (a *SettingController) testWechat(c *gin.Context) {
if wechatService == nil {
jsonMsg(c, I18nWeb(c, "pages.settings.wechatTestFailed"), errors.New("WeChat service is unavailable"))
return
}
enabled, err := a.settingService.GetWechatEnable()
if err != nil || !enabled {
jsonMsg(c, I18nWeb(c, "pages.settings.wechatTestFailed"), errors.New("WeChat notifications are disabled"))
return
}
if err := wechatService.SendTest(); err != nil {
jsonMsg(c, I18nWeb(c, "pages.settings.wechatTestFailed"), err)
return
}
jsonMsg(c, I18nWeb(c, "pages.settings.wechatTestSuccess"), nil)
}
+39
View File
@@ -0,0 +1,39 @@
package controller
import (
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
"github.com/mhsanaei/3x-ui/v3/internal/web/service/wechat"
)
func TestWechatTestEndpointRefusesDisabledSavedConfiguration(t *testing.T) {
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
previous := wechatService
t.Cleanup(func() { wechatService = previous })
SetWechatService(wechat.NewService(service.SettingService{}))
gin.SetMode(gin.TestMode)
router := gin.New()
NewSettingController(router.Group("/panel/api"))
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/panel/api/setting/testWechat", nil))
var result struct {
Success bool `json:"success"`
Msg string `json:"msg"`
}
if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
// Without the endpoint's own check the sender fails too, but with its generic configuration error.
if response.Code != http.StatusOK || result.Success || !strings.HasSuffix(result.Msg, "(WeChat notifications are disabled)") {
t.Fatalf("disabled test endpoint returned %d %s", response.Code, response.Body.String())
}
}
+21 -8
View File
@@ -78,6 +78,17 @@ type AllSetting struct {
SmtpCpu int `json:"smtpCpu" form:"smtpCpu" validate:"gte=0,lte=100"`
SmtpMemory int `json:"smtpMemory" form:"smtpMemory" validate:"gte=0,lte=100"`
WechatEnable bool `json:"wechatEnable" form:"wechatEnable"`
WechatMode string `json:"wechatMode" form:"wechatMode"`
WechatWebhookURL string `json:"wechatWebhookURL" form:"wechatWebhookURL"`
WechatToken string `json:"wechatToken" form:"wechatToken"`
WechatLang string `json:"wechatLang" form:"wechatLang"`
WechatReportEnable bool `json:"wechatReportEnable" form:"wechatReportEnable"`
WechatRunTime string `json:"wechatRunTime" form:"wechatRunTime"`
WechatEnabledEvents string `json:"wechatEnabledEvents" form:"wechatEnabledEvents"`
WechatCpu int `json:"wechatCpu" form:"wechatCpu" validate:"gte=0,lte=100"`
WechatMemory int `json:"wechatMemory" form:"wechatMemory" validate:"gte=0,lte=100"`
DiscordBotEnable bool `json:"discordBotEnable" form:"discordBotEnable"`
DiscordBotToken string `json:"discordBotToken" form:"discordBotToken"`
DiscordChannelId string `json:"discordChannelId" form:"discordChannelId"`
@@ -230,14 +241,16 @@ type AllSetting struct {
type AllSettingView struct {
AllSetting
HasTgBotToken bool `json:"hasTgBotToken"`
HasTwoFactorToken bool `json:"hasTwoFactorToken"`
HasLdapPassword bool `json:"hasLdapPassword"`
HasApiToken bool `json:"hasApiToken"`
HasWarpSecret bool `json:"hasWarpSecret"`
HasNordSecret bool `json:"hasNordSecret"`
HasSmtpPassword bool `json:"hasSmtpPassword"`
HasDiscordBotToken bool `json:"hasDiscordBotToken"`
HasTgBotToken bool `json:"hasTgBotToken"`
HasTwoFactorToken bool `json:"hasTwoFactorToken"`
HasLdapPassword bool `json:"hasLdapPassword"`
HasApiToken bool `json:"hasApiToken"`
HasWarpSecret bool `json:"hasWarpSecret"`
HasNordSecret bool `json:"hasNordSecret"`
HasSmtpPassword bool `json:"hasSmtpPassword"`
HasDiscordBotToken bool `json:"hasDiscordBotToken"`
HasWechatWebhookURL bool `json:"hasWechatWebhookURL"`
HasWechatToken bool `json:"hasWechatToken"`
}
func pathHasForbiddenChar(s string) bool {
+58
View File
@@ -0,0 +1,58 @@
package job
import (
"context"
"slices"
"sync"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
"github.com/mhsanaei/3x-ui/v3/internal/web/service/wechat"
)
type WechatNotifyJob struct {
serverService wechat.ServerProvider
inboundService wechat.InboundProvider
wechatService *wechat.Service
}
type wechatReportServer struct {
server wechat.ServerProvider
mu sync.Mutex
nativeSampled bool
}
func (s *wechatReportServer) GetStatus(last *service.Status) *service.Status {
s.mu.Lock()
defer s.mu.Unlock()
status := s.server.GetStatus(last)
if status == nil || status.ResourceScope != "" || s.nativeSampled {
return status
}
s.nativeSampled = true
if !status.MetricAvailable("cpu") {
return status
}
// A dedicated ServerService initializes its native CPU baseline with zero.
// Preserve the snapshot and label that first value as unavailable.
copy := *status
copy.UnavailableMetrics = append(slices.Clone(status.UnavailableMetrics), "cpu")
return &copy
}
func NewWechatNotifyJob(svc *wechat.Service) *WechatNotifyJob {
return &WechatNotifyJob{serverService: &wechatReportServer{server: &service.ServerService{}}, inboundService: &service.InboundService{}, wechatService: svc}
}
// Run reports status even if Xray is down; no backup or configuration files are read.
func (job *WechatNotifyJob) Run() {
if job.wechatService == nil {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
if err := job.wechatService.SendReport(ctx, job.serverService, job.inboundService); err != nil {
logger.Warning("WechatNotifyJob: ", err)
}
}
@@ -0,0 +1,59 @@
package job
import (
"slices"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
type wechatStatusSequence struct {
statuses []*service.Status
}
func (s *wechatStatusSequence) GetStatus(*service.Status) *service.Status {
status := s.statuses[0]
s.statuses = s.statuses[1:]
return status
}
func TestWechatReportDoesNotPresentCPUWarmupAsAnIdleHost(t *testing.T) {
warmup := &service.Status{UnavailableMetrics: []string{"uptime"}}
server := &wechatReportServer{server: &wechatStatusSequence{statuses: []*service.Status{
warmup, {}, {Cpu: 25},
}}}
first := server.GetStatus(nil)
if first.Cpu != 0 || first.MetricAvailable("cpu") || !slices.Equal(first.UnavailableMetrics, []string{"uptime", "cpu"}) {
t.Fatalf("CPU warmup must be unavailable without losing other metadata: %+v", first)
}
if !warmup.MetricAvailable("cpu") || !slices.Equal(warmup.UnavailableMetrics, []string{"uptime"}) {
t.Fatal("WeChat report changed its source status snapshot")
}
idle := server.GetStatus(nil)
if idle.Cpu != 0 || !idle.MetricAvailable("cpu") {
t.Fatalf("a measured idle sample must remain 0%% and available: %+v", idle)
}
busy := server.GetStatus(nil)
if busy.Cpu != 25 || !busy.MetricAvailable("cpu") {
t.Fatalf("a measured busy sample must remain 25%% and available: %+v", busy)
}
}
func TestWechatReportWaitsForNativeCPUBaselineAfterMissingOrScopedStatus(t *testing.T) {
scoped := &service.Status{ResourceScope: "lxc", UnavailableMetrics: []string{"cpu", "swap"}}
server := &wechatReportServer{server: &wechatStatusSequence{statuses: []*service.Status{
nil, scoped, {}, {},
}}}
if got := server.GetStatus(nil); got != nil {
t.Fatalf("missing server status became a reportable status: %+v", got)
}
if got := server.GetStatus(nil); got != scoped || !slices.Equal(got.UnavailableMetrics, []string{"cpu", "swap"}) {
t.Fatalf("scoped metric availability was changed: %+v", got)
}
if got := server.GetStatus(nil); got.MetricAvailable("cpu") {
t.Fatal("missing or scoped status consumed the native CPU baseline")
}
if got := server.GetStatus(nil); got.Cpu != 0 || !got.MetricAvailable("cpu") {
t.Fatalf("native CPU remained unavailable after its baseline: %+v", got)
}
}
+1 -1
View File
@@ -622,7 +622,7 @@ func (s *InboundService) emailSubIDsForClients(clients []model.Client) (map[stri
}
result := make(map[string]string, len(emails))
db := database.GetDB()
for _, batch := range chunkStrings(emailSpellings(emails), sqlInChunk) {
for _, batch := range chunkStrings(EmailSpellings(emails), sqlInChunk) {
var rows []struct {
Email string
SubID string `gorm:"column:sub_id"`
+4 -4
View File
@@ -124,9 +124,9 @@ func (s *InboundService) backfillClientStats(db *gorm.DB, inbounds []*model.Inbo
return clientsByInbound
}
// emailSpellings returns the arguments a "LOWER(col) IN ? OR col IN ?" match
// EmailSpellings returns the arguments a "LOWER(col) IN ? OR col IN ?" match
// needs: SQLite's LOWER() folds ASCII only, so non-ASCII capitals get every case.
func emailSpellings(emails []string) []string {
func EmailSpellings(emails []string) []string {
seen := make(map[string]struct{}, len(emails))
out := make([]string, 0, len(emails))
for _, e := range emails {
@@ -151,7 +151,7 @@ func emailSpellings(emails []string) []string {
// emailUsedByOtherInbounds reports whether email lives in any inbound other than
// exceptInboundId. Inside a transaction pass tx: a pool query there starves the pool.
func (s *InboundService) emailUsedByOtherInbounds(db *gorm.DB, email string, exceptInboundId int) (bool, error) {
spellings := emailSpellings([]string{email})
spellings := EmailSpellings([]string{email})
if len(spellings) == 0 {
return false, nil
}
@@ -171,7 +171,7 @@ func (s *InboundService) emailUsedByOtherInbounds(db *gorm.DB, email string, exc
// is keyed by the lower-cased email.
func (s *InboundService) emailsUsedByOtherInbounds(db *gorm.DB, emails []string, exceptInboundId int) (map[string]bool, error) {
shared := make(map[string]bool, len(emails))
for _, batch := range chunkStrings(emailSpellings(emails), sqlInChunk) {
for _, batch := range chunkStrings(EmailSpellings(emails), sqlInChunk) {
var rows []struct{ Email string }
err := db.Table("client_inbounds").
Joins("JOIN clients ON clients.id = client_inbounds.client_id").
+1 -1
View File
@@ -90,7 +90,7 @@ func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot
}
// SQLite's LOWER folds ASCII only, so a non-ASCII capital is matched by its spellings too.
var records []model.ClientRecord
for _, batch := range chunkStrings(emailSpellings(reported), sqlInChunk) {
for _, batch := range chunkStrings(EmailSpellings(reported), sqlInChunk) {
var rows []model.ClientRecord
if err := tx.Where("LOWER(email) IN ? OR email IN ?", batch, batch).Find(&rows).Error; err != nil {
return nil, err
+2 -2
View File
@@ -1084,7 +1084,7 @@ func (s *InboundService) DelDepletedClients(id int) (err error) {
emailExpr,
)
stillSet := make(map[string]struct{}, len(rowEmails))
for _, batch := range chunkStrings(emailSpellings(rowEmails), sqlInChunk) {
for _, batch := range chunkStrings(EmailSpellings(rowEmails), sqlInChunk) {
var stillReferenced []string
if err := tx.Raw(stillQuery, batch, batch).Scan(&stillReferenced).Error; err != nil {
return err
@@ -1099,7 +1099,7 @@ func (s *InboundService) DelDepletedClients(id int) (err error) {
toDelete = append(toDelete, e)
}
}
for _, batch := range chunkStrings(emailSpellings(toDelete), sqlInChunk) {
for _, batch := range chunkStrings(EmailSpellings(toDelete), sqlInChunk) {
if err := tx.Where("LOWER(email) IN ? OR email IN ?", batch, batch).Delete(xray.ClientTraffic{}).Error; err != nil {
return err
}
+44 -9
View File
@@ -105,6 +105,16 @@ var defaultValueMap = map[string]string{
"tgCpu": "80",
"tgMemory": "80",
"tgLang": "en-US",
"wechatEnable": "false",
"wechatMode": "wecom",
"wechatWebhookURL": "",
"wechatToken": "",
"wechatLang": "en-US",
"wechatReportEnable": "false",
"wechatRunTime": "@daily",
"wechatEnabledEvents": "login.attempt,cpu.high",
"wechatCpu": "80",
"wechatMemory": "80",
"twoFactorEnable": "false",
"twoFactorToken": "",
"happLinkEnable": "false",
@@ -371,6 +381,8 @@ func (s *SettingService) GetAllSettingView() (*entity.AllSettingView, error) {
view.HasNordSecret = secretConfigured(mustString(s.GetNord()))
view.HasSmtpPassword = secretConfigured(allSetting.SmtpPassword)
view.HasDiscordBotToken = secretConfigured(allSetting.DiscordBotToken)
view.HasWechatWebhookURL = secretConfigured(allSetting.WechatWebhookURL)
view.HasWechatToken = secretConfigured(allSetting.WechatToken)
var apiTokenCount int64
if err := database.GetDB().Model(model.ApiToken{}).Where("enabled = ?", true).Count(&apiTokenCount).Error; err == nil {
view.HasApiToken = apiTokenCount > 0
@@ -380,6 +392,8 @@ func (s *SettingService) GetAllSettingView() (*entity.AllSettingView, error) {
view.LdapPassword = ""
view.SmtpPassword = ""
view.DiscordBotToken = ""
view.WechatWebhookURL = ""
view.WechatToken = ""
return view, nil
}
@@ -1706,10 +1720,12 @@ func (s *SettingService) SetNodeDownThreshold(value int) error {
// flag, a blank submitted secret means "unchanged" (the field is always served
// blank to the browser) and the stored value is preserved.
type SecretClears struct {
TgBotToken bool
LdapPassword bool
SmtpPassword bool
DiscordBotToken bool
TgBotToken bool
LdapPassword bool
SmtpPassword bool
DiscordBotToken bool
WechatWebhookURL bool
WechatToken bool
}
func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting, clears SecretClears) error {
@@ -1739,6 +1755,9 @@ func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting, clears
}
allSetting.TwoFactorToken = totp.NormalizeSecret(allSetting.TwoFactorToken)
}
if err := validateWechatSettings(allSetting); err != nil {
return err
}
if err := validateSettingsURLs(allSetting); err != nil {
return err
}
@@ -1884,6 +1903,20 @@ func (s *SettingService) preserveRedactedSecrets(allSetting *entity.AllSetting,
}
allSetting.DiscordBotToken = value
}
if !clears.WechatWebhookURL && strings.TrimSpace(allSetting.WechatWebhookURL) == "" {
value, err := s.GetWechatWebhookURL()
if err != nil {
return err
}
allSetting.WechatWebhookURL = value
}
if !clears.WechatToken && strings.TrimSpace(allSetting.WechatToken) == "" {
value, err := s.GetWechatToken()
if err != nil {
return err
}
allSetting.WechatToken = value
}
return nil
}
@@ -2095,11 +2128,13 @@ func (s *SettingService) GetDefaultSettings(host string) (any, error) {
}
var factoryDefaultSecretKeys = map[string]bool{
"tgBotToken": true,
"twoFactorToken": true,
"ldapPassword": true,
"smtpPassword": true,
"discordBotToken": true,
"tgBotToken": true,
"twoFactorToken": true,
"ldapPassword": true,
"smtpPassword": true,
"discordBotToken": true,
"wechatWebhookURL": true,
"wechatToken": true,
}
/*
+126
View File
@@ -0,0 +1,126 @@
package service
import (
"errors"
"net"
"net/url"
"strconv"
"strings"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/eventbus"
"github.com/mhsanaei/3x-ui/v3/internal/util/cronspec"
"github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
"github.com/mhsanaei/3x-ui/v3/internal/web/entity"
)
func (s *SettingService) GetWechatEnable() (bool, error) { return s.getBool("wechatEnable") }
func (s *SettingService) GetWechatMode() (string, error) { return s.getString("wechatMode") }
func (s *SettingService) GetWechatWebhookURL() (string, error) {
return s.getString("wechatWebhookURL")
}
func (s *SettingService) GetWechatToken() (string, error) { return s.getString("wechatToken") }
func (s *SettingService) GetWechatLang() (string, error) { return s.getString("wechatLang") }
func (s *SettingService) GetWechatReportEnable() (bool, error) {
return s.getBool("wechatReportEnable")
}
func (s *SettingService) GetWechatRunTime() (string, error) { return s.getString("wechatRunTime") }
func (s *SettingService) GetWechatEnabledEvents() (string, error) {
return s.getString("wechatEnabledEvents")
}
func (s *SettingService) GetWechatCpu() (int, error) { return s.getInt("wechatCpu") }
func (s *SettingService) GetWechatMemory() (int, error) { return s.getInt("wechatMemory") }
type WechatDeliverySettings struct {
Enabled bool
Mode string
WebhookURL string
Token string
}
// GetWechatDeliverySettings reads a coherent destination and credential snapshot.
func (s *SettingService) GetWechatDeliverySettings() (WechatDeliverySettings, error) {
keys := []string{"wechatEnable", "wechatMode", "wechatWebhookURL", "wechatToken"}
values := make(map[string]string, len(keys))
for _, key := range keys {
values[key] = defaultValueMap[key]
}
var rows []model.Setting
if err := database.GetDB().Where("key IN ?", keys).Find(&rows).Error; err != nil {
return WechatDeliverySettings{}, err
}
for _, row := range rows {
values[row.Key] = row.Value
}
enabled, err := strconv.ParseBool(effectiveSettingValue("wechatEnable", values["wechatEnable"]))
if err != nil {
return WechatDeliverySettings{}, err
}
return WechatDeliverySettings{
Enabled: enabled, Mode: values["wechatMode"], WebhookURL: values["wechatWebhookURL"], Token: values["wechatToken"],
}, nil
}
// ValidateWechatDestination leaves DNS checks to the guarded dial, so saving
// settings cannot contact the receiver or leak a credential in an error.
func ValidateWechatDestination(mode, raw string) (string, error) {
if mode != "wecom" && mode != "webhook" {
return "", errors.New("WeChat notification mode is invalid")
}
raw = strings.TrimSpace(raw)
if raw == "" {
return "", nil
}
u, err := url.Parse(raw)
if err != nil || len(raw) > 4096 || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.Fragment != "" {
return "", errors.New("WeChat webhook URL is invalid")
}
host := strings.ToLower(strings.TrimSuffix(u.Hostname(), "."))
if host == "localhost" || strings.HasSuffix(host, ".localhost") || strings.Contains(host, "%") {
return "", errors.New("WeChat webhook URL is invalid")
}
if ip := net.ParseIP(host); ip != nil && netsafe.IsBlockedIP(ip) {
return "", errors.New("WeChat webhook URL is invalid")
}
if mode == "wecom" && (u.Host != "qyapi.weixin.qq.com" && u.Host != "qyapi.weixin.qq.com:443" || u.Path != "/cgi-bin/webhook/send" || u.RawPath != "" || u.Query().Get("key") == "" || len(u.Query()) != 1 || len(u.Query()["key"]) != 1) {
return "", errors.New("WeChat webhook URL is invalid")
}
return u.String(), nil
}
func validateWechatSettings(settings *entity.AllSetting) error {
if settings.WechatMode == "" {
settings.WechatMode = "wecom"
}
endpoint, err := ValidateWechatDestination(settings.WechatMode, settings.WechatWebhookURL)
if err != nil {
return err
}
if settings.WechatEnable && endpoint == "" {
return errors.New("WeChat webhook URL is required")
}
settings.WechatWebhookURL = endpoint
if len(settings.WechatToken) > 4096 || strings.ContainsAny(settings.WechatToken, "\r\n") {
return errors.New("WeChat bearer token is invalid")
}
if settings.WechatRunTime == "" {
settings.WechatRunTime = "@daily"
}
if _, err := cronspec.Parse(settings.WechatRunTime); err != nil {
return errors.New("WeChat report schedule is invalid")
}
for value := range strings.SplitSeq(settings.WechatEnabledEvents, ",") {
switch eventbus.EventType(strings.TrimSpace(value)) {
case "", eventbus.EventLoginAttempt, eventbus.EventCPUHigh, eventbus.EventMemoryHigh,
eventbus.EventNodeDown, eventbus.EventNodeUp, eventbus.EventXrayCrash,
eventbus.EventOutboundDown, eventbus.EventOutboundUp:
default:
return errors.New("WeChat notification event selection is invalid")
}
}
if settings.WechatLang == "" {
settings.WechatLang = "en-US"
}
return nil
}
+114
View File
@@ -0,0 +1,114 @@
package service
import (
"encoding/json"
"strings"
"testing"
)
func TestWechatSecretSettingsSurviveUnrelatedSaveAndClearExplicitly(t *testing.T) {
setupSettingTestDB(t)
s := &SettingService{}
const endpoint = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=private-key"
for key, value := range map[string]string{"wechatWebhookURL": endpoint, "wechatToken": "private-token"} {
if err := s.saveSetting(key, value); err != nil {
t.Fatal(err)
}
}
view, err := s.GetAllSettingView()
if err != nil {
t.Fatal(err)
}
encoded, err := json.Marshal(view)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(encoded), "private-key") || strings.Contains(string(encoded), "private-token") {
t.Fatal("settings response exposed a WeChat credential")
}
if !view.HasWechatWebhookURL || !view.HasWechatToken {
t.Fatal("redacted response lost the configured credential indicators")
}
view.PageSize = 50
if err := s.UpdateAllSetting(&view.AllSetting, SecretClears{}); err != nil {
t.Fatal(err)
}
stored, err := s.GetAllSetting()
if err != nil {
t.Fatal(err)
}
if stored.WechatWebhookURL != endpoint || stored.WechatToken != "private-token" || stored.PageSize != 50 {
t.Fatal("unrelated settings save replaced the redacted WeChat credentials")
}
stored.WechatWebhookURL, stored.WechatToken = "", ""
if err := s.UpdateAllSetting(stored, SecretClears{WechatWebhookURL: true, WechatToken: true}); err != nil {
t.Fatal(err)
}
cleared, err := s.GetAllSettingView()
if err != nil {
t.Fatal(err)
}
if cleared.HasWechatWebhookURL || cleared.HasWechatToken {
t.Fatal("explicit credential clearing retained the saved WeChat credentials")
}
}
func TestInvalidWechatDestinationDoesNotReplaceSavedSettings(t *testing.T) {
setupSettingTestDB(t)
s := &SettingService{}
for _, endpoint := range []string{
"http://example.com/notify", "https://user:password@example.com/notify",
"https://example.com/notify#secret", "https://127.0.0.1/notify",
"https://qyapi.weixin.qq.com.evil.example/cgi-bin/webhook/send?key=secret",
} {
t.Run(endpoint, func(t *testing.T) {
settings, err := s.GetAllSetting()
if err != nil {
t.Fatal(err)
}
settings.WechatEnable = true
settings.WechatMode = "wecom"
settings.WechatWebhookURL = endpoint
settings.PageSize = 99
err = s.UpdateAllSetting(settings, SecretClears{})
if err == nil || err.Error() != "WeChat webhook URL is invalid" {
t.Fatalf("invalid destination error = %v, want classified validation error", err)
}
stored, err := s.GetAllSetting()
if err != nil {
t.Fatal(err)
}
if stored.PageSize == 99 || stored.WechatEnable {
t.Fatal("invalid WeChat destination partially persisted unrelated settings")
}
})
}
}
func TestWechatCronAndEventSelectionRejectInvalidConfiguration(t *testing.T) {
setupSettingTestDB(t)
s := &SettingService{}
for _, tc := range []struct{ field, value string }{
{"wechatMode", "telegram"},
{"wechatRunTime", "not a schedule"},
{"wechatEnabledEvents", "login.attempt,unknown.event"},
} {
t.Run(tc.field, func(t *testing.T) {
settings, err := s.GetAllSetting()
if err != nil {
t.Fatal(err)
}
switch tc.field {
case "wechatMode":
settings.WechatMode = tc.value
case "wechatRunTime":
settings.WechatRunTime = tc.value
case "wechatEnabledEvents":
settings.WechatEnabledEvents = tc.value
}
if err := s.UpdateAllSetting(settings, SecretClears{}); err == nil || !strings.Contains(err.Error(), "WeChat") {
t.Fatalf("invalid %s was not rejected with a WeChat validation error: %v", tc.field, err)
}
})
}
}
+161
View File
@@ -0,0 +1,161 @@
package wechat
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/config"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
var ErrReport = errors.New("wechat status report is unavailable")
type ServerProvider interface {
GetStatus(*service.Status) *service.Status
}
type InboundProvider interface {
GetAllInbounds() ([]*model.Inbound, error)
}
type reportCounts struct{ total, disabled, expired, depleted int }
type reportTraffic struct {
used, remaining int64
quotaUnset bool
}
func addTrafficBytes(current, value int64) int64 {
value = max(value, 0)
const limit = int64(1<<63 - 1)
return current + min(value, limit-current)
}
func (traffic *reportTraffic) add(up, down, total int64) {
used := addTrafficBytes(max(up, 0), down)
traffic.used = addTrafficBytes(traffic.used, used)
if total <= 0 {
traffic.quotaUnset = true
return
}
traffic.remaining = addTrafficBytes(traffic.remaining, max(total-used, 0))
}
func (count *reportCounts) add(enabled bool, expiry, quota, up, down, now int64) {
count.total++
if !enabled {
count.disabled++
}
if expiry > 0 && expiry <= now {
count.expired++
}
if quota > 0 && (up >= quota || down >= quota || up >= quota-down) {
count.depleted++
}
}
func (s *Service) SendReport(ctx context.Context, server ServerProvider, inbound InboundProvider) error {
if ctx == nil {
ctx = context.Background()
}
on, err := s.settings.GetWechatEnable()
if err != nil {
return ErrConfiguration
}
if !on {
return nil
}
enabled, err := s.settings.GetWechatReportEnable()
if err != nil {
return ErrConfiguration
}
if !enabled {
return nil
}
if server == nil || inbound == nil {
return ErrReport
}
status := server.GetStatus(nil)
if status == nil {
return ErrReport
}
inbounds, err := inbound.GetAllInbounds()
if err != nil {
return ErrReport
}
limits, err := reportClientLimits(ctx, inbounds)
if err != nil {
return ErrReport
}
tr := s.translator()
now := time.Now()
cpu := "—"
if status.MetricAvailable("cpu") {
cpu = fmt.Sprintf("%.2f%%", status.Cpu)
}
uptime := "—"
if status.MetricAvailable("uptime") {
uptime = tr("discord.values.uptime", fmt.Sprintf("Days==%d", status.Uptime/86400), fmt.Sprintf("Hours==%d", status.Uptime%86400/3600))
}
capacity := func(used, total uint64) string {
if total == 0 {
return "—"
}
return fmt.Sprintf("%s / %s", common.FormatTraffic(int64(used)), common.FormatTraffic(int64(total)))
}
inboundCounts, clientCounts := reportCounts{}, reportCounts{}
traffic := reportTraffic{}
seen := make(map[string]bool)
for _, item := range inbounds {
if item == nil {
continue
}
inboundCounts.add(item.Enable, item.ExpiryTime, item.Total, item.Up, item.Down, now.UnixMilli())
for _, client := range item.ClientStats {
key := strings.ToLower(client.Email)
if seen[key] {
continue
}
seen[key] = true
if limit, ok := limits[key]; ok {
if client.Total == 0 {
client.Total = limit.TotalGB
}
if client.ExpiryTime == 0 {
client.ExpiryTime = limit.ExpiryTime
}
}
clientCounts.add(client.Enable, client.ExpiryTime, client.Total, client.Up, client.Down, now.UnixMilli())
traffic.add(client.Up, client.Down, client.Total)
}
}
if clientCounts.total == 0 {
traffic.quotaUnset = true
}
counts := func(value reportCounts) string {
return tr("wechat.report.counts", fmt.Sprintf("Total==%d", value.total), fmt.Sprintf("Disabled==%d", value.disabled), fmt.Sprintf("Expired==%d", value.expired), fmt.Sprintf("Depleted==%d", value.depleted))
}
remaining := common.FormatTraffic(traffic.remaining)
if traffic.quotaUnset {
remaining = tr("wechat.report.trafficQuotaUnset")
}
text := strings.Join([]string{
tr("wechat.report.title"),
tr("discord.fields.panelVersion") + ": " + config.GetPanelVersion(),
tr("discord.fields.xrayCore") + ": " + plain(status.Xray.Version) + " (" + string(status.Xray.State) + ")",
"CPU: " + cpu,
tr("pages.index.memory") + ": " + capacity(status.Mem.Current, status.Mem.Total),
tr("pages.index.storage") + ": " + capacity(status.Disk.Current, status.Disk.Total),
tr("pages.index.uptime") + ": " + uptime,
tr("wechat.report.trafficUsed") + ": " + common.FormatTraffic(traffic.used),
tr("wechat.report.trafficRemaining") + ": " + remaining,
tr("tgbot.inbounds") + ": " + counts(inboundCounts),
tr("clients") + ": " + counts(clientCounts),
}, "\n")
return s.send(ctx, "report", "report", text, now)
}
@@ -0,0 +1,49 @@
package wechat
import (
"context"
"strings"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
type reportClientLimit struct {
Email string
TotalGB int64
ExpiryTime int64
}
func reportClientLimits(ctx context.Context, inbounds []*model.Inbound) (map[string]reportClientLimit, error) {
emails := make([]string, 0)
seen := make(map[string]bool)
for _, inbound := range inbounds {
if inbound == nil {
continue
}
for _, client := range inbound.ClientStats {
key := strings.ToLower(client.Email)
if !seen[key] && (client.Total == 0 || client.ExpiryTime == 0) {
seen[key] = true
emails = append(emails, client.Email)
}
}
}
limits := make(map[string]reportClientLimit, len(emails))
spellings := service.EmailSpellings(emails)
// Each spelling is bound twice, keeping each query at no more than 500 parameters.
const batchSize = 250
for start := 0; start < len(spellings); start += batchSize {
batch := spellings[start:min(start+batchSize, len(spellings))]
var rows []reportClientLimit
if err := database.GetDB().WithContext(ctx).Model(&model.ClientRecord{}).
Select("email", "total_gb", "expiry_time").Where("LOWER(email) IN ? OR email IN ?", batch, batch).Find(&rows).Error; err != nil {
return nil, err
}
for _, row := range rows {
limits[strings.ToLower(row.Email)] = row
}
}
return limits, nil
}
+316
View File
@@ -0,0 +1,316 @@
package wechat
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"testing"
"time"
"gorm.io/gorm"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
type reportStatus struct{ status *service.Status }
func (provider reportStatus) GetStatus(*service.Status) *service.Status { return provider.status }
type reportInbounds struct {
inbounds []*model.Inbound
err error
}
func (provider reportInbounds) GetAllInbounds() ([]*model.Inbound, error) {
return provider.inbounds, provider.err
}
func TestReportSendsOnlySummaryAndCountsSharedClientsOnce(t *testing.T) {
settings := webhookSettings(t)
now := time.Now().UnixMilli()
status := &service.Status{Cpu: 12.5, Uptime: 90000}
status.Mem.Current, status.Mem.Total = 1<<30, 4<<30
status.Disk.Current, status.Disk.Total = 10<<30, 50<<30
status.Xray.Version = "test-core"
items := []*model.Inbound{
{Id: 1, Enable: true, ExpiryTime: now - 1000, Settings: `{"privateKey":"never-send"}`, ClientStats: []xray.ClientTraffic{
{Email: "shared", Enable: true, Total: 100, Up: 100},
{Email: "expired", Enable: true, ExpiryTime: now - 1000},
}},
{Id: 2, Enable: true, Total: 100, Down: 100, ClientStats: []xray.ClientTraffic{{Email: "shared", Enable: true, Total: 100, Up: 100}}},
}
var payload Envelope
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) {
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
t.Error(err)
}
})
if err := svc.SendReport(context.Background(), reportStatus{status}, reportInbounds{inbounds: items}); err != nil {
t.Fatal(err)
}
for _, expected := range []string{"CPU: 12.50%", "1.00GB / 4.00GB", "10.00GB / 50.00GB", "Total: 2", "Expired: 1", "Depleted: 1"} {
if !strings.Contains(payload.Text, expected) {
t.Errorf("report missing %q: %s", expected, payload.Text)
}
}
if payload.Type != "report" || payload.Event != "report" || strings.Contains(payload.Text, "never-send") || strings.Contains(payload.Text, "shared") {
t.Fatalf("report leaked configuration or client identity: %+v", payload)
}
}
func TestReportDoesNotPresentUnavailableMetricsAsMeasuredZero(t *testing.T) {
settings := webhookSettings(t)
var payload Envelope
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) { _ = json.NewDecoder(r.Body).Decode(&payload) })
status := &service.Status{UnavailableMetrics: []string{"cpu", "uptime"}}
if err := svc.SendReport(context.Background(), reportStatus{status}, reportInbounds{}); err != nil {
t.Fatal(err)
}
if !strings.Contains(payload.Text, "CPU: —") || !strings.Contains(payload.Text, "Uptime: —") || strings.Contains(payload.Text, "CPU: 0.00%") {
t.Fatalf("unavailable metric became a real zero: %s", payload.Text)
}
}
func TestReportReadFailureDoesNotSendAnAllZeroSuccessReport(t *testing.T) {
settings := webhookSettings(t)
calls := 0
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) { calls++ })
err := svc.SendReport(context.Background(), reportStatus{&service.Status{}}, reportInbounds{err: errors.New("private database path")})
if !errors.Is(err, ErrReport) || calls != 0 || strings.Contains(err.Error(), "private database path") {
t.Fatalf("report failure was sent or disclosed: calls=%d err=%v", calls, err)
}
}
func TestReportIncludesSubscriptionUsedAndRemainingTraffic(t *testing.T) {
for _, tc := range []struct {
name string
items []*model.Inbound
used, remaining string
}{
{"shared subscription", []*model.Inbound{
{Up: 1 << 40, ClientStats: []xray.ClientTraffic{{Email: "a", Up: 1024, Down: 2048, Total: 8192}}},
{Up: 1 << 40, ClientStats: []xray.ClientTraffic{{Email: "a", Up: 1024, Down: 2048, Total: 8192}, {Email: "b", Up: 8192, Total: 4096}}},
}, "11.00KB", "5.00KB"},
{"not configured", []*model.Inbound{{Total: 8192, ClientStats: []xray.ClientTraffic{{Email: "a", Up: 1024, Down: 2048}}}}, "3.00KB", "Quota not configured"},
{"partly configured", []*model.Inbound{{ClientStats: []xray.ClientTraffic{{Email: "a", Up: 1024, Total: 4096}, {Email: "b", Down: 2048}}}}, "3.00KB", "Quota not configured"},
} {
t.Run(tc.name, func(t *testing.T) {
settings := webhookSettings(t)
var payload Envelope
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) { _ = json.NewDecoder(r.Body).Decode(&payload) })
if err := svc.SendReport(context.Background(), reportStatus{&service.Status{}}, reportInbounds{inbounds: tc.items}); err != nil {
t.Fatal(err)
}
for _, expected := range []string{"3x-ui used traffic: " + tc.used, "3x-ui remaining traffic: " + tc.remaining} {
if !strings.Contains(payload.Text, expected) {
t.Errorf("missing %q in report: %s", expected, payload.Text)
}
}
})
}
}
func TestReportUsesNormalizedLimitsWhenNodeTrafficOmitsThem(t *testing.T) {
settings := webhookSettings(t)
db := database.GetDB()
item := model.Inbound{Enable: true, Settings: "{}"}
if err := db.Create(&item).Error; err != nil {
t.Fatal(err)
}
client := model.ClientRecord{Email: "private-client", UUID: "private-uuid", TotalGB: 8192, ExpiryTime: time.Now().UnixMilli() - 1000, Enable: true}
if err := db.Create(&client).Error; err != nil {
t.Fatal(err)
}
runtime := xray.ClientTraffic{InboundId: item.Id, Email: client.Email, Enable: true, Up: 1024, Down: 2048}
if err := db.Create(&runtime).Error; err != nil {
t.Fatal(err)
}
var payload Envelope
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) { _ = json.NewDecoder(r.Body).Decode(&payload) })
if err := svc.SendReport(context.Background(), reportStatus{&service.Status{}}, &service.InboundService{}); err != nil {
t.Fatal(err)
}
for _, expected := range []string{"3x-ui used traffic: 3.00KB", "3x-ui remaining traffic: 5.00KB", "Clients: Total: 1 | Disabled: 0 | Expired: 1 | Depleted: 0"} {
if !strings.Contains(payload.Text, expected) {
t.Errorf("report missing %q: %s", expected, payload.Text)
}
}
if strings.Contains(payload.Text, client.Email) || strings.Contains(payload.Text, client.UUID) {
t.Fatal("report disclosed client identity")
}
var saved xray.ClientTraffic
if err := db.First(&saved, runtime.Id).Error; err != nil {
t.Fatal(err)
}
if saved.Total != 0 || saved.ExpiryTime != 0 {
t.Fatal("report changed the runtime counters")
}
}
func TestReportNormalizedLimitReadFailureDoesNotSend(t *testing.T) {
settings := webhookSettings(t)
if err := database.GetDB().Migrator().DropTable(&model.ClientRecord{}); err != nil {
t.Fatal(err)
}
calls := 0
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) { calls++ })
items := []*model.Inbound{{ClientStats: []xray.ClientTraffic{{Email: "node-client", Up: 1024}}}}
err := svc.SendReport(context.Background(), reportStatus{&service.Status{}}, reportInbounds{inbounds: items})
if !errors.Is(err, ErrReport) || calls != 0 {
t.Fatalf("unavailable limits produced a successful report: calls=%d err=%v", calls, err)
}
}
func TestReportPreservesNonzeroRuntimeLimits(t *testing.T) {
settings := webhookSettings(t)
client := model.ClientRecord{Email: "node-client", TotalGB: 8192, ExpiryTime: time.Now().UnixMilli() - 1000}
if err := database.GetDB().Create(&client).Error; err != nil {
t.Fatal(err)
}
items := []*model.Inbound{{ClientStats: []xray.ClientTraffic{{Email: client.Email, Enable: true, Up: 1024, Down: 2048, Total: 4096, ExpiryTime: time.Now().Add(time.Hour).UnixMilli()}}}}
var payload Envelope
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) { _ = json.NewDecoder(r.Body).Decode(&payload) })
if err := svc.SendReport(context.Background(), reportStatus{&service.Status{}}, reportInbounds{inbounds: items}); err != nil {
t.Fatal(err)
}
if !strings.Contains(payload.Text, "3x-ui remaining traffic: 1.00KB") || !strings.Contains(payload.Text, "Clients: Total: 1 | Disabled: 0 | Expired: 0 | Depleted: 0") {
t.Fatalf("normalized limits replaced available runtime limits: %s", payload.Text)
}
}
func TestReportCaseInsensitiveClientIdentity(t *testing.T) {
for _, tc := range []struct {
name string
total int64
hasExpiry bool
remaining string
expired int
email string
statsEmail string
}{
{name: "both limits omitted", remaining: "5.00KB", expired: 1},
{name: "runtime quota preserved", total: 4096, remaining: "1.00KB", expired: 1},
{name: "runtime expiry preserved", hasExpiry: true, remaining: "5.00KB"},
{name: "both runtime limits preserved", total: 4096, hasExpiry: true, remaining: "1.00KB"},
{name: "unicode client identity", email: "ПРИВАТНЫЙ-КЛИЕНТ", remaining: "5.00KB", expired: 1},
{name: "unicode title identity", email: "Приватный-клиент", remaining: "5.00KB", expired: 1},
{name: "unicode original identity", email: "пРиВаТнЫй-КлИеНт", statsEmail: "пРиВаТнЫй-КлИеНт", remaining: "5.00KB", expired: 1},
} {
t.Run(tc.name, func(t *testing.T) {
settings := webhookSettings(t)
db := database.GetDB()
email := tc.email
if email == "" {
email = "Private-Client"
}
client := model.ClientRecord{Email: email, TotalGB: 8192, ExpiryTime: time.Now().Add(-time.Hour).UnixMilli()}
if err := db.Create(&client).Error; err != nil {
t.Fatal(err)
}
var originals []xray.ClientTraffic
statsEmails := []string{strings.ToLower(email), strings.ToUpper(email)}
if tc.statsEmail != "" {
statsEmails[0] = tc.statsEmail
}
for _, email := range statsEmails {
inbound := model.Inbound{Tag: fmt.Sprintf("casefold-%d", len(originals)), Enable: true, Settings: "{}"}
if err := db.Create(&inbound).Error; err != nil {
t.Fatal(err)
}
runtime := xray.ClientTraffic{InboundId: inbound.Id, Email: email, Enable: true, Up: 1024, Down: 2048, Total: tc.total}
if tc.hasExpiry {
runtime.ExpiryTime = time.Now().Add(time.Hour).UnixMilli()
}
if err := db.Create(&runtime).Error; err != nil {
t.Fatal(err)
}
originals = append(originals, runtime)
}
var payload Envelope
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) { _ = json.NewDecoder(r.Body).Decode(&payload) })
if err := svc.SendReport(context.Background(), reportStatus{&service.Status{}}, &service.InboundService{}); err != nil {
t.Fatal(err)
}
for _, expected := range []string{
"3x-ui used traffic: 3.00KB",
"3x-ui remaining traffic: " + tc.remaining,
fmt.Sprintf("Clients: Total: 1 | Disabled: 0 | Expired: %d | Depleted: 0", tc.expired),
} {
if !strings.Contains(payload.Text, expected) {
t.Errorf("report missing %q: %s", expected, payload.Text)
}
}
for _, original := range originals {
var saved xray.ClientTraffic
if err := db.First(&saved, original.Id).Error; err != nil {
t.Fatal(err)
}
if saved != original {
t.Errorf("report changed runtime row: got %+v, want %+v", saved, original)
}
}
})
}
}
func TestReportClientLimitsLoadsCaseInsensitiveBatch(t *testing.T) {
webhookSettings(t)
clients := make([]model.ClientRecord, 501)
stats := make([]xray.ClientTraffic, 0, 2*len(clients))
for i := range clients {
email := fmt.Sprintf("Client-%03d", i)
clients[i] = model.ClientRecord{Email: email, TotalGB: int64(i + 1), ExpiryTime: int64(i + 2)}
stats = append(stats, xray.ClientTraffic{Email: strings.ToUpper(email)}, xray.ClientTraffic{Email: strings.ToLower(email)})
}
if err := database.GetDB().CreateInBatches(&clients, 100).Error; err != nil {
t.Fatal(err)
}
const callback = "test:report_limit_parameter_budget"
db := database.GetDB()
queries := 0
if err := db.Callback().Query().After("gorm:query").Register(callback, func(tx *gorm.DB) {
if tx.Statement.Table == "clients" {
queries++
if got := len(tx.Statement.Vars); got > 500 {
t.Errorf("client limit query used %d parameters, want at most 500", got)
}
}
}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Callback().Query().Remove(callback) })
limits, err := reportClientLimits(context.Background(), []*model.Inbound{{ClientStats: stats}})
if err != nil {
t.Fatal(err)
}
if len(limits) != len(clients) {
t.Fatalf("loaded %d client limits, want %d", len(limits), len(clients))
}
if queries == 0 {
t.Fatal("test did not observe a client limit query")
}
for _, client := range clients {
if got := limits[strings.ToLower(client.Email)]; got.Email != client.Email || got.TotalGB != client.TotalGB || got.ExpiryTime != client.ExpiryTime {
t.Errorf("incorrect client limits for %q: %+v", client.Email, got)
}
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, err := reportClientLimits(ctx, []*model.Inbound{{ClientStats: stats}}); !errors.Is(err, context.Canceled) {
t.Fatalf("limit lookup ignored cancelled context: %v", err)
}
}
+171
View File
@@ -0,0 +1,171 @@
package wechat
import (
"context"
"fmt"
"math"
"strings"
"sync"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/eventbus"
"github.com/mhsanaei/3x-ui/v3/internal/logger"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
type Subscriber struct {
settings service.SettingService
service *Service
mu sync.Mutex
lastSent map[string]time.Time
now func() time.Time
}
func NewSubscriber(settings service.SettingService, svc *Service) *Subscriber {
return &Subscriber{settings: settings, service: svc, lastSent: make(map[string]time.Time), now: time.Now}
}
func (s *Subscriber) HandleEvent(event eventbus.Event) {
if s.service == nil {
return
}
enabled, err := s.settings.GetWechatEnable()
if err != nil || !enabled || !s.eventEnabled(event.Type) {
return
}
text, ok := s.format(event)
if !ok {
return
}
s.mu.Lock()
defer s.mu.Unlock()
now := s.now()
for key, sent := range s.lastSent {
if now.Sub(sent) >= time.Minute || now.Before(sent) {
delete(s.lastSent, key)
}
}
key := string(event.Type) + ":" + event.Source
if event.Type == eventbus.EventLoginAttempt {
if data := eventData[eventbus.LoginEventData](event.Data); data != nil {
key += ":" + data.Status
}
}
if sent, found := s.lastSent[key]; found && now.Sub(sent) < time.Minute {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
if err := s.service.send(ctx, "event", string(event.Type), text, event.Timestamp); err != nil {
logger.Warning("wechat subscriber: ", err)
return
}
s.lastSent[key] = s.now()
}
func (s *Subscriber) eventEnabled(kind eventbus.EventType) bool {
events, err := s.settings.GetWechatEnabledEvents()
if err != nil {
return false
}
for value := range strings.SplitSeq(events, ",") {
if strings.TrimSpace(value) == string(kind) {
return true
}
}
return false
}
func eventData[T any](value any) *T {
switch data := value.(type) {
case T:
return &data
case *T:
return data
default:
return nil
}
}
func plain(value string) string {
value = strings.Join(strings.Fields(value), " ")
runes := []rune(value)
if len(runes) > 256 {
return string(runes[:256]) + "…"
}
return string(runes)
}
func (s *Subscriber) format(event eventbus.Event) (string, bool) {
tr := s.service.translator()
var title string
fields := []string{}
if source := plain(event.Source); source != "" {
fields = append(fields, tr("discord.fields.source")+": "+source)
}
switch event.Type {
case eventbus.EventOutboundDown, eventbus.EventOutboundUp:
title = tr("discord.alerts.outboundDown")
if event.Type == eventbus.EventOutboundUp {
title = tr("discord.alerts.outboundUp")
}
if data := eventData[eventbus.OutboundHealthData](event.Data); data != nil {
if data.Error != "" {
fields = append(fields, tr("discord.fields.error")+": "+plain(data.Error))
}
if data.Delay > 0 {
fields = append(fields, fmt.Sprintf("%s: %d ms", tr("discord.fields.delay"), data.Delay))
}
}
case eventbus.EventNodeDown, eventbus.EventNodeUp:
title = tr("discord.alerts.nodeDown")
if event.Type == eventbus.EventNodeUp {
title = tr("discord.alerts.nodeUp")
}
if data := eventData[eventbus.NodeHealthData](event.Data); data != nil {
if data.XrayError != "" {
fields = append(fields, tr("discord.fields.error")+": "+plain(data.XrayError))
}
if data.LatencyMs > 0 {
fields = append(fields, fmt.Sprintf("%s: %d ms", tr("discord.fields.delay"), data.LatencyMs))
}
}
case eventbus.EventXrayCrash:
title = tr("discord.alerts.xrayCrash")
if event.Data != nil {
fields = append(fields, tr("discord.fields.error")+": "+plain(fmt.Sprint(event.Data)))
}
case eventbus.EventCPUHigh, eventbus.EventMemoryHigh:
data := eventData[eventbus.SystemMetricData](event.Data)
if data == nil || math.IsNaN(data.Percent) || math.IsInf(data.Percent, 0) {
return "", false
}
threshold, err := s.settings.GetWechatCpu()
title = tr("discord.alerts.cpuHigh")
if event.Type == eventbus.EventMemoryHigh {
threshold, err = s.settings.GetWechatMemory()
title = tr("discord.alerts.memoryHigh")
}
if err != nil || threshold <= 0 || data.Percent <= float64(threshold) {
return "", false
}
fields = append(fields, fmt.Sprintf("%s: %.2f%%; %s: %d%%", tr("usage"), data.Percent, tr("discord.fields.threshold"), threshold))
case eventbus.EventLoginAttempt:
title = tr("discord.alerts.loginFailed")
if data := eventData[eventbus.LoginEventData](event.Data); data != nil {
if data.Status == "success" {
title = tr("discord.alerts.loginSuccess")
}
fields = append(fields, tr("username")+": "+plain(data.Username), "IP: "+plain(data.IP))
if data.Reason != "" {
fields = append(fields, tr("discord.fields.reason")+": "+plain(data.Reason))
}
if data.Time != "" {
fields = append(fields, tr("discord.fields.time")+": "+plain(data.Time))
}
}
default:
return "", false
}
return strings.Join(append([]string{"3x-ui · " + title}, fields...), "\n"), true
}
@@ -0,0 +1,145 @@
package wechat
import (
"encoding/json"
"io"
"net/http"
"strings"
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/eventbus"
)
func TestSubscriberFiltersEventsAndUsesIndependentWechatThresholds(t *testing.T) {
settings := setupSettings(t, map[string]string{
"wechatEnable": "true", "wechatMode": "webhook", "wechatWebhookURL": "https://receiver.example/notify",
"wechatEnabledEvents": "cpu.high,memory.high,node.down", "wechatCpu": "80", "wechatMemory": "70",
"tgCpu": "1", "tgMemory": "1", "discordCpu": "1", "discordMemory": "1", "wechatLang": "en-US",
})
var payloads []Envelope
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) {
var payload Envelope
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
t.Error(err)
}
payloads = append(payloads, payload)
})
subscriber := NewSubscriber(settings, svc)
for _, event := range []eventbus.Event{
{Type: eventbus.EventCPUHigh, Data: eventbus.SystemMetricData{Percent: 79}},
{Type: eventbus.EventMemoryHigh, Data: &eventbus.SystemMetricData{Percent: 69}},
{Type: eventbus.EventOutboundDown, Source: "filtered"},
{Type: eventbus.EventCPUHigh, Data: eventbus.SystemMetricData{Percent: 85}},
{Type: eventbus.EventMemoryHigh, Data: &eventbus.SystemMetricData{Percent: 75}},
{Type: eventbus.EventNodeDown, Source: "node-a"},
} {
subscriber.HandleEvent(event)
}
if len(payloads) != 3 || payloads[0].Event != "cpu.high" || payloads[1].Event != "memory.high" || payloads[2].Event != "node.down" {
t.Fatalf("event filters or independent thresholds failed: %+v", payloads)
}
}
func TestSubscriberFailedSendDoesNotConsumeSuccessfulSendCooldown(t *testing.T) {
settings := setupSettings(t, map[string]string{
"wechatEnable": "true", "wechatMode": "webhook", "wechatWebhookURL": "https://receiver.example/notify",
"wechatEnabledEvents": "node.down", "wechatLang": "en-US",
})
var calls int
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) {
calls++
if calls == 1 {
w.WriteHeader(http.StatusBadRequest)
}
})
subscriber := NewSubscriber(settings, svc)
clock := time.Unix(1000, 0)
subscriber.now = func() time.Time { return clock }
event := eventbus.Event{Type: eventbus.EventNodeDown, Source: "node-a"}
subscriber.HandleEvent(event)
subscriber.HandleEvent(event)
subscriber.HandleEvent(event)
if calls != 2 {
t.Fatalf("failure consumed cooldown or success was duplicated: %d requests", calls)
}
clock = clock.Add(time.Minute)
subscriber.HandleEvent(event)
if calls != 3 {
t.Fatalf("cooldown did not expire: %d requests", calls)
}
}
func TestLoginFailureDoesNotSuppressSuccessFromTheSameIP(t *testing.T) {
settings := setupSettings(t, map[string]string{
"wechatEnable": "true", "wechatMode": "webhook", "wechatWebhookURL": "https://receiver.example/notify",
"wechatEnabledEvents": "login.attempt", "wechatLang": "en-US",
})
var texts []string
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) {
var payload Envelope
_ = json.NewDecoder(r.Body).Decode(&payload)
texts = append(texts, payload.Text)
})
subscriber := NewSubscriber(settings, svc)
for _, status := range []string{"fail", "success", "success"} {
subscriber.HandleEvent(eventbus.Event{
Type: eventbus.EventLoginAttempt, Source: "203.0.113.10",
Data: eventbus.LoginEventData{IP: "203.0.113.10", Username: "test", Status: status},
})
}
if len(texts) != 2 || !strings.Contains(texts[0], "Login Failed") || !strings.Contains(texts[1], "Login Success") {
t.Fatalf("login success was lost after failure: %q", texts)
}
}
func TestSubscriberSupportsAllNativeEventsWithoutFilesOrGlobalBotLocale(t *testing.T) {
settings := setupSettings(t, map[string]string{
"wechatEnable": "true", "wechatMode": "webhook", "wechatWebhookURL": "https://receiver.example/notify",
"wechatEnabledEvents": "outbound.down,outbound.up,node.down,node.up,xray.crash,cpu.high,memory.high,login.attempt",
"wechatCpu": "50", "wechatMemory": "50", "wechatLang": "en-US", "tgLang": "ru-RU",
})
var received []string
var texts []string
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
var payload Envelope
if err := json.Unmarshal(body, &payload); err != nil {
t.Error(err)
}
if payload.Type != "event" || payload.Text == "" || payload.ID == "" || r.Header.Get("Content-Type") != "application/json" {
t.Errorf("invalid event request: %s", body)
}
received = append(received, payload.Event)
texts = append(texts, payload.Text)
})
subscriber := NewSubscriber(settings, svc)
events := []eventbus.Event{
{Type: eventbus.EventOutboundDown, Source: "proxy-a", Data: eventbus.OutboundHealthData{Error: "connection refused"}},
{Type: eventbus.EventOutboundUp, Source: "proxy-a", Data: &eventbus.OutboundHealthData{Delay: 18}},
{Type: eventbus.EventNodeDown, Source: "node-a", Data: &eventbus.NodeHealthData{XrayError: "stopped"}},
{Type: eventbus.EventNodeUp, Source: "node-a", Data: eventbus.NodeHealthData{LatencyMs: 20}},
{Type: eventbus.EventXrayCrash, Data: "process exited"},
{Type: eventbus.EventCPUHigh, Data: eventbus.SystemMetricData{Percent: 90}},
{Type: eventbus.EventMemoryHigh, Data: eventbus.SystemMetricData{Percent: 90}},
{Type: eventbus.EventLoginAttempt, Source: "203.0.113.10", Data: eventbus.LoginEventData{Username: "test", IP: "203.0.113.10", Status: "success"}},
}
for _, event := range events {
subscriber.HandleEvent(event)
}
if len(received) != 8 {
t.Fatalf("expected all eight event types, got %v", received)
}
for i, event := range events {
if received[i] != string(event.Type) {
t.Fatalf("event %d became %q", i, received[i])
}
}
if !strings.Contains(texts[4], "Xray Core Crashed") {
t.Fatalf("Telegram's global Russian locale changed WeChat text: %s", texts[4])
}
}
+237
View File
@@ -0,0 +1,237 @@
package wechat
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
"github.com/mhsanaei/3x-ui/v3/internal/web/locale"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
var (
ErrConfiguration = errors.New("wechat notification configuration is invalid")
ErrDelivery = errors.New("wechat notification delivery failed")
ErrTooLong = errors.New("wechat notification exceeds the text limit")
)
type Envelope struct {
Version int `json:"version"`
ID string `json:"id"`
Type string `json:"type"`
Event string `json:"event"`
Hostname string `json:"hostname"`
OccurredAt string `json:"occurred_at"`
Text string `json:"text"`
}
type Service struct {
settings service.SettingService
httpClient *http.Client
sendGate chan struct{}
lastSend time.Time
sendInterval time.Duration
retryWait func(context.Context, time.Duration) error
}
func NewService(settings service.SettingService) *Service {
return &Service{
settings: settings, sendInterval: 3100 * time.Millisecond, retryWait: waitContext,
sendGate: make(chan struct{}, 1),
httpClient: &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
Proxy: nil, DialContext: netsafe.SSRFGuardedDialContext,
TLSHandshakeTimeout: 5 * time.Second, ResponseHeaderTimeout: 5 * time.Second,
IdleConnTimeout: 30 * time.Second,
},
},
}
}
func (s *Service) client() *http.Client {
client := s.httpClient
if client == nil {
client = NewService(s.settings).httpClient
}
copy := *client
copy.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
if copy.Timeout <= 0 || copy.Timeout > 10*time.Second {
copy.Timeout = 10 * time.Second
}
return &copy
}
func waitContext(ctx context.Context, duration time.Duration) error {
timer := time.NewTimer(max(0, duration))
defer timer.Stop()
select {
case <-timer.C:
return nil
case <-ctx.Done():
return ErrDelivery
}
}
func (s *Service) configuration() (string, string, string, error) {
settings, err := s.settings.GetWechatDeliverySettings()
if err != nil || !settings.Enabled {
return "", "", "", ErrConfiguration
}
if strings.TrimSpace(settings.WebhookURL) == "" {
return "", "", "", ErrConfiguration
}
endpoint, err := service.ValidateWechatDestination(settings.Mode, settings.WebhookURL)
if err != nil {
return "", "", "", ErrConfiguration
}
if len(settings.Token) > 4096 || strings.ContainsAny(settings.Token, "\r\n") {
return "", "", "", ErrConfiguration
}
return settings.Mode, endpoint, strings.TrimSpace(settings.Token), nil
}
func (s *Service) send(ctx context.Context, kind, event, text string, occurredAt time.Time) error {
if ctx == nil {
ctx = context.Background()
}
ctx = netsafe.ContextWithAllowPrivate(ctx, false)
mode, endpoint, token, err := s.configuration()
if err != nil {
return err
}
if occurredAt.IsZero() {
occurredAt = time.Now()
}
hostname, _ := os.Hostname()
if hostname == "" {
hostname = "3x-ui"
}
text = "3x-ui · " + plain(hostname) + "\n" + text
if !utf8.ValidString(text) || len(text) > 20480 {
return ErrTooLong
}
if mode == "webhook" {
body, err := json.Marshal(Envelope{
Version: 1, ID: uuid.NewString(), Type: kind, Event: event, Hostname: hostname,
OccurredAt: occurredAt.UTC().Format(time.RFC3339), Text: text,
})
if err != nil {
return ErrDelivery
}
return s.sendWebhook(ctx, endpoint, token, body)
}
pieces, err := splitText(text)
if err != nil {
return err
}
select {
case s.sendGate <- struct{}{}:
defer func() { <-s.sendGate }()
case <-ctx.Done():
return ErrDelivery
}
for _, piece := range pieces {
if err := s.retryWait(ctx, s.sendInterval-time.Since(s.lastSend)); err != nil {
return ErrDelivery
}
body, err := json.Marshal(map[string]any{"msgtype": "text", "text": map[string]string{"content": piece}})
if err != nil {
return ErrDelivery
}
s.lastSend = time.Now()
_, response, err := s.post(ctx, endpoint, "", body)
if err != nil {
return ErrDelivery
}
var result struct {
Errcode *int `json:"errcode"`
}
if json.Unmarshal(response, &result) != nil || result.Errcode == nil || *result.Errcode != 0 {
return ErrDelivery
}
}
return nil
}
func splitText(text string) ([]string, error) {
var result []string
for len(text) > 2048 {
cut := 2048
for !utf8.RuneStart(text[cut]) {
cut--
}
result = append(result, text[:cut])
text = text[cut:]
}
if text != "" {
result = append(result, text)
}
if len(result) > 10 {
return nil, ErrTooLong
}
return result, nil
}
func (s *Service) sendWebhook(ctx context.Context, endpoint, token string, body []byte) error {
for attempt := range 2 {
status, _, err := s.post(ctx, endpoint, token, body)
if err == nil {
return nil
}
if attempt == 1 || (status != 0 && status < 500) || ctx.Err() != nil {
return ErrDelivery
}
if s.retryWait(ctx, time.Second) != nil {
return ErrDelivery
}
}
return ErrDelivery
}
func (s *Service) post(ctx context.Context, endpoint, token string, body []byte) (int, []byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
if err != nil {
return 0, nil, ErrDelivery
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "3x-ui-WeChat/1")
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
response, err := s.client().Do(req)
if err != nil {
return 0, nil, ErrDelivery
}
defer response.Body.Close()
data, err := io.ReadAll(io.LimitReader(response.Body, 4097))
if err != nil || response.StatusCode < 200 || response.StatusCode >= 300 {
return response.StatusCode, nil, ErrDelivery
}
return response.StatusCode, data, nil
}
func (s *Service) translator() func(string, ...string) string {
lang, err := s.settings.GetWechatLang()
if err != nil || lang == "" {
lang = "en-US"
}
return func(key string, params ...string) string { return locale.I18nForLang(lang, key, params...) }
}
func (s *Service) SendTest() error {
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
tr := s.translator()
return s.send(ctx, "test", "test", tr("wechat.test.title")+"\n"+tr("wechat.test.body"), time.Now())
}
+358
View File
@@ -0,0 +1,358 @@
package wechat
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"unicode/utf8"
"gorm.io/gorm"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/util/netsafe"
"github.com/mhsanaei/3x-ui/v3/internal/web/locale"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
type botLanguage struct{}
func (botLanguage) GetTgLang() (string, error) { return "ru-RU", nil }
func TestMain(main *testing.M) {
if err := locale.InitLocalizer(os.DirFS("../.."), botLanguage{}); err != nil {
panic(err)
}
os.Exit(main.Run())
}
func setupSettings(t *testing.T, values map[string]string) service.SettingService {
t.Helper()
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
for key, value := range values {
if err := database.GetDB().Where("key = ?", key).Delete(&model.Setting{}).Error; err != nil {
t.Fatal(err)
}
if err := database.GetDB().Create(&model.Setting{Key: key, Value: value}).Error; err != nil {
t.Fatal(err)
}
}
return service.SettingService{}
}
func localReceiver(t *testing.T, handler http.HandlerFunc) *http.Client {
t.Helper()
receiver := httptest.NewTLSServer(handler)
t.Cleanup(receiver.Close)
client := receiver.Client()
transport := client.Transport.(*http.Transport)
transport.TLSClientConfig.ServerName = "example.com"
transport.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, network, receiver.Listener.Addr().String())
}
return client
}
func webhookSettings(t *testing.T) service.SettingService {
t.Helper()
return setupSettings(t, map[string]string{
"wechatEnable": "true", "wechatMode": "webhook", "wechatWebhookURL": "https://receiver.example/notify",
"wechatToken": "test-secret", "wechatLang": "en-US", "wechatReportEnable": "true",
})
}
func TestWebhookRetriesKeepOneEnvelopeIdentityAndBearerCredential(t *testing.T) {
settings := webhookSettings(t)
var bodies [][]byte
svc := NewService(settings)
svc.retryWait = func(context.Context, time.Duration) error { return nil }
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost || r.URL.Path != "/notify" || r.Header.Get("Authorization") != "Bearer test-secret" {
t.Errorf("unexpected request: %s %s auth=%q", r.Method, r.URL.Path, r.Header.Get("Authorization"))
}
body, _ := io.ReadAll(r.Body)
bodies = append(bodies, body)
if len(bodies) == 1 {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusAccepted)
})
if err := svc.SendTest(); err != nil {
t.Fatal(err)
}
if len(bodies) != 2 || string(bodies[0]) != string(bodies[1]) {
t.Fatalf("retry changed envelope or was unbounded: %q", bodies)
}
var payload Envelope
if err := json.Unmarshal(bodies[0], &payload); err != nil {
t.Fatal(err)
}
if payload.Version != 1 || payload.Type != "test" || payload.Event != "test" || len(payload.ID) != 36 || payload.Hostname == "" || !strings.Contains(payload.Text, "3x-ui") {
t.Fatalf("invalid webhook contract: %+v", payload)
}
if _, err := time.Parse(time.RFC3339, payload.OccurredAt); err != nil {
t.Fatalf("invalid event timestamp: %q", payload.OccurredAt)
}
}
func TestWebhookCredentialRotationKeepsDestinationAndTokenTogether(t *testing.T) {
settings := webhookSettings(t)
db := database.GetDB()
var rotated atomic.Bool
const callback = "test:rotate_wechat_destination"
if err := db.Callback().Query().After("gorm:query").Register(callback, func(tx *gorm.DB) {
if !strings.Contains(fmt.Sprint(tx.Statement.Vars), "wechatWebhookURL") || !rotated.CompareAndSwap(false, true) {
return
}
if err := db.Exec("UPDATE settings SET value = CASE key WHEN 'wechatWebhookURL' THEN ? WHEN 'wechatToken' THEN ? ELSE value END WHERE key IN (?, ?)",
"https://new-receiver.example/notify", "new-secret", "wechatWebhookURL", "wechatToken").Error; err != nil {
t.Error(err)
}
}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Callback().Query().Remove(callback) })
svc := NewService(settings)
var destination, credential string
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) {
destination, credential = r.Host, r.Header.Get("Authorization")
})
if err := svc.SendTest(); err != nil {
t.Fatal(err)
}
if !rotated.Load() {
t.Fatal("test did not rotate the saved destination")
}
if destination != "receiver.example" || credential != "Bearer test-secret" {
t.Fatalf("credential rotation mixed snapshots: destination=%q credential=%q", destination, credential)
}
}
func TestWecomSplitsOnlyAtUTF8BoundariesAndConfirmsErrcode(t *testing.T) {
settings := setupSettings(t, map[string]string{
"wechatEnable": "true", "wechatMode": "wecom", "wechatWebhookURL": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test-key",
})
var pieces []string
svc := NewService(settings)
svc.retryWait = func(context.Context, time.Duration) error { return nil }
svc.sendInterval = 0
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) {
var payload struct {
MsgType string `json:"msgtype"`
Text struct {
Content string `json:"content"`
} `json:"text"`
}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
t.Error(err)
}
if payload.MsgType != "text" || len(payload.Text.Content) > 2048 || !utf8.ValidString(payload.Text.Content) {
t.Errorf("invalid WeCom segment: %q", payload.Text.Content)
}
if r.Header.Get("Authorization") != "" {
t.Error("WeCom must not receive custom webhook bearer credentials")
}
pieces = append(pieces, payload.Text.Content)
_, _ = io.WriteString(w, `{"errcode":0}`)
})
text := strings.Repeat("汉🙂", 600)
if err := svc.send(context.Background(), "event", "node.down", text, time.Now()); err != nil {
t.Fatal(err)
}
if len(pieces) != 3 || !strings.HasSuffix(strings.Join(pieces, ""), "\n"+text) || !strings.HasPrefix(pieces[0], "3x-ui · ") {
t.Fatalf("segments lost text: count=%d", len(pieces))
}
}
func TestWecomRejectedResponseIsNotReportedAsSuccessOrRetried(t *testing.T) {
settings := setupSettings(t, map[string]string{
"wechatEnable": "true", "wechatMode": "wecom", "wechatWebhookURL": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=private-key",
})
var calls int
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) {
calls++
_, _ = io.WriteString(w, `{"errcode":45009,"errmsg":"private-key rejected"}`)
})
err := svc.SendTest()
if !errors.Is(err, ErrDelivery) || calls != 1 || strings.Contains(err.Error(), "private-key") {
t.Fatalf("provider rejection or privacy failure: calls=%d err=%v", calls, err)
}
}
func TestInvalidDestinationNeverReachesTheNetwork(t *testing.T) {
cases := []struct{ mode, url string }{
{"webhook", "http://receiver.example/hook"},
{"webhook", "https://127.0.0.1/hook"},
{"webhook", "https://169.254.169.254/latest"},
{"webhook", "https://[::1]/hook"},
{"webhook", "https://user:pass@receiver.example/hook"},
{"webhook", "https://receiver.example/hook#fragment"},
{"wecom", "https://receiver.example/cgi-bin/webhook/send?key=secret"},
{"wecom", "https://qyapi.weixin.qq.com/other?key=secret"},
{"wecom", "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=secret&other=value"},
}
for _, tc := range cases {
t.Run(tc.mode+tc.url, func(t *testing.T) {
settings := setupSettings(t, map[string]string{"wechatEnable": "true", "wechatMode": tc.mode, "wechatWebhookURL": tc.url})
var called atomic.Bool
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) { called.Store(true) })
if err := svc.SendTest(); !errors.Is(err, ErrConfiguration) || called.Load() {
t.Fatalf("invalid destination reached network: called=%v err=%v", called.Load(), err)
}
})
}
}
func TestRedirectCannotForwardBearerCredentials(t *testing.T) {
settings := webhookSettings(t)
var calls int
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) {
calls++
w.Header().Set("Location", "https://other.example/stolen")
w.WriteHeader(http.StatusTemporaryRedirect)
})
if err := svc.SendTest(); !errors.Is(err, ErrDelivery) || calls != 1 {
t.Fatalf("redirect followed or accepted: calls=%d err=%v", calls, err)
}
}
func TestDNSResolutionToLoopbackIsBlockedAtDial(t *testing.T) {
listener, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = listener.Close() })
go func() {
for {
buffer := make([]byte, 1024)
count, peer, err := listener.ReadFrom(buffer)
if err != nil {
return
}
query := buffer[:count]
if len(query) < 17 {
continue
}
end := 12
for end < len(query) && query[end] != 0 {
end += int(query[end]) + 1
}
if end+5 > len(query) {
continue
}
end += 5
answer := append([]byte(nil), query[:end]...)
answer[2], answer[3], answer[6], answer[7] = 0x81, 0x80, 0, 0
answer[10], answer[11] = 0, 0
if query[end-4] == 0 && query[end-3] == 1 {
answer[7] = 1
answer = append(answer, 0xc0, 0x0c, 0, 1, 0, 1, 0, 0, 0, 0, 0, 4, 127, 0, 0, 1)
}
_, _ = listener.WriteTo(answer, peer)
}
}()
previous := net.DefaultResolver
net.DefaultResolver = &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, "udp", listener.LocalAddr().String())
}}
t.Cleanup(func() { net.DefaultResolver = previous })
settings := setupSettings(t, map[string]string{"wechatEnable": "true", "wechatMode": "webhook", "wechatWebhookURL": "https://receiver-dns.example/hook"})
svc := NewService(settings)
svc.retryWait = func(context.Context, time.Duration) error { return nil }
dial := svc.httpClient.Transport.(*http.Transport).DialContext
if _, err := dial(context.Background(), "tcp", "receiver-dns.example:443"); !errors.Is(err, netsafe.ErrPrivateAddressBlocked) {
t.Fatalf("DNS rebinding bypassed guarded dial: %v", err)
}
if err := svc.SendTest(); !errors.Is(err, ErrDelivery) || strings.Contains(err.Error(), "receiver-dns") {
t.Fatalf("guard or redaction failed: %v", err)
}
}
func TestWecomPacingHonorsCancellationAndDoesNotSendAnExtraMessage(t *testing.T) {
settings := setupSettings(t, map[string]string{
"wechatEnable": "true", "wechatMode": "wecom", "wechatWebhookURL": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test-key",
})
var requests int
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) {
requests++
_, _ = io.WriteString(w, `{"errcode":0}`)
})
if err := svc.SendTest(); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Millisecond)
defer cancel()
err := svc.send(ctx, "event", "node.down", "second message", time.Now())
if !errors.Is(err, ErrDelivery) || requests != 1 {
t.Fatalf("pacing ignored cancellation: requests=%d err=%v", requests, err)
}
}
func TestWecomQueuedRequestCanCancelWhileAnotherReportOwnsTheSendGate(t *testing.T) {
settings := setupSettings(t, map[string]string{
"wechatEnable": "true", "wechatMode": "wecom", "wechatWebhookURL": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test-key",
})
var requests atomic.Int32
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) { requests.Add(1) })
svc.sendGate <- struct{}{}
defer func() { <-svc.sendGate }()
ctx, cancel := context.WithCancel(context.Background())
cancel()
result := make(chan error, 1)
go func() { result <- svc.send(ctx, "event", "node.down", "queued event", time.Now()) }()
select {
case err := <-result:
if !errors.Is(err, ErrDelivery) || requests.Load() != 0 {
t.Fatalf("cancelled request reached receiver: count=%d err=%v", requests.Load(), err)
}
case <-time.After(time.Second):
t.Fatal("cancelled event remained blocked behind the report")
}
}
func TestWebhookFailuresStopAfterOneRetryAndDoNotDiscloseResponseBody(t *testing.T) {
settings := webhookSettings(t)
var requests int
svc := NewService(settings)
svc.retryWait = func(context.Context, time.Duration) error { return nil }
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) {
requests++
w.WriteHeader(http.StatusServiceUnavailable)
_, _ = io.WriteString(w, "secret-response-body")
})
err := svc.SendTest()
if !errors.Is(err, ErrDelivery) || requests != 2 || strings.Contains(err.Error(), "secret") {
t.Fatalf("unbounded retries or response disclosure: requests=%d err=%v", requests, err)
}
}
func TestOversizedWecomMessageFailsBeforePartialDelivery(t *testing.T) {
settings := setupSettings(t, map[string]string{
"wechatEnable": "true", "wechatMode": "wecom", "wechatWebhookURL": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test-key",
})
var requests int
svc := NewService(settings)
svc.httpClient = localReceiver(t, func(w http.ResponseWriter, r *http.Request) { requests++ })
err := svc.send(context.Background(), "report", "report", strings.Repeat("字", 7000), time.Now())
if !errors.Is(err, ErrTooLong) || requests != 0 {
t.Fatalf("oversize caused partial notification: requests=%d err=%v", requests, err)
}
}
+40 -1
View File
@@ -1911,7 +1911,33 @@
"subHostSortMode": "ترتيب عقد الاشتراك",
"subHostSortInbound": "ترتيب الاتصالات الواردة (الافتراضي)",
"subHostSortHosts": "ترتيب المضيفين",
"subHostSortModeDesc": "يتبع ترتيب المضيفين صفحة المضيفين عبر جميع الاتصالات الواردة. يحدد هذا ترتيب مخرجات الخادم؛ وقد تطبق تطبيقات العميل ترتيبًا آخر."
"subHostSortModeDesc": "يتبع ترتيب المضيفين صفحة المضيفين عبر جميع الاتصالات الواردة. يحدد هذا ترتيب مخرجات الخادم؛ وقد تطبق تطبيقات العميل ترتيبًا آخر.",
"wechatSettings": "إشعارات WeChat",
"wechatEnable": "تفعيل إشعارات WeChat",
"wechatEnableDesc": "إرسال تنبيهات عبر روبوت مجموعة WeCom أو بوابة webhook متوافقة.",
"wechatMode": "طريقة الإرسال",
"wechatModeDesc": "اختر تنسيق الرسائل الذي تدعمه الوجهة.",
"wechatModeWecom": "روبوت مجموعة WeCom",
"wechatModeWebhook": "بوابة webhook مخصصة",
"wechatPersonalGateway": "يتطلب WeChat الشخصي بوابة متوافقة. يرسل روبوت WeCom إلى مجموعات WeCom وليس مباشرة إلى WeChat الشخصي.",
"wechatWebhookURL": "عنوان webhook",
"wechatWebhookURLConfigured": "تم حفظ العنوان. اترك الحقل فارغًا للاحتفاظ به.",
"wechatWebhookURLDesc": "استخدم وجهة HTTPS. قد يحتوي العنوان على سر ولا تعيد اللوحة القيمة المحفوظة.",
"wechatSecretPlaceholder": "اتركه فارغًا للاحتفاظ بالقيمة المحفوظة",
"wechatToken": "رمز Bearer",
"wechatTokenConfigured": "تم حفظ الرمز. اترك الحقل فارغًا للاحتفاظ به.",
"wechatTokenDesc": "مصادقة اختيارية للبوابة. اتركه فارغًا إذا لم تكن مطلوبة.",
"wechatLanguage": "لغة الرسائل",
"wechatSaveBeforeTest": "احفظ التغييرات قبل الاختبار. يستخدم الاختبار الإعدادات المحفوظة.",
"wechatTest": "إرسال إشعار تجريبي",
"wechatTestSuccess": "تم إرسال الإشعار التجريبي بنجاح",
"wechatTestFailed": "تعذر إرسال الإشعار التجريبي",
"wechatReportEnable": "تقارير مجدولة",
"wechatReportEnableDesc": "إرسال ملخصات نصية دورية مستقلة عن التنبيهات. لا تُرفق قواعد البيانات أو ملفات الإعداد.",
"wechatReportTime": "جدول التقارير",
"wechatReportTimeDesc": "استخدم تعبير cron أو إعدادًا مثل @daily.",
"wechatEvents": "تنبيهات الأحداث",
"wechatEventsDesc": "اختر الأحداث التي ترسل إشعارات واضبط حدود التنبيه."
},
"xray": {
"save": "احفظ",
@@ -2943,5 +2969,18 @@
"restartXray": "إعادة تشغيل خدمة Xray",
"restartXraySuccess": "تمت إعادة تشغيل خدمة Xray بنجاح",
"settings": "الإعدادات"
},
"wechat": {
"test": {
"title": "اختبار إشعارات WeChat من 3x-ui",
"body": "هذا إشعار تجريبي من 3x-ui. لا يتضمن أي ملفات لقاعدة البيانات أو الإعدادات."
},
"report": {
"title": "تقرير حالة 3x-ui",
"counts": "الإجمالي: {{ .Total }} | معطل: {{ .Disabled }} | منتهي الصلاحية: {{ .Expired }} | مستنفد: {{ .Depleted }}",
"trafficUsed": "حركة البيانات المستخدمة في 3x-ui",
"trafficRemaining": "حركة البيانات المتبقية في 3x-ui",
"trafficQuotaUnset": "لم يتم إعداد الحصة"
}
}
}
+40 -1
View File
@@ -2032,7 +2032,33 @@
"subHostSortMode": "Subscription Node Ordering",
"subHostSortInbound": "Inbound order (default)",
"subHostSortHosts": "Hosts order",
"subHostSortModeDesc": "Hosts order follows the Hosts page across inbounds. This controls the order emitted by the server; client apps may apply their own sorting."
"subHostSortModeDesc": "Hosts order follows the Hosts page across inbounds. This controls the order emitted by the server; client apps may apply their own sorting.",
"wechatSettings": "WeChat notifications",
"wechatEnable": "Enable WeChat notifications",
"wechatEnableDesc": "Deliver panel alerts through a WeCom group robot or compatible webhook gateway.",
"wechatMode": "Delivery mode",
"wechatModeDesc": "Choose the message format accepted by your destination.",
"wechatModeWecom": "WeCom group robot",
"wechatModeWebhook": "Custom webhook gateway",
"wechatPersonalGateway": "Personal WeChat requires a compatible gateway. A WeCom robot posts to a WeCom group, not directly to personal WeChat.",
"wechatWebhookURL": "Webhook URL",
"wechatWebhookURLConfigured": "A webhook URL is saved. Leave this field blank to keep it.",
"wechatWebhookURLDesc": "Use an HTTPS destination. The URL may contain a secret and is never returned by the panel.",
"wechatSecretPlaceholder": "Leave blank to keep the saved value",
"wechatToken": "Bearer token",
"wechatTokenConfigured": "A bearer token is saved. Leave this field blank to keep it.",
"wechatTokenDesc": "Optional authentication for the custom gateway. Leave blank if the destination does not require it.",
"wechatLanguage": "Message language",
"wechatSaveBeforeTest": "Save changes before testing. The test uses the saved configuration.",
"wechatTest": "Send test notification",
"wechatTestSuccess": "Test notification sent successfully",
"wechatTestFailed": "Failed to send test notification",
"wechatReportEnable": "Scheduled reports",
"wechatReportEnableDesc": "Send a periodic text summary independently of event alerts. Database and configuration files are not attached.",
"wechatReportTime": "Report schedule",
"wechatReportTimeDesc": "Use a cron expression or a preset such as @daily.",
"wechatEvents": "Event alerts",
"wechatEventsDesc": "Choose which panel events send WeChat notifications and set the alert thresholds."
},
"xray": {
"save": "Save",
@@ -2943,5 +2969,18 @@
"restartXray": "Restart Xray Service",
"restartXraySuccess": "Xray has been successfully relaunched",
"settings": "Settings"
},
"wechat": {
"test": {
"title": "3x-ui WeChat Notification Test",
"body": "This is a test notification from 3x-ui. No database or configuration files are included."
},
"report": {
"title": "3x-ui Status Report",
"counts": "Total: {{ .Total }} | Disabled: {{ .Disabled }} | Expired: {{ .Expired }} | Depleted: {{ .Depleted }}",
"trafficUsed": "3x-ui used traffic",
"trafficRemaining": "3x-ui remaining traffic",
"trafficQuotaUnset": "Quota not configured"
}
}
}
+40 -1
View File
@@ -1911,7 +1911,33 @@
"subHostSortMode": "Orden de nodos de suscripción",
"subHostSortInbound": "Orden de entradas (predeterminado)",
"subHostSortHosts": "Orden de hosts",
"subHostSortModeDesc": "Sigue el orden de la página de hosts entre distintas entradas. Determina el orden emitido por el servidor; las aplicaciones cliente pueden aplicar su propio orden."
"subHostSortModeDesc": "Sigue el orden de la página de hosts entre distintas entradas. Determina el orden emitido por el servidor; las aplicaciones cliente pueden aplicar su propio orden.",
"wechatSettings": "Notificaciones de WeChat",
"wechatEnable": "Activar notificaciones de WeChat",
"wechatEnableDesc": "Envía alertas mediante un robot de grupo de WeCom o una pasarela webhook compatible.",
"wechatMode": "Modo de envío",
"wechatModeDesc": "Elige el formato que admite el destino.",
"wechatModeWecom": "Robot de grupo de WeCom",
"wechatModeWebhook": "Pasarela webhook personalizada",
"wechatPersonalGateway": "WeChat personal necesita una pasarela compatible. El robot de WeCom envía a grupos de WeCom, no directamente a WeChat personal.",
"wechatWebhookURL": "URL del webhook",
"wechatWebhookURLConfigured": "Hay una URL guardada. Déjala vacía para conservarla.",
"wechatWebhookURLDesc": "Usa un destino HTTPS. La URL puede contener un secreto y el panel nunca devuelve el valor guardado.",
"wechatSecretPlaceholder": "Dejar vacío para conservar el valor",
"wechatToken": "Token Bearer",
"wechatTokenConfigured": "Hay un token guardado. Déjalo vacío para conservarlo.",
"wechatTokenDesc": "Autenticación opcional de la pasarela. Déjalo vacío si no es necesaria.",
"wechatLanguage": "Idioma de los mensajes",
"wechatSaveBeforeTest": "Guarda los cambios antes de probar. La prueba usa la configuración guardada.",
"wechatTest": "Enviar notificación de prueba",
"wechatTestSuccess": "Notificación de prueba enviada correctamente",
"wechatTestFailed": "No se pudo enviar la notificación de prueba",
"wechatReportEnable": "Informes programados",
"wechatReportEnableDesc": "Envía resúmenes de texto periódicos aparte de las alertas. No adjunta bases de datos ni archivos de configuración.",
"wechatReportTime": "Horario del informe",
"wechatReportTimeDesc": "Usa una expresión cron o un valor como @daily.",
"wechatEvents": "Alertas de eventos",
"wechatEventsDesc": "Elige los eventos que envían notificaciones y sus umbrales."
},
"xray": {
"save": "Guardar configuración",
@@ -2943,5 +2969,18 @@
"restartXray": "Reiniciar servicio Xray",
"restartXraySuccess": "El servicio Xray se ha reiniciado con éxito",
"settings": "Configuración"
},
"wechat": {
"test": {
"title": "Prueba de notificación de WeChat de 3x-ui",
"body": "Esta es una notificación de prueba de 3x-ui. No incluye archivos de base de datos ni de configuración."
},
"report": {
"title": "Informe de estado de 3x-ui",
"counts": "Total: {{ .Total }} | Deshabilitados: {{ .Disabled }} | Caducados: {{ .Expired }} | Agotados: {{ .Depleted }}",
"trafficUsed": "Tráfico usado de 3x-ui",
"trafficRemaining": "Tráfico restante de 3x-ui",
"trafficQuotaUnset": "Cuota no configurada"
}
}
}
+40 -1
View File
@@ -1911,7 +1911,33 @@
"subHostSortMode": "ترتیب گره‌های اشتراک",
"subHostSortInbound": "ترتیب ورودی‌ها (پیش‌فرض)",
"subHostSortHosts": "ترتیب میزبان‌ها",
"subHostSortModeDesc": "ترتیب میزبان‌ها در صفحهٔ میزبان‌ها، میان همهٔ ورودی‌ها اعمال می‌شود. این تنظیم ترتیب خروجی سرور را تعیین می‌کند؛ برنامهٔ کلاینت ممکن است ترتیب دیگری اعمال کند."
"subHostSortModeDesc": "ترتیب میزبان‌ها در صفحهٔ میزبان‌ها، میان همهٔ ورودی‌ها اعمال می‌شود. این تنظیم ترتیب خروجی سرور را تعیین می‌کند؛ برنامهٔ کلاینت ممکن است ترتیب دیگری اعمال کند.",
"wechatSettings": "اعلان‌های وی‌چت",
"wechatEnable": "فعال‌سازی اعلان‌های وی‌چت",
"wechatEnableDesc": "ارسال هشدار از طریق ربات گروه WeCom یا درگاه وب‌هوک سازگار.",
"wechatMode": "روش ارسال",
"wechatModeDesc": "قالب پیام پشتیبانی‌شده توسط مقصد را انتخاب کنید.",
"wechatModeWecom": "ربات گروه WeCom",
"wechatModeWebhook": "درگاه وب‌هوک سفارشی",
"wechatPersonalGateway": "وی‌چت شخصی به درگاه سازگار نیاز دارد. ربات WeCom به گروه WeCom ارسال می‌کند، نه مستقیماً به وی‌چت شخصی.",
"wechatWebhookURL": "نشانی وب‌هوک",
"wechatWebhookURLConfigured": "نشانی ذخیره شده است. برای حفظ آن، خالی بگذارید.",
"wechatWebhookURLDesc": "از مقصد HTTPS استفاده کنید. نشانی ممکن است محرمانه باشد و پنل مقدار ذخیره‌شده را نمایش نمی‌دهد.",
"wechatSecretPlaceholder": "برای حفظ مقدار ذخیره‌شده خالی بگذارید",
"wechatToken": "توکن Bearer",
"wechatTokenConfigured": "توکن ذخیره شده است. برای حفظ آن خالی بگذارید.",
"wechatTokenDesc": "احراز هویت اختیاری درگاه. در صورت عدم نیاز خالی بگذارید.",
"wechatLanguage": "زبان پیام",
"wechatSaveBeforeTest": "پیش از آزمایش، تغییرات را ذخیره کنید. آزمایش از تنظیمات ذخیره‌شده استفاده می‌کند.",
"wechatTest": "ارسال اعلان آزمایشی",
"wechatTestSuccess": "اعلان آزمایشی با موفقیت ارسال شد",
"wechatTestFailed": "ارسال اعلان آزمایشی ناموفق بود",
"wechatReportEnable": "گزارش‌های زمان‌بندی‌شده",
"wechatReportEnableDesc": "خلاصه متنی دوره‌ای مستقل از هشدارها ارسال می‌شود. پایگاه داده یا فایل تنظیمات پیوست نمی‌شود.",
"wechatReportTime": "زمان‌بندی گزارش",
"wechatReportTimeDesc": "از عبارت cron یا پیش‌تنظیمی مانند @daily استفاده کنید.",
"wechatEvents": "هشدارهای رویداد",
"wechatEventsDesc": "رویدادهای ارسال اعلان و آستانه هشدار را انتخاب کنید."
},
"xray": {
"save": "ذخیره",
@@ -2943,5 +2969,18 @@
"restartXray": "راه‌اندازی مجدد سرویس Xray",
"restartXraySuccess": "سرویس Xray با موفقیت مجدداً راه‌اندازی شد",
"settings": "تنظیمات"
},
"wechat": {
"test": {
"title": "آزمایش اعلان وی‌چت 3x-ui",
"body": "این یک اعلان آزمایشی از 3x-ui است. هیچ فایل پایگاه داده یا پیکربندی ضمیمه نشده است."
},
"report": {
"title": "گزارش وضعیت 3x-ui",
"counts": "کل: {{ .Total }} | غیرفعال: {{ .Disabled }} | منقضی: {{ .Expired }} | تمام‌شده: {{ .Depleted }}",
"trafficUsed": "ترافیک مصرف‌شده 3x-ui",
"trafficRemaining": "ترافیک باقی‌مانده 3x-ui",
"trafficQuotaUnset": "سهمیه تنظیم نشده است"
}
}
}
+40 -1
View File
@@ -1911,7 +1911,33 @@
"subHostSortMode": "Urutan node langganan",
"subHostSortInbound": "Urutan inbound (bawaan)",
"subHostSortHosts": "Urutan host",
"subHostSortModeDesc": "Mengikuti urutan di halaman Host untuk semua inbound. Ini menentukan urutan keluaran server; aplikasi klien dapat menerapkan urutan sendiri."
"subHostSortModeDesc": "Mengikuti urutan di halaman Host untuk semua inbound. Ini menentukan urutan keluaran server; aplikasi klien dapat menerapkan urutan sendiri.",
"wechatSettings": "Notifikasi WeChat",
"wechatEnable": "Aktifkan notifikasi WeChat",
"wechatEnableDesc": "Kirim peringatan melalui robot grup WeCom atau gateway webhook yang kompatibel.",
"wechatMode": "Mode pengiriman",
"wechatModeDesc": "Pilih format pesan yang didukung tujuan.",
"wechatModeWecom": "Robot grup WeCom",
"wechatModeWebhook": "Gateway webhook khusus",
"wechatPersonalGateway": "WeChat pribadi memerlukan gateway yang kompatibel. Robot WeCom mengirim ke grup WeCom, bukan langsung ke WeChat pribadi.",
"wechatWebhookURL": "URL webhook",
"wechatWebhookURLConfigured": "URL sudah disimpan. Kosongkan untuk mempertahankannya.",
"wechatWebhookURLDesc": "Gunakan tujuan HTTPS. URL mungkin berisi rahasia dan nilai tersimpan tidak dikembalikan oleh panel.",
"wechatSecretPlaceholder": "Kosongkan untuk mempertahankan nilai tersimpan",
"wechatToken": "Token Bearer",
"wechatTokenConfigured": "Token sudah disimpan. Kosongkan untuk mempertahankannya.",
"wechatTokenDesc": "Autentikasi gateway opsional. Kosongkan jika tidak diperlukan.",
"wechatLanguage": "Bahasa pesan",
"wechatSaveBeforeTest": "Simpan perubahan sebelum menguji. Pengujian memakai konfigurasi tersimpan.",
"wechatTest": "Kirim notifikasi uji",
"wechatTestSuccess": "Notifikasi uji berhasil dikirim",
"wechatTestFailed": "Gagal mengirim notifikasi uji",
"wechatReportEnable": "Laporan terjadwal",
"wechatReportEnableDesc": "Kirim ringkasan teks berkala terpisah dari peringatan. Basis data dan berkas konfigurasi tidak dilampirkan.",
"wechatReportTime": "Jadwal laporan",
"wechatReportTimeDesc": "Gunakan ekspresi cron atau preset seperti @daily.",
"wechatEvents": "Peringatan peristiwa",
"wechatEventsDesc": "Pilih peristiwa yang mengirim notifikasi dan atur ambang peringatan."
},
"xray": {
"save": "Simpan",
@@ -2943,5 +2969,18 @@
"restartXray": "Mulai Ulang Layanan Xray",
"restartXraySuccess": "Layanan Xray berhasil dimulai ulang",
"settings": "Pengaturan"
},
"wechat": {
"test": {
"title": "Uji Notifikasi WeChat 3x-ui",
"body": "Ini adalah notifikasi uji dari 3x-ui. Tidak menyertakan berkas basis data atau konfigurasi."
},
"report": {
"title": "Laporan Status 3x-ui",
"counts": "Total: {{ .Total }} | Dinonaktifkan: {{ .Disabled }} | Kedaluwarsa: {{ .Expired }} | Kuota habis: {{ .Depleted }}",
"trafficUsed": "Trafik terpakai 3x-ui",
"trafficRemaining": "Sisa trafik 3x-ui",
"trafficQuotaUnset": "Kuota belum dikonfigurasi"
}
}
}
+40 -1
View File
@@ -1911,7 +1911,33 @@
"subHostSortMode": "サブスクリプションのノード順序",
"subHostSortInbound": "インバウンド順(既定)",
"subHostSortHosts": "ホスト順",
"subHostSortModeDesc": "異なるインバウンド間でもホストページの順序に従います。サーバーが出力する順序を指定しますが、クライアントアプリが独自に並べ替える場合があります。"
"subHostSortModeDesc": "異なるインバウンド間でもホストページの順序に従います。サーバーが出力する順序を指定しますが、クライアントアプリが独自に並べ替える場合があります。",
"wechatSettings": "WeChat 通知",
"wechatEnable": "WeChat 通知を有効化",
"wechatEnableDesc": "WeCom グループのボットまたは互換 Webhook ゲートウェイでアラートを送信します。",
"wechatMode": "配信方式",
"wechatModeDesc": "宛先が対応するメッセージ形式を選択します。",
"wechatModeWecom": "WeCom グループボット",
"wechatModeWebhook": "カスタム Webhook ゲートウェイ",
"wechatPersonalGateway": "個人用 WeChat には互換ゲートウェイが必要です。WeCom ボットは WeCom グループに送信し、個人用 WeChat には直接送信できません。",
"wechatWebhookURL": "Webhook URL",
"wechatWebhookURLConfigured": "Webhook URL は保存済みです。空欄で現在の値を保持します。",
"wechatWebhookURLDesc": "HTTPS の宛先を使用します。URL に含まれる秘密情報は保存後に返されません。",
"wechatSecretPlaceholder": "空欄で保存済みの値を保持",
"wechatToken": "Bearer トークン",
"wechatTokenConfigured": "Bearer トークンは保存済みです。空欄で現在の値を保持します。",
"wechatTokenDesc": "カスタムゲートウェイの任意の認証です。不要なら空欄にします。",
"wechatLanguage": "メッセージ言語",
"wechatSaveBeforeTest": "テスト前に変更を保存してください。テストは保存済みの設定を使用します。",
"wechatTest": "テスト通知を送信",
"wechatTestSuccess": "テスト通知を送信しました",
"wechatTestFailed": "テスト通知を送信できませんでした",
"wechatReportEnable": "定期レポート",
"wechatReportEnableDesc": "イベントアラートとは別に定期的なテキスト概要を送信します。データベースや設定ファイルは添付しません。",
"wechatReportTime": "レポートのスケジュール",
"wechatReportTimeDesc": "Cron 式または @daily などのプリセットを使用します。",
"wechatEvents": "イベントアラート",
"wechatEventsDesc": "WeChat 通知を送信するイベントとアラートのしきい値を選択します。"
},
"xray": {
"importRules": "ルールをインポート",
@@ -2943,5 +2969,18 @@
"restartXray": "Xrayサービスを再起動",
"restartXraySuccess": "Xrayサービスが正常に再起動されました",
"settings": "設定"
},
"wechat": {
"test": {
"title": "3x-ui WeChat 通知テスト",
"body": "これは 3x-ui からのテスト通知です。データベースや設定ファイルは含まれません。"
},
"report": {
"title": "3x-ui ステータスレポート",
"counts": "合計:{{ .Total }} | 無効:{{ .Disabled }} | 期限切れ:{{ .Expired }} | 容量消尽:{{ .Depleted }}",
"trafficUsed": "3x-ui 使用済み通信量",
"trafficRemaining": "3x-ui 残りの通信量",
"trafficQuotaUnset": "上限未設定"
}
}
}
+40 -1
View File
@@ -1911,7 +1911,33 @@
"subHostSortMode": "Ordem dos nós da assinatura",
"subHostSortInbound": "Ordem das entradas (padrão)",
"subHostSortHosts": "Ordem dos hosts",
"subHostSortModeDesc": "Segue a ordem da página de hosts entre diferentes entradas. Define a ordem emitida pelo servidor; os aplicativos clientes podem aplicar sua própria ordenação."
"subHostSortModeDesc": "Segue a ordem da página de hosts entre diferentes entradas. Define a ordem emitida pelo servidor; os aplicativos clientes podem aplicar sua própria ordenação.",
"wechatSettings": "Notificações do WeChat",
"wechatEnable": "Ativar notificações do WeChat",
"wechatEnableDesc": "Envie alertas por um robô de grupo do WeCom ou gateway webhook compatível.",
"wechatMode": "Modo de envio",
"wechatModeDesc": "Escolha o formato aceito pelo destino.",
"wechatModeWecom": "Robô de grupo do WeCom",
"wechatModeWebhook": "Gateway webhook personalizado",
"wechatPersonalGateway": "O WeChat pessoal exige um gateway compatível. O robô do WeCom envia para grupos do WeCom, não diretamente ao WeChat pessoal.",
"wechatWebhookURL": "URL do webhook",
"wechatWebhookURLConfigured": "Uma URL está salva. Deixe em branco para mantê-la.",
"wechatWebhookURLDesc": "Use um destino HTTPS. A URL pode conter um segredo e o painel não retorna o valor salvo.",
"wechatSecretPlaceholder": "Deixe em branco para manter o valor salvo",
"wechatToken": "Token Bearer",
"wechatTokenConfigured": "Um token está salvo. Deixe em branco para mantê-lo.",
"wechatTokenDesc": "Autenticação opcional do gateway. Deixe em branco se não for necessária.",
"wechatLanguage": "Idioma das mensagens",
"wechatSaveBeforeTest": "Salve as alterações antes de testar. O teste usa a configuração salva.",
"wechatTest": "Enviar notificação de teste",
"wechatTestSuccess": "Notificação de teste enviada com sucesso",
"wechatTestFailed": "Falha ao enviar notificação de teste",
"wechatReportEnable": "Relatórios agendados",
"wechatReportEnableDesc": "Envie resumos de texto periódicos separados dos alertas. Não anexa bancos de dados ou arquivos de configuração.",
"wechatReportTime": "Agendamento do relatório",
"wechatReportTimeDesc": "Use uma expressão cron ou uma opção como @daily.",
"wechatEvents": "Alertas de eventos",
"wechatEventsDesc": "Escolha os eventos que enviam notificações e os limites de alerta."
},
"xray": {
"importRules": "Importar regras",
@@ -2943,5 +2969,18 @@
"restartXray": "Reiniciar serviço Xray",
"restartXraySuccess": "O serviço Xray foi reiniciado com sucesso",
"settings": "Configurações"
},
"wechat": {
"test": {
"title": "Teste de notificação WeChat do 3x-ui",
"body": "Esta é uma notificação de teste do 3x-ui. Nenhum arquivo de banco de dados ou configuração está incluído."
},
"report": {
"title": "Relatório de status do 3x-ui",
"counts": "Total: {{ .Total }} | Desativados: {{ .Disabled }} | Expirados: {{ .Expired }} | Esgotados: {{ .Depleted }}",
"trafficUsed": "Tráfego usado do 3x-ui",
"trafficRemaining": "Tráfego restante do 3x-ui",
"trafficQuotaUnset": "Cota não configurada"
}
}
}
+40 -1
View File
@@ -1911,7 +1911,33 @@
"subHostSortMode": "Порядок узлов подписки",
"subHostSortInbound": "Порядок входящих подключений (по умолчанию)",
"subHostSortHosts": "Порядок хостов",
"subHostSortModeDesc": "Используется порядок со страницы хостов для всех входящих подключений. Настройка задаёт порядок выдачи сервером; клиентские приложения могут сортировать узлы самостоятельно."
"subHostSortModeDesc": "Используется порядок со страницы хостов для всех входящих подключений. Настройка задаёт порядок выдачи сервером; клиентские приложения могут сортировать узлы самостоятельно.",
"wechatSettings": "Уведомления WeChat",
"wechatEnable": "Включить уведомления WeChat",
"wechatEnableDesc": "Отправка оповещений через бота группы WeCom или совместимый webhook-шлюз.",
"wechatMode": "Способ доставки",
"wechatModeDesc": "Выберите формат сообщений, поддерживаемый получателем.",
"wechatModeWecom": "Бот группы WeCom",
"wechatModeWebhook": "Собственный webhook-шлюз",
"wechatPersonalGateway": "Для личного WeChat нужен совместимый шлюз. Бот WeCom отправляет сообщения в группы WeCom, а не напрямую в личный WeChat.",
"wechatWebhookURL": "URL webhook",
"wechatWebhookURLConfigured": "URL сохранён. Оставьте поле пустым, чтобы сохранить его.",
"wechatWebhookURLDesc": "Используйте адрес HTTPS. URL может содержать секрет; сохранённое значение не возвращается панелью.",
"wechatSecretPlaceholder": "Оставьте пустым, чтобы сохранить значение",
"wechatToken": "Токен Bearer",
"wechatTokenConfigured": "Токен сохранён. Оставьте поле пустым, чтобы сохранить его.",
"wechatTokenDesc": "Необязательная авторизация шлюза. Оставьте пустым, если она не нужна.",
"wechatLanguage": "Язык сообщений",
"wechatSaveBeforeTest": "Сохраните изменения перед проверкой. Проверка использует сохранённую конфигурацию.",
"wechatTest": "Отправить тестовое уведомление",
"wechatTestSuccess": "Тестовое уведомление успешно отправлено",
"wechatTestFailed": "Не удалось отправить тестовое уведомление",
"wechatReportEnable": "Отчёты по расписанию",
"wechatReportEnableDesc": "Периодические текстовые сводки независимо от оповещений. Базы данных и файлы конфигурации не прикрепляются.",
"wechatReportTime": "Расписание отчётов",
"wechatReportTimeDesc": "Используйте выражение cron или шаблон, например @daily.",
"wechatEvents": "Оповещения о событиях",
"wechatEventsDesc": "Выберите события для уведомлений и пороговые значения."
},
"xray": {
"importRules": "Импорт правил",
@@ -2943,5 +2969,18 @@
"restartXray": "Перезапустить службу Xray",
"restartXraySuccess": "Служба Xray успешно перезапущена",
"settings": "Настройки"
},
"wechat": {
"test": {
"title": "Тест уведомлений WeChat от 3x-ui",
"body": "Это тестовое уведомление от 3x-ui. Файлы базы данных и конфигурации не прилагаются."
},
"report": {
"title": "Отчёт о состоянии 3x-ui",
"counts": "Всего: {{ .Total }} | Отключено: {{ .Disabled }} | Истекло: {{ .Expired }} | Исчерпано: {{ .Depleted }}",
"trafficUsed": "Использованный трафик 3x-ui",
"trafficRemaining": "Оставшийся трафик 3x-ui",
"trafficQuotaUnset": "Лимит не задан"
}
}
}
+40 -1
View File
@@ -2032,7 +2032,33 @@
"subHostSortMode": "Poradie uzlov v predplatnom",
"subHostSortInbound": "Poradie inboundov (predvolené)",
"subHostSortHosts": "Poradie hostiteľov",
"subHostSortModeDesc": "Poradie hostiteľov sa riadi stránkou Hostitelia naprieč inboundmi. Určuje poradie, ktoré odosiela server; klientske aplikácie môžu použiť vlastné triedenie."
"subHostSortModeDesc": "Poradie hostiteľov sa riadi stránkou Hostitelia naprieč inboundmi. Určuje poradie, ktoré odosiela server; klientske aplikácie môžu použiť vlastné triedenie.",
"wechatSettings": "Oznámenia WeChat",
"wechatEnable": "Zapnúť oznámenia WeChat",
"wechatEnableDesc": "Posielať upozornenia cez robota skupiny WeCom alebo kompatibilnú webhook bránu.",
"wechatMode": "Spôsob doručenia",
"wechatModeDesc": "Vyberte formát správ podporovaný cieľom.",
"wechatModeWecom": "Robot skupiny WeCom",
"wechatModeWebhook": "Vlastná webhook brána",
"wechatPersonalGateway": "Osobný WeChat vyžaduje kompatibilnú bránu. Robot WeCom posiela do skupín WeCom, nie priamo do osobného WeChatu.",
"wechatWebhookURL": "URL webhooku",
"wechatWebhookURLConfigured": "URL je uložená. Prázdne pole ju zachová.",
"wechatWebhookURLDesc": "Použite HTTPS. URL môže obsahovať tajný údaj a panel uloženú hodnotu nevracia.",
"wechatSecretPlaceholder": "Prázdne pole zachová uloženú hodnotu",
"wechatToken": "Bearer token",
"wechatTokenConfigured": "Token je uložený. Prázdne pole ho zachová.",
"wechatTokenDesc": "Voliteľné overenie brány. Ak nie je potrebné, nechajte prázdne.",
"wechatLanguage": "Jazyk správ",
"wechatSaveBeforeTest": "Pred testom uložte zmeny. Test používa uloženú konfiguráciu.",
"wechatTest": "Odoslať testovacie oznámenie",
"wechatTestSuccess": "Skúšobné oznámenie bolo úspešne odoslané",
"wechatTestFailed": "Skúšobné oznámenie sa nepodarilo odoslať",
"wechatReportEnable": "Plánované prehľady",
"wechatReportEnableDesc": "Pravidelné textové prehľady nezávislé od upozornení. Databázy ani konfiguračné súbory sa neprikladajú.",
"wechatReportTime": "Plán prehľadov",
"wechatReportTimeDesc": "Použite výraz cron alebo predvoľbu ako @daily.",
"wechatEvents": "Upozornenia na udalosti",
"wechatEventsDesc": "Vyberte udalosti pre oznámenia a nastavte prahy upozornení."
},
"xray": {
"save": "Uložiť",
@@ -2943,5 +2969,18 @@
"restartXray": "Reštartovať službu Xray",
"restartXraySuccess": "Xray bol úspešne reštartovaný",
"settings": "Nastavenia"
},
"wechat": {
"test": {
"title": "Test oznámení WeChat z 3x-ui",
"body": "Toto je skúšobné oznámenie z 3x-ui. Neobsahuje súbory databázy ani konfigurácie."
},
"report": {
"title": "Správa o stave 3x-ui",
"counts": "Celkom: {{ .Total }} | Zakázané: {{ .Disabled }} | Platnosť skončila: {{ .Expired }} | Vyčerpané: {{ .Depleted }}",
"trafficUsed": "Použitý prenos 3x-ui",
"trafficRemaining": "Zostávajúci prenos 3x-ui",
"trafficQuotaUnset": "Limit nie je nastavený"
}
}
}
+40 -1
View File
@@ -1911,7 +1911,33 @@
"subHostSortMode": "Abonelik düğümü sıralaması",
"subHostSortInbound": "Gelen bağlantı sırası (varsayılan)",
"subHostSortHosts": "Ana bilgisayar sırası",
"subHostSortModeDesc": "Farklı gelen bağlantılarda Ana Bilgisayarlar sayfasının sırasını izler. Sunucunun çıktı sırasını belirler; istemci uygulamaları kendi sıralamalarını uygulayabilir."
"subHostSortModeDesc": "Farklı gelen bağlantılarda Ana Bilgisayarlar sayfasının sırasını izler. Sunucunun çıktı sırasını belirler; istemci uygulamaları kendi sıralamalarını uygulayabilir.",
"wechatSettings": "WeChat bildirimleri",
"wechatEnable": "WeChat bildirimlerini etkinleştir",
"wechatEnableDesc": "WeCom grup robotu veya uyumlu webhook ağ geçidi üzerinden uyarı gönderin.",
"wechatMode": "Gönderim modu",
"wechatModeDesc": "Hedefin desteklediği mesaj biçimini seçin.",
"wechatModeWecom": "WeCom grup robotu",
"wechatModeWebhook": "Özel webhook ağ geçidi",
"wechatPersonalGateway": "Kişisel WeChat uyumlu bir ağ geçidi gerektirir. WeCom robotu, kişisel WeChat yerine WeCom gruplarına gönderir.",
"wechatWebhookURL": "Webhook URL’si",
"wechatWebhookURLConfigured": "Bir URL kaydedildi. Korumak için boş bırakın.",
"wechatWebhookURLDesc": "HTTPS hedefi kullanın. URL gizli bilgi içerebilir; panel kayıtlı değeri geri döndürmez.",
"wechatSecretPlaceholder": "Kayıtlı değeri korumak için boş bırakın",
"wechatToken": "Bearer belirteci",
"wechatTokenConfigured": "Bir belirteç kaydedildi. Korumak için boş bırakın.",
"wechatTokenDesc": "Ağ geçidi için isteğe bağlı kimlik doğrulama. Gerekmiyorsa boş bırakın.",
"wechatLanguage": "Mesaj dili",
"wechatSaveBeforeTest": "Testten önce değişiklikleri kaydedin. Test kayıtlı yapılandırmayı kullanır.",
"wechatTest": "Test bildirimi gönder",
"wechatTestSuccess": "Test bildirimi başarıyla gönderildi",
"wechatTestFailed": "Test bildirimi gönderilemedi",
"wechatReportEnable": "Zamanlanmış raporlar",
"wechatReportEnableDesc": "Olay uyarılarından bağımsız düzenli metin özetleri gönderin. Veritabanı ve yapılandırma dosyaları eklenmez.",
"wechatReportTime": "Rapor zamanlaması",
"wechatReportTimeDesc": "Cron ifadesi veya @daily gibi bir ön ayar kullanın.",
"wechatEvents": "Olay uyarıları",
"wechatEventsDesc": "Bildirim gönderecek olayları seçin ve uyarı eşiklerini ayarlayın."
},
"xray": {
"save": "Kaydet",
@@ -2943,5 +2969,18 @@
"restartXray": "Xray Hizmetini Yeniden Başlat",
"restartXraySuccess": "Xray hizmeti başarıyla yeniden başlatıldı",
"settings": "Ayarlar"
},
"wechat": {
"test": {
"title": "3x-ui WeChat Bildirim Testi",
"body": "Bu, 3x-ui tarafından gönderilen bir test bildirimidir. Veritabanı veya yapılandırma dosyası içermez."
},
"report": {
"title": "3x-ui Durum Raporu",
"counts": "Toplam: {{ .Total }} | Devre dışı: {{ .Disabled }} | Süresi dolan: {{ .Expired }} | Kotası tükenen: {{ .Depleted }}",
"trafficUsed": "3x-ui kullanılan trafik",
"trafficRemaining": "3x-ui kalan trafik",
"trafficQuotaUnset": "Kota yapılandırılmamış"
}
}
}
+40 -1
View File
@@ -1911,7 +1911,33 @@
"subHostSortMode": "Порядок вузлів підписки",
"subHostSortInbound": "Порядок вхідних підключень (типово)",
"subHostSortHosts": "Порядок хостів",
"subHostSortModeDesc": "Використовується порядок зі сторінки хостів для всіх вхідних підключень. Це визначає порядок видачі сервером; клієнтські застосунки можуть сортувати вузли самостійно."
"subHostSortModeDesc": "Використовується порядок зі сторінки хостів для всіх вхідних підключень. Це визначає порядок видачі сервером; клієнтські застосунки можуть сортувати вузли самостійно.",
"wechatSettings": "Сповіщення WeChat",
"wechatEnable": "Увімкнути сповіщення WeChat",
"wechatEnableDesc": "Надсилайте сповіщення через бота групи WeCom або сумісний webhook-шлюз.",
"wechatMode": "Спосіб доставки",
"wechatModeDesc": "Виберіть формат повідомлень, який підтримує одержувач.",
"wechatModeWecom": "Бот групи WeCom",
"wechatModeWebhook": "Власний webhook-шлюз",
"wechatPersonalGateway": "Для особистого WeChat потрібен сумісний шлюз. Бот WeCom надсилає повідомлення до груп WeCom, а не безпосередньо в особистий WeChat.",
"wechatWebhookURL": "URL webhook",
"wechatWebhookURLConfigured": "URL збережено. Залиште поле порожнім, щоб його зберегти.",
"wechatWebhookURLDesc": "Використовуйте HTTPS. URL може містити секрет; панель не повертає збережене значення.",
"wechatSecretPlaceholder": "Залиште порожнім, щоб зберегти значення",
"wechatToken": "Токен Bearer",
"wechatTokenConfigured": "Токен збережено. Залиште поле порожнім, щоб його зберегти.",
"wechatTokenDesc": "Необов’язкова автентифікація шлюзу. Залиште порожнім, якщо вона не потрібна.",
"wechatLanguage": "Мова повідомлень",
"wechatSaveBeforeTest": "Збережіть зміни перед перевіркою. Перевірка використовує збережену конфігурацію.",
"wechatTest": "Надіслати тестове сповіщення",
"wechatTestSuccess": "Тестове сповіщення успішно надіслано",
"wechatTestFailed": "Не вдалося надіслати тестове сповіщення",
"wechatReportEnable": "Звіти за розкладом",
"wechatReportEnableDesc": "Періодичні текстові підсумки окремо від сповіщень. Бази даних і файли конфігурації не додаються.",
"wechatReportTime": "Розклад звітів",
"wechatReportTimeDesc": "Використовуйте вираз cron або шаблон, наприклад @daily.",
"wechatEvents": "Сповіщення про події",
"wechatEventsDesc": "Виберіть події для сповіщень і порогові значення."
},
"xray": {
"save": "Зберегти",
@@ -2943,5 +2969,18 @@
"restartXray": "Перезапустити службу Xray",
"restartXraySuccess": "Службу Xray успішно перезапущено",
"settings": "Налаштування"
},
"wechat": {
"test": {
"title": "Тест сповіщень WeChat від 3x-ui",
"body": "Це тестове сповіщення від 3x-ui. Файли бази даних і конфігурації не додаються."
},
"report": {
"title": "Звіт про стан 3x-ui",
"counts": "Усього: {{ .Total }} | Вимкнено: {{ .Disabled }} | Термін минув: {{ .Expired }} | Вичерпано: {{ .Depleted }}",
"trafficUsed": "Використаний трафік 3x-ui",
"trafficRemaining": "Залишок трафіку 3x-ui",
"trafficQuotaUnset": "Ліміт не задано"
}
}
}
+40 -1
View File
@@ -1911,7 +1911,33 @@
"subHostSortMode": "Thứ tự nút đăng ký",
"subHostSortInbound": "Thứ tự kết nối vào (mặc định)",
"subHostSortHosts": "Thứ tự máy chủ",
"subHostSortModeDesc": "Theo thứ tự trên trang Máy chủ giữa các kết nối vào. Thiết lập này quyết định thứ tự do máy chủ xuất ra; ứng dụng khách có thể tự sắp xếp lại."
"subHostSortModeDesc": "Theo thứ tự trên trang Máy chủ giữa các kết nối vào. Thiết lập này quyết định thứ tự do máy chủ xuất ra; ứng dụng khách có thể tự sắp xếp lại.",
"wechatSettings": "Thông báo WeChat",
"wechatEnable": "Bật thông báo WeChat",
"wechatEnableDesc": "Gửi cảnh báo qua robot nhóm WeCom hoặc cổng webhook tương thích.",
"wechatMode": "Phương thức gửi",
"wechatModeDesc": "Chọn định dạng tin nhắn mà đích hỗ trợ.",
"wechatModeWecom": "Robot nhóm WeCom",
"wechatModeWebhook": "Cổng webhook tùy chỉnh",
"wechatPersonalGateway": "WeChat cá nhân cần cổng tương thích. Robot WeCom gửi tới nhóm WeCom, không gửi trực tiếp tới WeChat cá nhân.",
"wechatWebhookURL": "URL webhook",
"wechatWebhookURLConfigured": "URL đã được lưu. Để trống để giữ giá trị cũ.",
"wechatWebhookURLDesc": "Dùng địa chỉ HTTPS. URL có thể chứa bí mật và bảng điều khiển không trả lại giá trị đã lưu.",
"wechatSecretPlaceholder": "Để trống để giữ giá trị đã lưu",
"wechatToken": "Mã Bearer",
"wechatTokenConfigured": "Mã đã được lưu. Để trống để giữ lại.",
"wechatTokenDesc": "Xác thực tùy chọn cho cổng. Để trống nếu không cần.",
"wechatLanguage": "Ngôn ngữ tin nhắn",
"wechatSaveBeforeTest": "Lưu thay đổi trước khi thử. Phép thử dùng cấu hình đã lưu.",
"wechatTest": "Gửi thông báo thử",
"wechatTestSuccess": "Đã gửi thông báo thử nghiệm",
"wechatTestFailed": "Không thể gửi thông báo thử nghiệm",
"wechatReportEnable": "Báo cáo định kỳ",
"wechatReportEnableDesc": "Gửi tóm tắt văn bản định kỳ độc lập với cảnh báo. Không đính kèm cơ sở dữ liệu hay tệp cấu hình.",
"wechatReportTime": "Lịch báo cáo",
"wechatReportTimeDesc": "Dùng biểu thức cron hoặc giá trị như @daily.",
"wechatEvents": "Cảnh báo sự kiện",
"wechatEventsDesc": "Chọn sự kiện gửi thông báo và đặt ngưỡng cảnh báo."
},
"xray": {
"importRules": "Nhập quy tắc",
@@ -2943,5 +2969,18 @@
"restartXray": "Khởi động lại dịch vụ Xray",
"restartXraySuccess": "Dịch vụ Xray đã được khởi động lại thành công",
"settings": "Cài đặt"
},
"wechat": {
"test": {
"title": "Kiểm tra thông báo WeChat của 3x-ui",
"body": "Đây là thông báo thử nghiệm từ 3x-ui. Không bao gồm tệp cơ sở dữ liệu hoặc cấu hình."
},
"report": {
"title": "Báo cáo trạng thái 3x-ui",
"counts": "Tổng: {{ .Total }} | Đã tắt: {{ .Disabled }} | Hết hạn: {{ .Expired }} | Hết lưu lượng: {{ .Depleted }}",
"trafficUsed": "Lưu lượng 3x-ui đã dùng",
"trafficRemaining": "Lưu lượng 3x-ui còn lại",
"trafficQuotaUnset": "Chưa đặt hạn mức"
}
}
}
+40 -1
View File
@@ -1911,7 +1911,33 @@
"subHostSortMode": "订阅节点排序",
"subHostSortInbound": "入站顺序(默认)",
"subHostSortHosts": "主机顺序",
"subHostSortModeDesc": "跨入站使用主机页面中的排序。此设置决定服务器输出顺序;客户端应用仍可能自行排序。"
"subHostSortModeDesc": "跨入站使用主机页面中的排序。此设置决定服务器输出顺序;客户端应用仍可能自行排序。",
"wechatSettings": "微信通知",
"wechatEnable": "启用微信通知",
"wechatEnableDesc": "通过企业微信群机器人或兼容的 Webhook 网关发送面板告警。",
"wechatMode": "发送方式",
"wechatModeDesc": "选择接收端支持的消息格式。",
"wechatModeWecom": "企业微信群机器人",
"wechatModeWebhook": "自定义 Webhook 网关",
"wechatPersonalGateway": "个人微信需要兼容的网关。企业微信机器人只向企业微信群发送消息,不能直接发送到个人微信。",
"wechatWebhookURL": "Webhook 地址",
"wechatWebhookURLConfigured": "已保存 Webhook 地址,留空可保留原值。",
"wechatWebhookURLDesc": "使用 HTTPS 接收地址。地址可能包含密钥,面板不会返回已保存的原值。",
"wechatSecretPlaceholder": "留空可保留已保存的值",
"wechatToken": "Bearer 令牌",
"wechatTokenConfigured": "已保存 Bearer 令牌,留空可保留原值。",
"wechatTokenDesc": "自定义网关的可选身份认证;接收端不需要时请留空。",
"wechatLanguage": "消息语言",
"wechatSaveBeforeTest": "请先保存修改再测试。测试使用服务器已保存的配置。",
"wechatTest": "发送测试通知",
"wechatTestSuccess": "测试通知发送成功",
"wechatTestFailed": "测试通知发送失败",
"wechatReportEnable": "定时报告",
"wechatReportEnableDesc": "独立于事件告警发送定期文字摘要,不附带数据库或配置文件。",
"wechatReportTime": "报告时间",
"wechatReportTimeDesc": "使用 Cron 表达式或 @daily 等预设。",
"wechatEvents": "事件告警",
"wechatEventsDesc": "选择需要发送微信通知的面板事件,并设置告警阈值。"
},
"xray": {
"importRules": "导入规则",
@@ -2943,5 +2969,18 @@
"restartXray": "重启 Xray 服务",
"restartXraySuccess": "Xray 服务已成功重启",
"settings": "设置"
},
"wechat": {
"test": {
"title": "3x-ui 微信通知测试",
"body": "这是一条来自 3x-ui 的测试通知,不包含数据库或配置文件。"
},
"report": {
"title": "3x-ui 状态报告",
"counts": "总计:{{ .Total }} | 已禁用:{{ .Disabled }} | 已过期:{{ .Expired }} | 流量耗尽:{{ .Depleted }}",
"trafficUsed": "3x-ui 已用流量",
"trafficRemaining": "3x-ui 剩余流量",
"trafficQuotaUnset": "未配置额度"
}
}
}
+40 -1
View File
@@ -1911,7 +1911,33 @@
"subHostSortMode": "訂閱節點排序",
"subHostSortInbound": "入站順序(預設)",
"subHostSortHosts": "主機順序",
"subHostSortModeDesc": "跨入站使用主機頁面中的排序。此設定決定伺服器輸出順序;用戶端應用程式仍可能自行排序。"
"subHostSortModeDesc": "跨入站使用主機頁面中的排序。此設定決定伺服器輸出順序;用戶端應用程式仍可能自行排序。",
"wechatSettings": "微信通知",
"wechatEnable": "啟用微信通知",
"wechatEnableDesc": "透過企業微信群組機器人或相容的 Webhook 閘道傳送面板警報。",
"wechatMode": "傳送方式",
"wechatModeDesc": "選擇接收端支援的訊息格式。",
"wechatModeWecom": "企業微信群組機器人",
"wechatModeWebhook": "自訂 Webhook 閘道",
"wechatPersonalGateway": "個人微信需要相容的閘道。企業微信機器人只向企業微信群組傳送訊息,無法直接傳送到個人微信。",
"wechatWebhookURL": "Webhook 位址",
"wechatWebhookURLConfigured": "已儲存 Webhook 位址,留空可保留原值。",
"wechatWebhookURLDesc": "使用 HTTPS 接收位址。位址可能包含金鑰,面板不會傳回已儲存的原值。",
"wechatSecretPlaceholder": "留空可保留已儲存的值",
"wechatToken": "Bearer 權杖",
"wechatTokenConfigured": "已儲存 Bearer 權杖,留空可保留原值。",
"wechatTokenDesc": "自訂閘道的選用驗證;接收端不需要時請留空。",
"wechatLanguage": "訊息語言",
"wechatSaveBeforeTest": "請先儲存修改再測試。測試使用伺服器已儲存的設定。",
"wechatTest": "傳送測試通知",
"wechatTestSuccess": "測試通知發送成功",
"wechatTestFailed": "測試通知發送失敗",
"wechatReportEnable": "定時報告",
"wechatReportEnableDesc": "獨立於事件警報傳送定期文字摘要,不附加資料庫或設定檔。",
"wechatReportTime": "報告時間",
"wechatReportTimeDesc": "使用 Cron 運算式或 @daily 等預設。",
"wechatEvents": "事件警報",
"wechatEventsDesc": "選擇需要傳送微信通知的面板事件,並設定警報門檻。"
},
"xray": {
"save": "儲存",
@@ -2943,5 +2969,18 @@
"restartXray": "重啟 Xray 服務",
"restartXraySuccess": "Xray 服務已成功重啟",
"settings": "設定"
},
"wechat": {
"test": {
"title": "3x-ui 微信通知測試",
"body": "這是一則來自 3x-ui 的測試通知,不包含資料庫或設定檔。"
},
"report": {
"title": "3x-ui 狀態報告",
"counts": "總計:{{ .Total }} | 已停用:{{ .Disabled }} | 已到期:{{ .Expired }} | 流量耗盡:{{ .Depleted }}",
"trafficUsed": "3x-ui 已用流量",
"trafficRemaining": "3x-ui 剩餘流量",
"trafficQuotaUnset": "未設定額度"
}
}
}
+30 -9
View File
@@ -15,6 +15,7 @@ import (
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/amneziawgkern"
@@ -38,6 +39,7 @@ import (
"github.com/mhsanaei/3x-ui/v3/internal/web/service/email"
"github.com/mhsanaei/3x-ui/v3/internal/web/service/panel"
"github.com/mhsanaei/3x-ui/v3/internal/web/service/tgbot"
"github.com/mhsanaei/3x-ui/v3/internal/web/service/wechat"
"github.com/mhsanaei/3x-ui/v3/internal/web/websocket"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
@@ -126,12 +128,19 @@ type Server struct {
tgbotService tgbot.Tgbot
discordService *discord.DiscordService
discordGateway *discord.GatewayClient
wechatService *wechat.Service
wsHub *websocket.Hub
bus *eventbus.Bus
cron *cron.Cron
discordNotifyEntryID cron.EntryID
wechatNotifyEntryID cron.EntryID
cpuAlarmEntryID cron.EntryID
memoryAlarmEntryID cron.EntryID
wechatScheduleMu sync.Mutex
wechatScheduler *cron.Cron
wechatReportSpec string
ctx context.Context
cancel context.CancelFunc
@@ -419,15 +428,7 @@ func (s *Server) startTask(restartXray bool, loc *time.Location) {
s.discordNotifyEntryID = scheduleSettingJob(s.cron, "Discord notify", runtime, "@daily", job.NewDiscordNotifyJob(s.discordService))
}
// CPU monitor publishes cpu.high events; register it whenever any notifier
// (Telegram or Email) wants them, independent of the Telegram bot being on.
if s.cpuAlarmWanted() {
_, _ = s.cron.AddJob(cadenceCPUAlarm, job.NewCheckCpuJob())
}
// Memory monitor publishes memory.high events; register it whenever any notifier wants them.
if s.memoryAlarmWanted() {
_, _ = s.cron.AddJob(cadenceMemoryAlarm, job.NewCheckMemJob())
}
s.reloadWechatJobs()
if mins := sys.MemoryReleaseIntervalMinutes(); mins > 0 {
_, _ = s.cron.AddJob(fmt.Sprintf("@every %dm", mins), job.NewMemoryReleaseJob())
@@ -473,6 +474,13 @@ func (s *Server) cpuAlarmWanted() bool {
return true
}
}
if on, _ := s.settingService.GetWechatEnable(); on {
events, _ := s.settingService.GetWechatEnabledEvents()
threshold, _ := s.settingService.GetWechatCpu()
if wants(events, threshold) {
return true
}
}
return false
}
@@ -510,6 +518,13 @@ func (s *Server) memoryAlarmWanted() bool {
return true
}
}
if on, _ := s.settingService.GetWechatEnable(); on {
events, _ := s.settingService.GetWechatEnabledEvents()
threshold, _ := s.settingService.GetWechatMemory()
if wants(events, threshold) {
return true
}
}
return false
}
@@ -672,6 +687,12 @@ func (s *Server) start(restartXray bool, startTgBot bool) (err error) {
// Wire email service to controller for test endpoint
controller.SetEmailService(emailService)
s.wechatService = wechat.NewService(s.settingService)
wechatSub := wechat.NewSubscriber(s.settingService, s.wechatService)
s.bus.Subscribe("wechat-notifier", wechatSub.HandleEvent)
controller.SetWechatService(s.wechatService)
controller.SetReloadWechatFunc(s.reloadWechatJobs)
// Register discord subscriber (always — it checks discordBotEnable at runtime)
s.discordService = discord.NewDiscordService(s.settingService)
discordSub := discord.NewSubscriber(s.settingService, s.discordService)
+45
View File
@@ -0,0 +1,45 @@
package web
import "github.com/mhsanaei/3x-ui/v3/internal/web/job"
func (s *Server) reloadWechatJobs() {
s.wechatScheduleMu.Lock()
defer s.wechatScheduleMu.Unlock()
if s.cron == nil {
return
}
if s.wechatScheduler != s.cron {
s.wechatScheduler = s.cron
s.wechatNotifyEntryID, s.cpuAlarmEntryID, s.memoryAlarmEntryID = 0, 0, 0
s.wechatReportSpec = ""
}
enabled, enableErr := s.settingService.GetWechatEnable()
reports, reportErr := s.settingService.GetWechatReportEnable()
spec, specErr := s.settingService.GetWechatRunTime()
wanted := enableErr == nil && reportErr == nil && specErr == nil && enabled && reports
if s.wechatNotifyEntryID != 0 && (!wanted || spec != s.wechatReportSpec) {
s.cron.Remove(s.wechatNotifyEntryID)
s.wechatNotifyEntryID = 0
s.wechatReportSpec = ""
}
if wanted && s.wechatNotifyEntryID == 0 {
s.wechatNotifyEntryID = scheduleSettingJob(s.cron, "WeChat notify", spec, "@daily", job.NewWechatNotifyJob(s.wechatService))
s.wechatReportSpec = spec
}
if s.cpuAlarmWanted() {
if s.cpuAlarmEntryID == 0 {
s.cpuAlarmEntryID, _ = s.cron.AddJob(cadenceCPUAlarm, job.NewCheckCpuJob())
}
} else if s.cpuAlarmEntryID != 0 {
s.cron.Remove(s.cpuAlarmEntryID)
s.cpuAlarmEntryID = 0
}
if s.memoryAlarmWanted() {
if s.memoryAlarmEntryID == 0 {
s.memoryAlarmEntryID, _ = s.cron.AddJob(cadenceMemoryAlarm, job.NewCheckMemJob())
}
} else if s.memoryAlarmEntryID != 0 {
s.cron.Remove(s.memoryAlarmEntryID)
s.memoryAlarmEntryID = 0
}
}
+69
View File
@@ -0,0 +1,69 @@
package web
import (
"path/filepath"
"testing"
"github.com/robfig/cron/v3"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
"github.com/mhsanaei/3x-ui/v3/internal/web/service/wechat"
)
func TestWechatSettingsReloadSchedulesReportsAndMetricsWithoutTelegram(t *testing.T) {
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
save := func(key, value string) {
t.Helper()
row := model.Setting{Key: key, Value: value}
if err := database.GetDB().Where("key = ?", key).Assign(model.Setting{Value: value}).FirstOrCreate(&row).Error; err != nil {
t.Fatal(err)
}
}
for _, key := range []string{"tgBotEnable", "smtpEnable", "discordBotEnable", "wechatEnable"} {
save(key, "false")
}
s := &Server{cron: cron.New(), wechatService: wechat.NewService(service.SettingService{})}
s.reloadWechatJobs()
if got := len(s.cron.Entries()); got != 0 {
t.Fatalf("disabled notifiers scheduled %d jobs, want zero", got)
}
save("wechatEnable", "true")
save("wechatEnabledEvents", "cpu.high,memory.high")
save("wechatReportEnable", "true")
save("wechatRunTime", "@daily")
s.reloadWechatJobs()
if got := len(s.cron.Entries()); got != 3 || s.wechatNotifyEntryID == 0 || s.cpuAlarmEntryID == 0 || s.memoryAlarmEntryID == 0 {
t.Fatalf("newly enabled WeChat scheduled %d jobs, want report plus CPU and memory samplers", got)
}
oldReport, oldCPU := s.wechatNotifyEntryID, s.cpuAlarmEntryID
save("pageSize", "50")
s.reloadWechatJobs()
if s.wechatNotifyEntryID != oldReport || s.cpuAlarmEntryID != oldCPU {
t.Fatal("unrelated settings save restarted the report schedule or metric sampler")
}
save("wechatRunTime", "@hourly")
s.reloadWechatJobs()
if s.wechatNotifyEntryID == oldReport || s.cpuAlarmEntryID != oldCPU || len(s.cron.Entries()) != 3 {
t.Fatal("changing report schedule retained the old report or duplicated metric samplers")
}
s.cron = cron.New()
unrelatedID, err := s.cron.AddFunc("@hourly", func() {})
if err != nil {
t.Fatal(err)
}
s.reloadWechatJobs()
if len(s.cron.Entries()) != 4 || !s.cron.Entry(unrelatedID).Valid() {
t.Fatal("scheduler replacement lost metric samplers or removed an unrelated job with a reused ID")
}
oldCPU = s.cpuAlarmEntryID
save("wechatEnable", "false")
save("smtpEnable", "true")
save("smtpEnabledEvents", "cpu.high")
s.reloadWechatJobs()
if len(s.cron.Entries()) != 2 || !s.cron.Entry(unrelatedID).Valid() || s.cpuAlarmEntryID != oldCPU || s.memoryAlarmEntryID != 0 || s.wechatNotifyEntryID != 0 {
t.Fatal("disabling WeChat removed another notifier's CPU sampler or retained WeChat-only jobs")
}
}