mirror of
https://github.com/QuantumNous/new-api.git
synced 2026-12-05 08:03:01 +00:00
* feat(plugins): add provider plugins, request plugins and a community marketplace - Provider plugins turn an upstream vendor into a channel type: routes, protocol conversion, models, static keys, sign-in flows with token refresh, balance queries, per-channel config and a scheduled hook. - Request plugins run on requests and replies (ingress, request, outbound, egress, reply, report), with instances by scope, model ranges, dry runs and per-log records. Built-ins: request filter, request redaction, parameter override, auto reasoning effort, image compression and content moderation. Sensitive words move into a request filter instance on first start. - Node sync: a system_sync_topics table lets every node reload settings, channels, plugins and other data within seconds, and the system info page shows each node's state. - Marketplace: a community source next to the official one, lookup by plugin code for official and community plugins, key rules for community plugins, install counts and takedown warnings. * docs(plugins): name request protocols and host-only members in the plugin API - Protocol names: ctx.format and samples use relaykit's protocol names. The spec lists the client paths and body of each name, so every host passes the same names to plugins. - Host-specific members: channel, group, user, token, channelTypes, channelOther and utils.paramOverride exist only on new-api. The types mark them optional. - Relay routes: the spec now writes out the route keys and the converters each incoming path accepts. The schema lists the converter names. * feat(plugins): show recommended plugins from the official list too The site now marks official plugins as recommended in its index. The built-in official and community lists both get a Recommended group; lists added by the administrator still cannot recommend plugins. * feat(plugins): fall back to www.newapi.pro when www.newapi.ai does not answer Plugin lists, plugin files and logos from www.newapi.ai are downloaded from www.newapi.pro, the mainland China site, when newapi.ai gives no answer within 10 seconds; the browser remembers this for a day. The marketplace toolbar has a download site picker: Auto, or Mainland China to always use www.newapi.pro. Saved source addresses stay on newapi.ai, and every file is still checked against its sha256. Community install counts go to newapi.ai first and to newapi.pro when newapi.ai cannot be reached. * fix(plugins): leaving the page does not switch the plugin site to www.newapi.pro Reloading or leaving the marketplace cancels requests still running. That was read as www.newapi.ai not answering, so the browser moved to www.newapi.pro for a day although newapi.ai was reachable. Requests cut off by leaving the page are no longer counted. * feat(plugins): choose the plugin download site by hand The marketplace no longer switches between plugin sites by itself. The toolbar menu lists the main site www.newapi.ai, the backup site www.newapi.pro and the other plugin lists; picking an entry is the only thing that changes where plugins are downloaded from, and the main site can always be picked again. A browser that the earlier automatic switch had moved to www.newapi.pro opens on the main site again. The download site, the source choice and managing sources now share one menu in the list header. * feat(plugins): show plugin usage guides and require README and changelog Every marketplace plugin version now ships a usage guide, README.md, and a changelog, CHANGELOG.md, next to plugin.js. The install dialog shows the guide in the reader's language when a translation is listed, falls back to English, and links to the source file. A guide or changelog that breaks the format is reported with its file, line and rule instead of being shown. The plugin API document describes both formats, the translations they may list, and the checks the community marketplace runs before it accepts a version: readme_missing, readme_invalid, changelog_missing and changelog_invalid. Versions accepted before these checks are not checked again. * fix(plugins): address review findings on plugin parts, limits and access - Only the root user reads request plugin instance configs; an admin who may bind instances to channels gets them without configs. - Outbound hooks that grow the body are held to MAX_REQUEST_BODY_MB, as ingress hooks are, and answer 413 without a retry. - An admin who cannot read plugin options keeps the balance and model list actions on plugin channels; the server answers whether they work. - Reading the parts of a plugin source gives up when the source does not parse or code elsewhere refers to meta, as the meta preview does. * fix(plugins): address review findings on request processing, documents and node sync - PDF checks resolve indirect parameters and bound every value the parser allocates or loops on: predictor columns, object stream counts, nested object streams, cross-reference streams and ToUnicode ranges. Font and CMap work checks the deadline. - A WebP frame must match its declared canvas, and keyword search stops at its match limit. - Request processing treats a body as JSON whenever the gateway parses it as JSON, keeps Gemini reply parts in place, scopes instances by the settled auto group, hides channel header overrides from plugin param overrides, and captures replies only for report instances in scope. - Request processing no longer follows the plugin master switch, which now covers plugin tasks and channels only. - json.patch copies stop at MAX_REQUEST_BODY_MB, and provider prepareRequest effects past it answer 413. - Image billing reads the count from the final upstream body, including the count members of SiliconFlow, Imagen and Replicate and the Imagen default. - Automatic channel status changes no longer reload every node's channel cache. A credential refresh holds no channel lock while it waits on the vendor. A key that needs login is disabled and the request can retry. - Balance requests must go to the channel host or allowedHosts, and provider stream events a plugin drops keep the stream alive. - Node sync: OAuth provider writes bump inside their transaction, a failed startup load is retried, and each node is judged by its own topics. - request-filter checks the text the old sensitive-word check did, request-redact and content-moderation handle large inputs, and image-compress lossless mode leaves JPEG and WebP alone. * fix(plugins): address the second review on balances, egress and routes - Channel other_info writes (status changes, balance queries and manual multi-key actions) only land while other_info is still the value read, and retry otherwise, so a write on one node no longer overwrites another node's balance or status reason. They write only their own columns. - On the Responses path egress reads the body after the channel finalizes it, which is the body sent upstream. - The Vertex AI plugin picks the region by the model the client asked for, as the built-in Vertex AI channel does. - /request-processing and /security are reserved route namespaces, and a test checks that every console page is reserved. - The plugin API docs say what egress reads on a provider plugin channel. * feat(channels): run the balance update as a system task with progress "Update all balances" now queues a channel_balance system task instead of starting a goroutine guarded by an in-process flag. The task row holds the progress (enabled channels queried of total), so any node can answer it, and its active key keeps one run at a time across nodes. The CHANNEL_UPDATE_FREQUENCY schedule becomes the same task's schedule, so manual and scheduled runs no longer overlap. GET /api/channel/update_balance answers with the task id, and with the running one when a run is already queued. GET /api/channel/update_balance/task/:task_id, under the same channel permission, returns the status, progress and failure of balance update tasks only. The channel list follows the task, reloads as more channels are queried and once more at the end, and reports how the run ended. * feat(system): sync nodes through system tasks and clean up task history Node sync no longer needs its own table. A write to synced data adds a pending sync_<topic> system task. Every node polls the newest task of each topic it keeps every 3 s and reloads when that task is newer than the one it applied. Custom OAuth providers still add their task inside the write transaction, and lock the newest task of the topic first, so tasks commit in id order. The master marks a sync task succeeded once every online node that keeps the topic has applied it. Until then the task shows how many nodes have applied it and why the others have not. The system_sync_topics table is gone. A composite (type, id) index answers the newest task of a type from the index. The latest-per-type and earliest-pending queries now read ids first, because MySQL 5.7 scanned the whole table for them. A daily system_task_cleanup task deletes finished system tasks older than system_task_setting.retention_days (default 30, at least 1), in batches. It never deletes active tasks or the newest task of any type. The retention is set under Operations > Log maintenance.
417 lines
14 KiB
Go
417 lines
14 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"embed"
|
|
"errors"
|
|
"log"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"strconv"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/QuantumNous/new-api/common"
|
|
"github.com/QuantumNous/new-api/constant"
|
|
"github.com/QuantumNous/new-api/controller"
|
|
"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/pkg/jsplugin"
|
|
perfmetrics "github.com/QuantumNous/new-api/pkg/perf_metrics"
|
|
"github.com/QuantumNous/new-api/pkg/wsmanager"
|
|
"github.com/QuantumNous/new-api/relay"
|
|
"github.com/QuantumNous/new-api/relay/requestplugin"
|
|
kitutil "github.com/QuantumNous/new-api/relaykit/relayconvert/kitutil"
|
|
"github.com/QuantumNous/new-api/router"
|
|
"github.com/QuantumNous/new-api/service"
|
|
"github.com/QuantumNous/new-api/service/authz"
|
|
_ "github.com/QuantumNous/new-api/setting/performance_setting"
|
|
"github.com/QuantumNous/new-api/setting/ratio_setting"
|
|
|
|
"github.com/bytedance/gopkg/util/gopool"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/joho/godotenv"
|
|
|
|
_ "net/http/pprof"
|
|
)
|
|
|
|
//go:embed web/dist
|
|
var buildFS embed.FS
|
|
|
|
//go:embed web/dist/index.html
|
|
var indexPage []byte
|
|
|
|
func main() {
|
|
if len(os.Args) > 1 && os.Args[1] == "plugin" {
|
|
os.Exit(jsplugin.RunCLI(os.Args[2:], os.Stdout, os.Stderr))
|
|
}
|
|
startTime := time.Now()
|
|
kitutil.SetLogging(common.SysLog, func(message string) {
|
|
logger.LogError(nil, message)
|
|
})
|
|
kitutil.SetSystemErrorLogging(common.SysError)
|
|
|
|
err := InitResources()
|
|
if err != nil {
|
|
common.FatalLog(common.LogText("failed to initialize resources: %s", err.Error()))
|
|
return
|
|
}
|
|
|
|
common.SysLog(common.LogText("New API %s started", common.Version))
|
|
if os.Getenv("GIN_MODE") != "debug" {
|
|
gin.SetMode(gin.ReleaseMode)
|
|
}
|
|
if common.DebugEnabled {
|
|
common.SysLog(common.LogText("running in debug mode"))
|
|
}
|
|
|
|
kitutil.Debug.Store(common.DebugEnabled)
|
|
|
|
defer func() {
|
|
err := model.CloseDB()
|
|
if err != nil {
|
|
common.FatalLog(common.LogText("failed to close database: %s", err.Error()))
|
|
}
|
|
}()
|
|
|
|
if common.RedisEnabled {
|
|
// for compatibility with old versions
|
|
common.MemoryCacheEnabled = true
|
|
}
|
|
if common.MemoryCacheEnabled {
|
|
common.SysLog(common.LogText("memory cache enabled"))
|
|
common.SysLog(common.LogText("sync frequency: %d seconds", common.SyncFrequency))
|
|
|
|
// Add panic recovery and retry for InitChannelCache
|
|
func() {
|
|
defer func() {
|
|
if r := recover(); r != nil {
|
|
common.SysLog(common.LogText("InitChannelCache panic: %v, retrying once", r))
|
|
// Retry once
|
|
_, _, fixErr := model.FixAbility()
|
|
if fixErr != nil {
|
|
common.FatalLog(common.LogText("InitChannelCache failed: %s", fixErr.Error()))
|
|
}
|
|
}
|
|
}()
|
|
model.InitChannelCache()
|
|
}()
|
|
|
|
go model.SyncChannelCache(common.SyncFrequency)
|
|
}
|
|
wsmanager.StartSubscriber(context.Background())
|
|
|
|
// Warm pricing after channel cache initialization so Advanced Custom
|
|
// endpoint inference can read cached route settings on first request.
|
|
model.GetPricing()
|
|
|
|
// The first plugin sync finishes before the server accepts requests, so no
|
|
// request runs without the uploaded plugins.
|
|
controller.SyncTaskPluginsOnce()
|
|
|
|
// Every node reloads a topic within seconds of a write to it on any node.
|
|
// The periodic reloads below stay for writes that do not bump a topic.
|
|
service.RegisterSyncTopic(model.SyncTopicOptions, func(context.Context) error { return model.LoadOptionsFromDatabase() })
|
|
if common.MemoryCacheEnabled || common.IsMasterNode {
|
|
service.RegisterSyncTopic(model.SyncTopicChannels, func(ctx context.Context) error {
|
|
if common.MemoryCacheEnabled {
|
|
model.InitChannelCache()
|
|
}
|
|
return service.ScanScheduledPlugins(ctx)
|
|
})
|
|
}
|
|
service.RegisterSyncTopic(model.SyncTopicAuthz, func(context.Context) error { return authz.ReloadPolicy() })
|
|
service.RegisterSyncTopic(model.SyncTopicPlugins, controller.SyncTaskPluginsOnceContext)
|
|
service.RegisterSyncTopic(model.SyncTopicOAuthProviders, func(context.Context) error { return oauth.LoadCustomProviders() })
|
|
service.RegisterSyncTopic(model.SyncTopicModels, func(context.Context) error {
|
|
model.RefreshPricing()
|
|
return nil
|
|
})
|
|
if !common.RedisEnabled {
|
|
// With Redis every node shares the plan cache.
|
|
service.RegisterSyncTopic(model.SyncTopicSubscriptionPlans, func(context.Context) error { return model.PurgeSubscriptionPlanCache() })
|
|
}
|
|
service.StartNodeSync()
|
|
|
|
// 热更新配置
|
|
go model.SyncOptions(common.SyncFrequency)
|
|
go controller.SyncTaskPlugins()
|
|
|
|
// 周期性重载授权策略,保证多节点/多 master 部署下权限变更能传播到每个实例
|
|
go authz.StartPolicySync(common.SyncFrequency)
|
|
|
|
// 数据看板
|
|
go model.UpdateQuotaData()
|
|
|
|
// CHANNEL_UPDATE_FREQUENCY schedules the update of all balances, a system
|
|
// task registered below.
|
|
if os.Getenv("CHANNEL_UPDATE_FREQUENCY") != "" {
|
|
if _, err := strconv.Atoi(os.Getenv("CHANNEL_UPDATE_FREQUENCY")); err != nil {
|
|
common.FatalLog(common.LogText("failed to parse CHANNEL_UPDATE_FREQUENCY: %s", err.Error()))
|
|
}
|
|
}
|
|
|
|
// Codex credential auto-refresh check every 10 minutes, refresh when expires within 1 day
|
|
service.StartCodexCredentialAutoRefreshTask()
|
|
|
|
// Plugin credential refresh before expiry, on the master node every minute
|
|
service.StartPluginCredentialRefreshTask()
|
|
|
|
// Subscription quota reset task (daily/weekly/monthly/custom)
|
|
service.StartSubscriptionQuotaResetTask()
|
|
|
|
// Report this process as a system instance so the System Info page can show
|
|
// all currently alive nodes in multi-instance deployments.
|
|
service.StartSystemInstanceReporter()
|
|
|
|
// Wire task polling adaptor factory (breaks service -> relay import cycle).
|
|
// Must run before the system task runner starts: the async_task_poll handler
|
|
// calls service.RunTaskPollingOnce, which needs this factory set.
|
|
service.GetTaskAdaptorFunc = func(platform constant.TaskPlatform) service.TaskPollingAdaptor {
|
|
a := relay.GetTaskAdaptor(platform)
|
|
if a == nil {
|
|
return nil
|
|
}
|
|
return a
|
|
}
|
|
service.ReportTaskFunc = requestplugin.ReportTask
|
|
|
|
// Register the periodic channel test, balance update, upstream model update,
|
|
// and async task polling (Midjourney / Suno / video) jobs as scheduled system tasks
|
|
// (DB-lease dedup across masters + run history), then start the runner that
|
|
// schedules and executes them. Master-only execution and the UpdateTask
|
|
// switch are enforced inside the runner and each handler's Enabled().
|
|
controller.RegisterScheduledSystemTasks()
|
|
service.StartSystemTaskRunner()
|
|
|
|
if os.Getenv("BATCH_UPDATE_ENABLED") == "true" {
|
|
common.BatchUpdateEnabled = true
|
|
common.SysLog(common.LogText("batch update enabled with interval %ss", strconv.Itoa(common.BatchUpdateInterval)))
|
|
model.InitBatchUpdater()
|
|
}
|
|
|
|
host := os.Getenv("HOST")
|
|
if os.Getenv("ENABLE_PPROF") == "true" {
|
|
gopool.Go(func() {
|
|
log.Println(http.ListenAndServe(net.JoinHostPort(host, "8005"), nil))
|
|
})
|
|
go common.Monitor()
|
|
common.SysLog(common.LogText("pprof enabled"))
|
|
}
|
|
|
|
err = common.StartPyroScope()
|
|
if err != nil {
|
|
common.SysError(common.LogText("start pyroscope error : %v", err))
|
|
}
|
|
|
|
// Initialize HTTP server
|
|
server := gin.New()
|
|
if err := middleware.ConfigureTrustedProxies(server); err != nil {
|
|
common.FatalLog(common.LogText("failed to configure trusted proxies: %s", err.Error()))
|
|
return
|
|
}
|
|
server.Use(middleware.PanicRecover())
|
|
// This will cause SSE not to work!!!
|
|
//server.Use(gzip.Gzip(gzip.DefaultCompression))
|
|
server.Use(middleware.RequestId())
|
|
server.Use(middleware.Version())
|
|
server.Use(middleware.I18n())
|
|
middleware.SetUpLogger(server)
|
|
InjectUmamiAnalytics()
|
|
InjectGoogleAnalytics()
|
|
|
|
// 设置路由
|
|
router.SetRouter(server, router.WebAssets{
|
|
BuildFS: buildFS,
|
|
IndexPage: indexPage,
|
|
})
|
|
var port = os.Getenv("PORT")
|
|
if port == "" {
|
|
port = strconv.Itoa(*common.Port)
|
|
}
|
|
|
|
srv := &http.Server{
|
|
Addr: net.JoinHostPort(host, port),
|
|
Handler: server,
|
|
}
|
|
|
|
go func() {
|
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
common.FatalLog(common.LogText("failed to start HTTP server: %s", err.Error()))
|
|
}
|
|
}()
|
|
|
|
time.Sleep(100 * time.Millisecond)
|
|
|
|
common.LogStartupSuccess(startTime, host, port)
|
|
|
|
quit := make(chan os.Signal, 1)
|
|
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
|
sig := <-quit
|
|
common.SysLog(common.LogText("received signal: %v, shutting down...", sig))
|
|
|
|
// SSE streams may run for minutes; give them time to finish before forced exit
|
|
shutdownTimeout := time.Duration(common.GetEnvOrDefault("SHUTDOWN_TIMEOUT_SECONDS", 120)) * time.Second
|
|
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
|
|
defer cancel()
|
|
if err := srv.Shutdown(ctx); err != nil {
|
|
common.SysError(common.LogText("server forced to shutdown: %v", err))
|
|
}
|
|
// 内存中的看板数据保存入库,避免重启丢失未落库数据 (issue #5679)
|
|
if common.DataExportEnabled {
|
|
model.SaveQuotaDataCache()
|
|
}
|
|
common.SysLog(common.LogText("server exited"))
|
|
}
|
|
|
|
func InjectUmamiAnalytics() {
|
|
analyticsInjectBuilder := &strings.Builder{}
|
|
if os.Getenv("UMAMI_WEBSITE_ID") != "" {
|
|
umamiSiteID := os.Getenv("UMAMI_WEBSITE_ID")
|
|
umamiScriptURL := os.Getenv("UMAMI_SCRIPT_URL")
|
|
if umamiScriptURL == "" {
|
|
umamiScriptURL = "https://analytics.umami.is/script.js"
|
|
}
|
|
analyticsInjectBuilder.WriteString("<script defer src=\"")
|
|
analyticsInjectBuilder.WriteString(umamiScriptURL)
|
|
analyticsInjectBuilder.WriteString("\" data-website-id=\"")
|
|
analyticsInjectBuilder.WriteString(umamiSiteID)
|
|
analyticsInjectBuilder.WriteString("\"></script>")
|
|
}
|
|
analyticsInjectBuilder.WriteString("<!--Umami QuantumNous-->\n")
|
|
analyticsInject := []byte(analyticsInjectBuilder.String())
|
|
placeholder := []byte("<!--umami-->\n")
|
|
indexPage = bytes.ReplaceAll(indexPage, placeholder, analyticsInject)
|
|
}
|
|
|
|
func InjectGoogleAnalytics() {
|
|
analyticsInjectBuilder := &strings.Builder{}
|
|
if os.Getenv("GOOGLE_ANALYTICS_ID") != "" {
|
|
gaID := os.Getenv("GOOGLE_ANALYTICS_ID")
|
|
// Google Analytics 4 (gtag.js)
|
|
analyticsInjectBuilder.WriteString("<script async src=\"https://www.googletagmanager.com/gtag/js?id=")
|
|
analyticsInjectBuilder.WriteString(gaID)
|
|
analyticsInjectBuilder.WriteString("\"></script>")
|
|
analyticsInjectBuilder.WriteString("<script>")
|
|
analyticsInjectBuilder.WriteString("window.dataLayer = window.dataLayer || [];")
|
|
analyticsInjectBuilder.WriteString("function gtag(){dataLayer.push(arguments);}")
|
|
analyticsInjectBuilder.WriteString("gtag('js', new Date());")
|
|
analyticsInjectBuilder.WriteString("gtag('config', '")
|
|
analyticsInjectBuilder.WriteString(gaID)
|
|
analyticsInjectBuilder.WriteString("');")
|
|
analyticsInjectBuilder.WriteString("</script>")
|
|
}
|
|
analyticsInjectBuilder.WriteString("<!--Google Analytics QuantumNous-->\n")
|
|
analyticsInject := []byte(analyticsInjectBuilder.String())
|
|
placeholder := []byte("<!--Google Analytics-->\n")
|
|
indexPage = bytes.ReplaceAll(indexPage, placeholder, analyticsInject)
|
|
}
|
|
|
|
func InitResources() error {
|
|
// Initialize resources here if needed
|
|
// This is a placeholder function for future resource initialization
|
|
err := godotenv.Load(".env")
|
|
if err != nil {
|
|
if common.DebugEnabled {
|
|
common.SysLog(common.LogText("No .env file found, using default environment variables. If needed, please create a .env file and set the relevant variables."))
|
|
}
|
|
}
|
|
|
|
// 加载环境变量
|
|
common.InitEnv()
|
|
|
|
logger.SetupLogger()
|
|
|
|
// Initialize model settings
|
|
ratio_setting.InitRatioSettings()
|
|
|
|
service.InitHttpClient()
|
|
|
|
// Initialize SQL Database
|
|
err = model.InitDB()
|
|
if err != nil {
|
|
common.FatalLog(common.LogText("failed to initialize database: %s", err.Error()))
|
|
return err
|
|
}
|
|
// Before the loads below: a write made while they run is reloaded later.
|
|
service.ReadStartupSyncRevisions()
|
|
if err = authz.Init(model.DB); err != nil {
|
|
common.FatalLog(common.LogText("failed to initialize authorization: %s", err.Error()))
|
|
return err
|
|
}
|
|
if common.IsMasterNode {
|
|
// The master rewrote the built-in role policies.
|
|
model.BumpSyncTopic(model.SyncTopicAuthz)
|
|
}
|
|
if common.PasswordLoginEncryptionEnabled {
|
|
if err = model.InitPasswordEncryption(); err != nil {
|
|
common.FatalLog(common.LogText("failed to initialize password encryption: %s", err.Error()))
|
|
return err
|
|
}
|
|
}
|
|
|
|
model.CheckSetup()
|
|
|
|
// Initialize options, should after model.InitDB()
|
|
if common.IsMasterNode {
|
|
if err := model.MigrateRetiredFrontendOptions(); err != nil {
|
|
common.SysError(common.LogText("failed to migrate retired frontend options: %s", err.Error()))
|
|
}
|
|
if err := model.MigrateSensitiveWords(); err != nil {
|
|
common.SysError(common.LogText("failed to migrate sensitive words: %s", err.Error()))
|
|
}
|
|
}
|
|
model.InitOptionMap()
|
|
|
|
// 清理旧的磁盘缓存文件
|
|
common.CleanupOldCacheFiles()
|
|
|
|
// Initialize SQL Database
|
|
err = model.InitLogDB()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Initialize Redis
|
|
err = common.InitRedisClient()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
perfmetrics.Init()
|
|
|
|
// 启动系统监控
|
|
common.StartSystemMonitor()
|
|
|
|
// Initialize i18n
|
|
err = i18n.Init()
|
|
if err != nil {
|
|
common.SysError(common.LogText("failed to initialize i18n: %s", err.Error()))
|
|
// Don't return error, i18n is not critical
|
|
} else {
|
|
common.SysLog(common.LogText("i18n initialized with languages: %s", strings.Join(i18n.SupportedLanguages(), ", ")))
|
|
}
|
|
// Register user language loader for lazy loading
|
|
i18n.SetUserLangLoader(model.GetUserLanguage)
|
|
|
|
// Load custom OAuth providers from database
|
|
err = oauth.LoadCustomProviders()
|
|
if err != nil {
|
|
common.SysError(common.LogText("failed to load custom OAuth providers: %s", err.Error()))
|
|
// Don't return error, custom OAuth is not critical
|
|
// The node sync loads them again on its first tick.
|
|
service.SyncTopicLoadFailed(model.SyncTopicOAuthProviders, err)
|
|
}
|
|
|
|
service.StartAuthArtifactCleanup()
|
|
|
|
return nil
|
|
}
|