mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-07-11 23:26:07 +00:00
feat(notifications): event bus architecture with Telegram and SMTP subscribers (#5326)
* feat(notifications): event bus architecture with Telegram and SMTP subscribers
- Event bus core with buffered channel, fan-out, panic recovery
- Telegram subscriber with HTML formatting and rate limiting
- Email subscriber with SMTP/TLS/STARTTLS support and stage diagnostics
- 5 event types: outbound.down/up, xray.crash, cpu.high, login.attempt
- CPU threshold checks per subscriber (tgCpu for TG, smtpCpu for Email)
- SystemMetricData struct for raw metric values in events
- i18n keys for en-US, ru-RU, and English defaults for other locales
* fix
* fix(notifications): repair crash/CPU alerts, harden secrets, add node alerts
Bug fixes:
- Xray crash notifications were permanently suppressed after the first crash:
XrayStateTracker latched state="down" with no reset and no recovery event,
so only the first crash per process lifetime ever notified. Removed the
tracker; the existing 1/min rate limiter already dedupes crash-loop spam.
- Email CPU alerts could never fire unless Telegram was also enabled, because
the CPU job was registered only inside the tgbot block. Register it whenever
either Telegram or SMTP wants cpu.high (new cpuAlarmWanted gate) and relax
the cadence to @every 1m (cpu.Percent already samples over a full minute).
- SMTP password (and, pre-existing, all other secrets) were shipped to the
browser in plaintext: GetAllSettingView was dead code and /setting/all
returned the raw model. Wire getAllSetting -> GetAllSettingView, redact
smtpPassword with a hasSmtpPassword presence flag, and preserve it on blank
save. Closes the leak for tgBotToken/ldapPassword/2FA token too.
Polish:
- email Send: use nil SMTP auth when no credentials (Go refuses PlainAuth over
the unencrypted "none" transport).
- Remove unused EventClientDepleted; fix inaccurate bus.go doc comments; drop
stale tgBotLoginNotify from the frontend schema; gofmt alignment.
Feature - node online/offline alerts:
- Emit node.down/node.up from the heartbeat job on a real status transition
(with a startup-spam guard), reusing NodeHealthData. Formatted by both the
Telegram and email subscribers and selectable in the settings UI.
Regenerated frontend types (hasSmtpPassword). New i18n keys added to en-US;
other locales fall back to English (bundle default) until translated.
* fix(settings): use antd Space orientation instead of deprecated direction
Ant Design 6 deprecated Space's `direction` prop in favor of `orientation`,
which logged a console warning from the Telegram/Email notification tabs. Brings
these two tabs in line with the rest of the codebase, which already uses
`orientation`.
* i18n(notifications): translate the notification feature into all locales
The notifications PR shipped ~99 new strings (SMTP settings, event labels,
Telegram/email message templates) as English placeholders in every non-English
locale. Translate them — plus the node-alert keys added during this review —
into all 12 locales: Arabic, Spanish, Persian, Indonesian, Japanese,
Portuguese-BR, Russian, Turkish, Ukrainian, Vietnamese, and Simplified/
Traditional Chinese.
Go-template placeholders ({{ .Tag }}, {{ .Name }}, etc.) are preserved exactly;
tgbot message values carry no leading status emoji (the bot/email code adds
those, so an emoji in the value would duplicate it); product/protocol names
(SMTP, STARTTLS, TLS, CPU, Xray, Telegram) are kept as-is.
---------
Co-authored-by: Sanaei <ho3ein.sanaei@gmail.com>
This commit is contained in:
@@ -1200,7 +1200,69 @@
|
||||
"userPassMustBeNotEmpty": "Новое имя пользователя и новый пароль должны быть заполнены",
|
||||
"getOutboundTrafficError": "Ошибка получения трафика исходящего подключения",
|
||||
"resetOutboundTrafficError": "Ошибка сброса трафика исходящего подключения"
|
||||
}
|
||||
},
|
||||
"smtpSettings": "Настройки SMTP",
|
||||
"smtpEnable": "Включить уведомления по Email",
|
||||
"smtpEnableDesc": "Включить уведомления по email через SMTP",
|
||||
"smtpHost": "SMTP хост",
|
||||
"smtpHostDesc": "Имя хоста SMTP сервера (например smtp.gmail.com)",
|
||||
"smtpPort": "SMTP порт",
|
||||
"smtpPortDesc": "Порт SMTP сервера (по умолчанию: 587)",
|
||||
"smtpUsername": "SMTP логин",
|
||||
"smtpUsernameDesc": "Логин для аутентификации SMTP",
|
||||
"smtpPassword": "SMTP пароль",
|
||||
"smtpPasswordDesc": "Пароль для аутентификации SMTP",
|
||||
"smtpTo": "Получатели",
|
||||
"smtpToDesc": "Адреса получателей через запятую",
|
||||
"emailSettings": "Email",
|
||||
"emailNotifications": "Уведомления",
|
||||
"smtpEventBusNotify": "Email уведомления о событиях",
|
||||
"smtpEventBusNotifyDesc": "Выберите события для email уведомлений",
|
||||
"tgEventBusNotify": "Telegram уведомления о событиях",
|
||||
"tgEventBusNotifyDesc": "Выберите события для Telegram уведомлений",
|
||||
"testSmtp": "Отправить тестовое письмо",
|
||||
"testTgBot": "Отправить тестовое сообщение",
|
||||
"eventGroupOutbound": "Исходящие",
|
||||
"eventGroupXray": "Ядро Xray",
|
||||
"eventGroupSystem": "Система",
|
||||
"eventGroupSecurity": "Безопасность",
|
||||
"eventOutboundDown": "Недоступен",
|
||||
"eventOutboundUp": "Работает",
|
||||
"eventXrayCrash": "Сбой",
|
||||
"eventCPUHigh": "Превышение порога CPU (%)",
|
||||
"requestFailed": "Запрос не удался",
|
||||
"smtpEncryption": "Шифрование",
|
||||
"smtpEncryptionDesc": "Метод шифрования SMTP соединения",
|
||||
"smtpEncryptionNone": "Нет (открытый текст)",
|
||||
"smtpEncryptionStartTLS": "STARTTLS",
|
||||
"smtpEncryptionTLS": "TLS (неявное)",
|
||||
"smtpStageConnect": "Подключение",
|
||||
"smtpStageAuth": "Аутентификация",
|
||||
"smtpStageSend": "Отправка",
|
||||
"smtpTestSuccess": "Тестовое письмо отправлено успешно",
|
||||
"smtpHostNotConfigured": "SMTP хост не настроен",
|
||||
"smtpNoRecipients": "Получатели не настроены",
|
||||
"eventLoginAttempt": "Попытка входа",
|
||||
"telegramTokenConfigured": "Настроен; оставьте пустым для сохранения текущего токена.",
|
||||
"telegramTokenPlaceholder": "Настроен - введите новый токен для замены",
|
||||
"smtpNotInitialized": "SMTP не инициализирован",
|
||||
"tgBotNotEnabled": "Telegram бот не включен",
|
||||
"tgTestFailed": "Тест Telegram не удался",
|
||||
"tgTestSuccess": "Тестовое сообщение отправлено в Telegram",
|
||||
"tgBotNotRunning": "Telegram бот не запущен",
|
||||
"smtpErrorAuth": "Ошибка аутентификации — проверьте логин и пароль",
|
||||
"smtpErrorStarttls": "Сервер требует STARTTLS — измените тип шифрования",
|
||||
"smtpErrorTls": "Сервер требует TLS — измените тип шифрования",
|
||||
"smtpErrorRefused": "Соединение отклонено — проверьте хост и порт",
|
||||
"smtpErrorTimeout": "Таймаут соединения — хост недоступен",
|
||||
"smtpErrorRelay": "Сервер отклоняет отправку с этого адреса",
|
||||
"smtpErrorEof": "Соединение закрыто сервером",
|
||||
"smtpErrorUnknown": "Ошибка SMTP: {{ .Error }}",
|
||||
"eventGroupNode": "Узлы",
|
||||
"eventNodeDown": "Недоступен",
|
||||
"eventNodeUp": "В сети",
|
||||
"smtpPasswordConfigured": "Настроен; оставьте пустым для сохранения текущего пароля.",
|
||||
"smtpPasswordPlaceholder": "Настроен - введите новый пароль для замены"
|
||||
},
|
||||
"xray": {
|
||||
"title": "Настройки Xray",
|
||||
@@ -1703,7 +1765,18 @@
|
||||
"AreYouSure": "Вы уверены? 🤔",
|
||||
"SuccessResetTraffic": "📧 Почта: {{ .ClientEmail }}\n🏁 Результат: ✅ Успешно",
|
||||
"FailedResetTraffic": "📧 Почта: {{ .ClientEmail }}\n🏁 Результат: ❌ Неудача \n\n🛠️ Ошибка: [ {{ .ErrorMessage }} ]",
|
||||
"FinishProcess": "🔚 Сброс трафика завершён для всех клиентов."
|
||||
"FinishProcess": "🔚 Сброс трафика завершён для всех клиентов.",
|
||||
"eventOutboundDown": "Исходящее подключение {{ .Tag }} НЕДОСТУПНО",
|
||||
"eventOutboundUp": "Исходящее подключение {{ .Tag }} РАБОТАЕТ",
|
||||
"eventXrayCrash": "Сбой Xray",
|
||||
"eventXrayCrashError": "Ошибка: {{ .Error }}",
|
||||
"eventCPUHigh": "Высокая загрузка CPU",
|
||||
"eventCPUHighDetail": "CPU: {{ .Detail }}",
|
||||
"eventLoginFallback": "Неудачный вход с {{ .Source }}",
|
||||
"eventDelayDetail": "Задержка: {{ .Delay }} мс",
|
||||
"eventErrorDetail": "Ошибка: {{ .Error }}",
|
||||
"eventNodeDown": "Узел {{ .Name }} НЕДОСТУПЕН",
|
||||
"eventNodeUp": "Узел {{ .Name }} В СЕТИ"
|
||||
},
|
||||
"buttons": {
|
||||
"closeKeyboard": "❌ Закрыть клавиатуру",
|
||||
@@ -1773,5 +1846,37 @@
|
||||
"chooseClient": "Выберите клиента для входящего подключения {{ .Inbound }}",
|
||||
"chooseInbound": "Выберите входящее подключение"
|
||||
}
|
||||
},
|
||||
"email": {
|
||||
"subjectOutboundDown": "Исходящее подключение {{ .Tag }} НЕДОСТУПНО",
|
||||
"subjectOutboundUp": "Исходящее подключение {{ .Tag }} РАБОТАЕТ",
|
||||
"subjectXrayCrash": "Сбой Xray",
|
||||
"subjectCPUHigh": "Высокая загрузка CPU",
|
||||
"subjectLoginSuccess": "Успешный вход",
|
||||
"subjectLoginFailed": "Неудачный вход",
|
||||
"titleOutboundDown": "Исходящее подключение НЕДОСТУПНО",
|
||||
"titleOutboundUp": "Исходящее подключение РАБОТАЕТ",
|
||||
"titleXrayCrash": "Сбой Xray",
|
||||
"titleCPUHigh": "Высокая загрузка CPU",
|
||||
"titleLoginSuccess": "Успешный вход",
|
||||
"titleLoginFailed": "Неудачный вход",
|
||||
"labelStatus": "Статус",
|
||||
"labelOutbound": "Исходящее подключение",
|
||||
"labelError": "Ошибка",
|
||||
"labelDelay": "Задержка",
|
||||
"labelDetail": "Подробности",
|
||||
"labelUsername": "Имя пользователя",
|
||||
"labelIP": "IP",
|
||||
"labelReason": "Причина",
|
||||
"labelSource": "Источник",
|
||||
"labelTime": "Время",
|
||||
"statusCrashed": "СБОЙ",
|
||||
"statusRunning": "Работает",
|
||||
"statusHigh": "ВЫСОКАЯ",
|
||||
"statusSuccess": "УСПЕШНО",
|
||||
"statusFailed": "НЕУДАЧНО",
|
||||
"statusDown": "НЕДОСТУПЕН",
|
||||
"statusUp": "РАБОТАЕТ",
|
||||
"labelNode": "Узел"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user