mirror of
https://gh-proxy.org/https://github.com/klinsmaya/new-api.git
synced 2026-11-08 17:36:59 +08:00
* feat(i18n): translate web console messages in the frontend and AI-client errors in the backend
Chinese text was hard-coded in API messages, stored log content, emails and
server logs, so it reached users of every interface language.
Text is now translated where its reader is:
- Web console APIs return the English source text as message_key with
message_params, and the web console translates it in all seven languages.
message keeps the English text for other API callers.
- Errors returned to AI clients, emails and notifications are translated by
the backend (en, zh-CN, zh-TW) in the language saved on the account, then
the language of the request's Accept-Language header.
- A reader who states no language still gets the original Chinese text of the
messages that were Chinese before, word for word. Gateways that use another
new-api as their upstream match that text, for example to disable a channel
whose account ran out of quota.
- Usage, top-up and system log content is stored as content_parts (key and
params) and rendered in the viewer's language. Task fail reasons and refund
reasons written by the gateway are English keys. Rows written earlier are
shown as before.
- Server logs are English.
Also:
- The saved interface language zhTW, and zh-HK, zh-MO and zh-Hant, now select
Traditional Chinese in the backend instead of Simplified Chinese.
- The built-in group descriptions are translated; descriptions an
administrator saved are shown as written.
- .agents/rules/i18n.md records the conventions. Tests in i18n/ fail on a
non-English string literal, on a web console message without translations
and on a locale key without a constant.
* feat(i18n): print server logs in Chinese when LOG_LANGUAGE asks for it
Server log lines are English by default. With LOG_LANGUAGE=zh-CN, the lines
that were Chinese before print their original Chinese text.
common.LogText formats a log line from its English format, which is also the
key of its Chinese text in common/log_text.zh-CN.json. A line without an entry
prints in English. go vet checks the arguments of every call, and
TestServerLogTexts checks that each entry still matches a call and has the
same verbs as its key.
* docs: list LOG_LANGUAGE in the docker compose example
* feat(i18n): translate every server log line and add DEFAULT_LANGUAGE
Every line the gateway prints goes through common.LogText. With
DEFAULT_LANGUAGE=zh-CN, the lines that have a Chinese text in
common/log_text.zh-CN.json print it and the others print English.
DEFAULT_LANGUAGE replaces LOG_LANGUAGE. It also sets the language of
backend messages, emails and notifications for a reader who states no
language: en, zh-CN or zh-TW, English when unset. The list of messages
that stayed Chinese for such readers is removed.
Review fixes:
- Channel test logs store the token name "Model test"; the console shows
it in the interface language.
- Task fail reasons written by the gateway are fixed sentences the console
translates. The HTTP status and the upstream detail go to the server log
when a polled task is failed.
- The auto-disable reason of a slow channel is written in DEFAULT_LANGUAGE.
Also:
- Drop the repository-scanning lint tests, the i18n rules file and its
read gate. AGENTS.md keeps the conventions in four lines.
- Payment error toasts keep their previous text and only add the
translated message key.
- Remove guards and helpers that no caller needs.
* fix(i18n): address review on language lookup, notices and error responses
- Relay requests no longer load the user a second time to find the
language: the settings TokenAuth put into the request are used as they
are, also when they hold no language.
- Upstream model update notices are rendered in each recipient's saved
language, DEFAULT_LANGUAGE when none.
- /api/usage/token and /api/log/token answer with backend-translated
messages again, with the keys and status codes used before this PR.
Their callers are scripts, not the web console.
- Webhook notifications fill {{value}} placeholders like the other
senders. Running the rendered text through Sprintf appended
%!(EXTRA ...) and broke %2F in links.
- RootUserLanguage reads the setting of the root user it already loaded.
- zh_TW and zh_HK are read as Traditional Chinese.
- Add common.ApiErrorStatus for error responses under another HTTP status
and use it where those responses were built by hand.
- Remove middleware.GetLanguage, which had no callers.
327 lines
12 KiB
Go
327 lines
12 KiB
Go
package controller
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/QuantumNous/new-api/common"
|
|
"github.com/QuantumNous/new-api/constant"
|
|
"github.com/QuantumNous/new-api/i18n"
|
|
"github.com/QuantumNous/new-api/logger"
|
|
"github.com/QuantumNous/new-api/middleware"
|
|
"github.com/QuantumNous/new-api/model"
|
|
"github.com/QuantumNous/new-api/oauth"
|
|
"github.com/QuantumNous/new-api/service"
|
|
"github.com/QuantumNous/new-api/setting"
|
|
"github.com/QuantumNous/new-api/setting/console_setting"
|
|
"github.com/QuantumNous/new-api/setting/operation_setting"
|
|
"github.com/QuantumNous/new-api/setting/system_setting"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func TestStatus(c *gin.Context) {
|
|
err := model.PingDB()
|
|
if err != nil {
|
|
writeAccountStatusError(c, http.StatusServiceUnavailable, "Database connection failed")
|
|
return
|
|
}
|
|
// 获取HTTP统计信息
|
|
httpStats := middleware.GetStats()
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"success": true,
|
|
"message": "Server is running",
|
|
"http_stats": httpStats,
|
|
})
|
|
return
|
|
}
|
|
|
|
func GetStatus(c *gin.Context) {
|
|
|
|
cs := console_setting.GetConsoleSetting()
|
|
passkeySetting := system_setting.PasskeySettingsSnapshot()
|
|
common.OptionMapRWMutex.RLock()
|
|
defer common.OptionMapRWMutex.RUnlock()
|
|
|
|
legalSetting := system_setting.GetLegalSettings()
|
|
|
|
data := gin.H{
|
|
"version": common.Version,
|
|
"start_time": common.StartTime,
|
|
"email_verification": common.EmailVerificationEnabled,
|
|
"github_oauth": common.GitHubOAuthEnabled,
|
|
"github_client_id": common.GitHubClientId,
|
|
"discord_oauth": system_setting.GetDiscordSettings().Enabled,
|
|
"discord_client_id": system_setting.GetDiscordSettings().ClientId,
|
|
"linuxdo_oauth": common.LinuxDOOAuthEnabled,
|
|
"linuxdo_client_id": common.LinuxDOClientId,
|
|
"linuxdo_minimum_trust_level": common.LinuxDOMinimumTrustLevel,
|
|
"telegram_oauth": common.TelegramOAuthEnabled,
|
|
"telegram_oauth_configured": oauth.TelegramConfigurationError() == nil,
|
|
"telegram_bot_name": common.TelegramBotName,
|
|
"theme": "default",
|
|
"system_name": common.SystemName,
|
|
"logo": common.Logo,
|
|
"footer_html": common.Footer,
|
|
"wechat_qrcode": common.WeChatAccountQRCodeImageURL,
|
|
"wechat_login": common.WeChatAuthEnabled,
|
|
"server_address": system_setting.ServerAddress,
|
|
"turnstile_check": common.TurnstileCheckEnabled,
|
|
"turnstile_site_key": common.TurnstileSiteKey,
|
|
"docs_link": operation_setting.GetGeneralSetting().DocsLink,
|
|
"quota_per_unit": common.QuotaPerUnit,
|
|
// 兼容旧前端:保留 display_in_currency,同时提供新的 quota_display_type
|
|
"display_in_currency": operation_setting.IsCurrencyDisplay(),
|
|
"quota_display_type": operation_setting.GetQuotaDisplayType(),
|
|
"custom_currency_symbol": operation_setting.GetGeneralSetting().CustomCurrencySymbol,
|
|
"custom_currency_exchange_rate": operation_setting.GetGeneralSetting().CustomCurrencyExchangeRate,
|
|
"enable_batch_update": common.BatchUpdateEnabled,
|
|
"enable_drawing": common.DrawingEnabled,
|
|
"enable_task": common.TaskEnabled,
|
|
"enable_data_export": common.DataExportEnabled,
|
|
"data_export_default_time": common.DataExportDefaultTime,
|
|
"default_collapse_sidebar": common.DefaultCollapseSidebar,
|
|
"mj_notify_enabled": setting.MjNotifyEnabled,
|
|
"chats": setting.Chats,
|
|
"demo_site_enabled": operation_setting.DemoSiteEnabled,
|
|
"self_use_mode_enabled": operation_setting.SelfUseModeEnabled,
|
|
"register_enabled": common.RegisterEnabled,
|
|
"password_login_enabled": common.PasswordLoginEnabled,
|
|
"password_register_enabled": common.PasswordRegisterEnabled,
|
|
"default_use_auto_group": setting.DefaultUseAutoGroup,
|
|
|
|
"password_login_encryption_enabled": common.PasswordLoginEncryptionEnabled,
|
|
|
|
"usd_exchange_rate": operation_setting.USDExchangeRate,
|
|
"price": operation_setting.Price,
|
|
"stripe_unit_price": setting.StripeUnitPrice,
|
|
|
|
// 面板启用开关
|
|
"api_info_enabled": cs.ApiInfoEnabled,
|
|
"uptime_kuma_enabled": cs.UptimeKumaEnabled,
|
|
"announcements_enabled": cs.AnnouncementsEnabled,
|
|
"faq_enabled": cs.FAQEnabled,
|
|
|
|
// 模块管理配置
|
|
"HeaderNavModules": common.OptionMap["HeaderNavModules"],
|
|
"SidebarModulesAdmin": common.OptionMap["SidebarModulesAdmin"],
|
|
|
|
"oidc_enabled": system_setting.GetOIDCSettings().Enabled,
|
|
"oidc_client_id": system_setting.GetOIDCSettings().ClientId,
|
|
"oidc_authorization_endpoint": system_setting.GetOIDCSettings().AuthorizationEndpoint,
|
|
"oidc_display_name": system_setting.GetOIDCSettings().GetEffectiveDisplayName(),
|
|
"passkey_login": passkeySetting.Enabled,
|
|
"passkey_display_name": passkeySetting.RPDisplayName,
|
|
"passkey_rp_id": passkeySetting.EffectiveRPID(),
|
|
"passkey_rp_ids": passkeySetting.RelyingPartyIDs(),
|
|
"passkey_allow_insecure": passkeySetting.AllowInsecureOrigin,
|
|
"passkey_user_verification": passkeySetting.UserVerification,
|
|
"passkey_attachment": passkeySetting.AttachmentPreference,
|
|
"setup": constant.Setup,
|
|
"user_agreement_enabled": legalSetting.UserAgreement != "",
|
|
"privacy_policy_enabled": legalSetting.PrivacyPolicy != "",
|
|
"checkin_enabled": operation_setting.GetCheckinSetting().Enabled,
|
|
}
|
|
|
|
// 根据启用状态注入可选内容
|
|
if cs.ApiInfoEnabled {
|
|
data["api_info"] = console_setting.GetApiInfo()
|
|
}
|
|
if cs.AnnouncementsEnabled {
|
|
data["announcements"] = console_setting.GetAnnouncements()
|
|
}
|
|
if cs.FAQEnabled {
|
|
data["faq"] = console_setting.GetFAQ()
|
|
}
|
|
|
|
// Add enabled custom OAuth providers
|
|
customProviders := oauth.GetEnabledCustomProviders()
|
|
if len(customProviders) > 0 {
|
|
type CustomOAuthInfo struct {
|
|
Id int `json:"id"`
|
|
Name string `json:"name"`
|
|
Slug string `json:"slug"`
|
|
Icon string `json:"icon"`
|
|
ClientId string `json:"client_id"`
|
|
AuthorizationEndpoint string `json:"authorization_endpoint"`
|
|
Scopes string `json:"scopes"`
|
|
}
|
|
providersInfo := make([]CustomOAuthInfo, 0, len(customProviders))
|
|
for _, p := range customProviders {
|
|
config := p.GetConfig()
|
|
providersInfo = append(providersInfo, CustomOAuthInfo{
|
|
Id: config.Id,
|
|
Name: config.Name,
|
|
Slug: config.Slug,
|
|
Icon: config.Icon,
|
|
ClientId: config.ClientId,
|
|
AuthorizationEndpoint: config.AuthorizationEndpoint,
|
|
Scopes: config.Scopes,
|
|
})
|
|
}
|
|
data["custom_oauth_providers"] = providersInfo
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"success": true,
|
|
"message": "",
|
|
"data": data,
|
|
})
|
|
return
|
|
}
|
|
|
|
func GetNotice(c *gin.Context) {
|
|
common.OptionMapRWMutex.RLock()
|
|
notice := common.OptionMap["Notice"]
|
|
common.OptionMapRWMutex.RUnlock()
|
|
serveRevalidatedJSON(c, notice)
|
|
}
|
|
|
|
func GetAbout(c *gin.Context) {
|
|
common.OptionMapRWMutex.RLock()
|
|
about := common.OptionMap["About"]
|
|
common.OptionMapRWMutex.RUnlock()
|
|
serveRevalidatedJSON(c, about)
|
|
}
|
|
|
|
func GetUserAgreement(c *gin.Context) {
|
|
serveRevalidatedJSON(c, system_setting.GetLegalSettings().UserAgreement)
|
|
}
|
|
|
|
func GetPrivacyPolicy(c *gin.Context) {
|
|
serveRevalidatedJSON(c, system_setting.GetLegalSettings().PrivacyPolicy)
|
|
}
|
|
|
|
func GetMidjourney(c *gin.Context) {
|
|
common.OptionMapRWMutex.RLock()
|
|
defer common.OptionMapRWMutex.RUnlock()
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"success": true,
|
|
"message": "",
|
|
"data": common.OptionMap["Midjourney"],
|
|
})
|
|
return
|
|
}
|
|
|
|
func GetHomePageContent(c *gin.Context) {
|
|
common.OptionMapRWMutex.RLock()
|
|
homePageContent := common.OptionMap["HomePageContent"]
|
|
common.OptionMapRWMutex.RUnlock()
|
|
serveRevalidatedJSON(c, homePageContent)
|
|
}
|
|
|
|
func SendEmailVerification(c *gin.Context) {
|
|
email, err := service.ValidateAccountEmail(c.Query("email"))
|
|
if err != nil {
|
|
writeSecurityOperationError(c, err)
|
|
return
|
|
}
|
|
|
|
if model.IsEmailAlreadyTaken(email) {
|
|
common.ApiErrorT(c, "Email address is already in use")
|
|
return
|
|
}
|
|
code := common.GenerateVerificationCode(6)
|
|
common.RegisterVerificationCodeWithKey(email, code, common.EmailVerificationPurpose)
|
|
// The address may not belong to an account yet, so the mail follows the
|
|
// request language.
|
|
systemName := map[string]any{"SystemName": common.SystemName}
|
|
subject := i18n.T(c, i18n.MsgEmailVerificationSubject, systemName)
|
|
content := fmt.Sprintf("<p>%s</p>"+
|
|
"<p>%s</p>"+
|
|
"<p>%s</p>",
|
|
i18n.T(c, i18n.MsgEmailVerificationGreeting, systemName),
|
|
i18n.T(c, i18n.MsgEmailVerificationCode, map[string]any{"Code": code}),
|
|
i18n.T(c, i18n.MsgEmailVerificationValidity, map[string]any{"Minutes": common.VerificationValidMinutes}))
|
|
err = common.SendEmail(subject, email, content)
|
|
if err != nil {
|
|
common.ApiError(c, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"success": true,
|
|
"message": "",
|
|
})
|
|
return
|
|
}
|
|
|
|
func SendPasswordResetEmail(c *gin.Context) {
|
|
email := model.NormalizeEmail(c.Query("email"))
|
|
if err := common.Validate.Var(email, "required,email"); err != nil {
|
|
common.ApiErrorT(c, "Invalid parameters")
|
|
return
|
|
}
|
|
if user, err := model.GetUniqueUserByEmail(email); err == nil {
|
|
code := common.GenerateVerificationCode(0)
|
|
common.RegisterVerificationCodeWithKey(email, code, common.PasswordResetPurpose)
|
|
link := fmt.Sprintf("%s/user/reset?email=%s&token=%s", system_setting.ServerAddress, email, code)
|
|
lang := user.GetSetting().Language
|
|
if lang == "" {
|
|
lang = i18n.StatedLang(c)
|
|
}
|
|
systemName := map[string]any{"SystemName": common.SystemName}
|
|
linkParams := map[string]any{"Link": link}
|
|
subject := i18n.Translate(lang, i18n.MsgEmailPasswordResetSubject, systemName)
|
|
content := fmt.Sprintf("<p>%s</p>"+
|
|
"<p>%s</p>"+
|
|
"<p>%s </p>"+
|
|
"<p>%s</p>",
|
|
i18n.Translate(lang, i18n.MsgEmailPasswordResetGreeting, systemName),
|
|
i18n.Translate(lang, i18n.MsgEmailPasswordResetLink, linkParams),
|
|
i18n.Translate(lang, i18n.MsgEmailPasswordResetLinkFallback, linkParams),
|
|
i18n.Translate(lang, i18n.MsgEmailPasswordResetValidity, map[string]any{"Minutes": common.VerificationValidMinutes}))
|
|
err := common.SendEmail(subject, email, content)
|
|
if err != nil {
|
|
logger.LogError(c.Request.Context(), common.LogText("failed to send password reset email to %s: %s", email, err.Error()))
|
|
}
|
|
} else if err != nil && !errors.Is(err, model.ErrEmailNotFound) {
|
|
logger.LogWarn(c.Request.Context(), common.LogText("skip password reset email for %s: %s", email, err.Error()))
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"success": true,
|
|
"message": "",
|
|
})
|
|
}
|
|
|
|
type PasswordResetRequest struct {
|
|
Email string `json:"email"`
|
|
Token string `json:"token"`
|
|
}
|
|
|
|
func ResetPassword(c *gin.Context) {
|
|
var req PasswordResetRequest
|
|
err := json.NewDecoder(c.Request.Body).Decode(&req)
|
|
if err != nil {
|
|
common.ApiError(c, err)
|
|
return
|
|
}
|
|
req.Email = model.NormalizeEmail(req.Email)
|
|
if req.Email == "" || req.Token == "" {
|
|
common.ApiErrorT(c, "Invalid parameters")
|
|
return
|
|
}
|
|
if !common.VerifyCodeWithKey(req.Email, req.Token, common.PasswordResetPurpose) {
|
|
common.ApiErrorT(c, "Password reset link is invalid or has expired")
|
|
return
|
|
}
|
|
password := common.GenerateVerificationCode(12)
|
|
err = model.ResetUserPasswordByEmail(req.Email, password)
|
|
if err != nil {
|
|
if errors.Is(err, model.ErrEmailNotFound) || errors.Is(err, model.ErrEmailAmbiguous) {
|
|
common.ApiErrorT(c, "Password reset link is invalid or has expired")
|
|
return
|
|
}
|
|
common.ApiError(c, err)
|
|
return
|
|
}
|
|
common.DeleteKey(req.Email, common.PasswordResetPurpose)
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"success": true,
|
|
"message": "",
|
|
"data": password,
|
|
})
|
|
return
|
|
}
|