main.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. package main
  2. import (
  3. "bytes"
  4. "embed"
  5. "fmt"
  6. "log"
  7. "net/http"
  8. "os"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/QuantumNous/new-api/common"
  13. "github.com/QuantumNous/new-api/constant"
  14. "github.com/QuantumNous/new-api/controller"
  15. "github.com/QuantumNous/new-api/i18n"
  16. "github.com/QuantumNous/new-api/logger"
  17. "github.com/QuantumNous/new-api/middleware"
  18. "github.com/QuantumNous/new-api/model"
  19. "github.com/QuantumNous/new-api/oauth"
  20. perfmetrics "github.com/QuantumNous/new-api/pkg/perf_metrics"
  21. "github.com/QuantumNous/new-api/relay"
  22. "github.com/QuantumNous/new-api/router"
  23. "github.com/QuantumNous/new-api/service"
  24. _ "github.com/QuantumNous/new-api/setting/performance_setting"
  25. "github.com/QuantumNous/new-api/setting/ratio_setting"
  26. "github.com/bytedance/gopkg/util/gopool"
  27. "github.com/gin-contrib/sessions"
  28. "github.com/gin-contrib/sessions/cookie"
  29. "github.com/gin-gonic/gin"
  30. "github.com/joho/godotenv"
  31. _ "net/http/pprof"
  32. )
  33. //go:embed web/default/dist
  34. var buildFS embed.FS
  35. //go:embed web/default/dist/index.html
  36. var indexPage []byte
  37. //go:embed web/classic/dist
  38. var classicBuildFS embed.FS
  39. //go:embed web/classic/dist/index.html
  40. var classicIndexPage []byte
  41. func main() {
  42. startTime := time.Now()
  43. err := InitResources()
  44. if err != nil {
  45. common.FatalLog("failed to initialize resources: " + err.Error())
  46. return
  47. }
  48. common.SysLog("New API " + common.Version + " started")
  49. if os.Getenv("GIN_MODE") != "debug" {
  50. gin.SetMode(gin.ReleaseMode)
  51. }
  52. if common.DebugEnabled {
  53. common.SysLog("running in debug mode")
  54. }
  55. defer func() {
  56. err := model.CloseDB()
  57. if err != nil {
  58. common.FatalLog("failed to close database: " + err.Error())
  59. }
  60. }()
  61. if common.RedisEnabled {
  62. // for compatibility with old versions
  63. common.MemoryCacheEnabled = true
  64. }
  65. if common.MemoryCacheEnabled {
  66. common.SysLog("memory cache enabled")
  67. common.SysLog(fmt.Sprintf("sync frequency: %d seconds", common.SyncFrequency))
  68. // Add panic recovery and retry for InitChannelCache
  69. func() {
  70. defer func() {
  71. if r := recover(); r != nil {
  72. common.SysLog(fmt.Sprintf("InitChannelCache panic: %v, retrying once", r))
  73. // Retry once
  74. _, _, fixErr := model.FixAbility()
  75. if fixErr != nil {
  76. common.FatalLog(fmt.Sprintf("InitChannelCache failed: %s", fixErr.Error()))
  77. }
  78. }
  79. }()
  80. model.InitChannelCache()
  81. }()
  82. go model.SyncChannelCache(common.SyncFrequency)
  83. }
  84. // 热更新配置
  85. go model.SyncOptions(common.SyncFrequency)
  86. // 数据看板
  87. go model.UpdateQuotaData()
  88. if os.Getenv("CHANNEL_UPDATE_FREQUENCY") != "" {
  89. frequency, err := strconv.Atoi(os.Getenv("CHANNEL_UPDATE_FREQUENCY"))
  90. if err != nil {
  91. common.FatalLog("failed to parse CHANNEL_UPDATE_FREQUENCY: " + err.Error())
  92. }
  93. go controller.AutomaticallyUpdateChannels(frequency)
  94. }
  95. go controller.AutomaticallyTestChannels()
  96. // Codex credential auto-refresh check every 10 minutes, refresh when expires within 1 day
  97. service.StartCodexCredentialAutoRefreshTask()
  98. // Subscription quota reset task (daily/weekly/monthly/custom)
  99. service.StartSubscriptionQuotaResetTask()
  100. // Wire task polling adaptor factory (breaks service -> relay import cycle)
  101. service.GetTaskAdaptorFunc = func(platform constant.TaskPlatform) service.TaskPollingAdaptor {
  102. a := relay.GetTaskAdaptor(platform)
  103. if a == nil {
  104. return nil
  105. }
  106. return a
  107. }
  108. // Channel upstream model update check task
  109. controller.StartChannelUpstreamModelUpdateTask()
  110. if common.IsMasterNode && constant.UpdateTask {
  111. gopool.Go(func() {
  112. controller.UpdateMidjourneyTaskBulk()
  113. })
  114. gopool.Go(func() {
  115. controller.UpdateTaskBulk()
  116. })
  117. }
  118. if os.Getenv("BATCH_UPDATE_ENABLED") == "true" {
  119. common.BatchUpdateEnabled = true
  120. common.SysLog("batch update enabled with interval " + strconv.Itoa(common.BatchUpdateInterval) + "s")
  121. model.InitBatchUpdater()
  122. }
  123. if os.Getenv("ENABLE_PPROF") == "true" {
  124. gopool.Go(func() {
  125. log.Println(http.ListenAndServe("0.0.0.0:8005", nil))
  126. })
  127. go common.Monitor()
  128. common.SysLog("pprof enabled")
  129. }
  130. err = common.StartPyroScope()
  131. if err != nil {
  132. common.SysError(fmt.Sprintf("start pyroscope error : %v", err))
  133. }
  134. // Initialize HTTP server
  135. server := gin.New()
  136. server.Use(gin.CustomRecovery(func(c *gin.Context, err any) {
  137. common.SysLog(fmt.Sprintf("panic detected: %v", err))
  138. c.JSON(http.StatusInternalServerError, gin.H{
  139. "error": gin.H{
  140. "message": fmt.Sprintf("Panic detected, error: %v. Please submit a issue here: https://github.com/Calcium-Ion/new-api", err),
  141. "type": "new_api_panic",
  142. },
  143. })
  144. }))
  145. // This will cause SSE not to work!!!
  146. //server.Use(gzip.Gzip(gzip.DefaultCompression))
  147. server.Use(middleware.RequestId())
  148. server.Use(middleware.PoweredBy())
  149. server.Use(middleware.I18n())
  150. middleware.SetUpLogger(server)
  151. // Initialize session store
  152. store := cookie.NewStore([]byte(common.SessionSecret))
  153. store.Options(sessions.Options{
  154. Path: "/",
  155. MaxAge: 2592000, // 30 days
  156. HttpOnly: true,
  157. Secure: false,
  158. SameSite: http.SameSiteStrictMode,
  159. })
  160. server.Use(sessions.Sessions("session", store))
  161. InjectUmamiAnalytics()
  162. InjectGoogleAnalytics()
  163. // 设置路由
  164. router.SetRouter(server, router.ThemeAssets{
  165. DefaultBuildFS: buildFS,
  166. DefaultIndexPage: indexPage,
  167. ClassicBuildFS: classicBuildFS,
  168. ClassicIndexPage: classicIndexPage,
  169. })
  170. var port = os.Getenv("PORT")
  171. if port == "" {
  172. port = strconv.Itoa(*common.Port)
  173. }
  174. // Log startup success message
  175. common.LogStartupSuccess(startTime, port)
  176. err = server.Run(":" + port)
  177. if err != nil {
  178. common.FatalLog("failed to start HTTP server: " + err.Error())
  179. }
  180. }
  181. func InjectUmamiAnalytics() {
  182. analyticsInjectBuilder := &strings.Builder{}
  183. if os.Getenv("UMAMI_WEBSITE_ID") != "" {
  184. umamiSiteID := os.Getenv("UMAMI_WEBSITE_ID")
  185. umamiScriptURL := os.Getenv("UMAMI_SCRIPT_URL")
  186. if umamiScriptURL == "" {
  187. umamiScriptURL = "https://analytics.umami.is/script.js"
  188. }
  189. analyticsInjectBuilder.WriteString("<script defer src=\"")
  190. analyticsInjectBuilder.WriteString(umamiScriptURL)
  191. analyticsInjectBuilder.WriteString("\" data-website-id=\"")
  192. analyticsInjectBuilder.WriteString(umamiSiteID)
  193. analyticsInjectBuilder.WriteString("\"></script>")
  194. }
  195. analyticsInjectBuilder.WriteString("<!--Umami QuantumNous-->\n")
  196. analyticsInject := []byte(analyticsInjectBuilder.String())
  197. placeholder := []byte("<!--umami-->\n")
  198. indexPage = bytes.ReplaceAll(indexPage, placeholder, analyticsInject)
  199. classicIndexPage = bytes.ReplaceAll(classicIndexPage, placeholder, analyticsInject)
  200. }
  201. func InjectGoogleAnalytics() {
  202. analyticsInjectBuilder := &strings.Builder{}
  203. if os.Getenv("GOOGLE_ANALYTICS_ID") != "" {
  204. gaID := os.Getenv("GOOGLE_ANALYTICS_ID")
  205. // Google Analytics 4 (gtag.js)
  206. analyticsInjectBuilder.WriteString("<script async src=\"https://www.googletagmanager.com/gtag/js?id=")
  207. analyticsInjectBuilder.WriteString(gaID)
  208. analyticsInjectBuilder.WriteString("\"></script>")
  209. analyticsInjectBuilder.WriteString("<script>")
  210. analyticsInjectBuilder.WriteString("window.dataLayer = window.dataLayer || [];")
  211. analyticsInjectBuilder.WriteString("function gtag(){dataLayer.push(arguments);}")
  212. analyticsInjectBuilder.WriteString("gtag('js', new Date());")
  213. analyticsInjectBuilder.WriteString("gtag('config', '")
  214. analyticsInjectBuilder.WriteString(gaID)
  215. analyticsInjectBuilder.WriteString("');")
  216. analyticsInjectBuilder.WriteString("</script>")
  217. }
  218. analyticsInjectBuilder.WriteString("<!--Google Analytics QuantumNous-->\n")
  219. analyticsInject := []byte(analyticsInjectBuilder.String())
  220. placeholder := []byte("<!--Google Analytics-->\n")
  221. indexPage = bytes.ReplaceAll(indexPage, placeholder, analyticsInject)
  222. classicIndexPage = bytes.ReplaceAll(classicIndexPage, placeholder, analyticsInject)
  223. }
  224. func InitResources() error {
  225. // Initialize resources here if needed
  226. // This is a placeholder function for future resource initialization
  227. err := godotenv.Load(".env")
  228. if err != nil {
  229. if common.DebugEnabled {
  230. common.SysLog("No .env file found, using default environment variables. If needed, please create a .env file and set the relevant variables.")
  231. }
  232. }
  233. // 加载环境变量
  234. common.InitEnv()
  235. logger.SetupLogger()
  236. // Initialize model settings
  237. ratio_setting.InitRatioSettings()
  238. service.InitHttpClient()
  239. service.InitTokenEncoders()
  240. // Initialize SQL Database
  241. err = model.InitDB()
  242. if err != nil {
  243. common.FatalLog("failed to initialize database: " + err.Error())
  244. return err
  245. }
  246. model.CheckSetup()
  247. // Initialize options, should after model.InitDB()
  248. model.InitOptionMap()
  249. // 清理旧的磁盘缓存文件
  250. common.CleanupOldCacheFiles()
  251. // 初始化模型
  252. model.GetPricing()
  253. // Initialize SQL Database
  254. err = model.InitLogDB()
  255. if err != nil {
  256. return err
  257. }
  258. // Initialize Redis
  259. err = common.InitRedisClient()
  260. if err != nil {
  261. return err
  262. }
  263. perfmetrics.Init()
  264. // 启动系统监控
  265. common.StartSystemMonitor()
  266. // Initialize i18n
  267. err = i18n.Init()
  268. if err != nil {
  269. common.SysError("failed to initialize i18n: " + err.Error())
  270. // Don't return error, i18n is not critical
  271. } else {
  272. common.SysLog("i18n initialized with languages: " + strings.Join(i18n.SupportedLanguages(), ", "))
  273. }
  274. // Register user language loader for lazy loading
  275. i18n.SetUserLangLoader(model.GetUserLanguage)
  276. // Load custom OAuth providers from database
  277. err = oauth.LoadCustomProviders()
  278. if err != nil {
  279. common.SysError("failed to load custom OAuth providers: " + err.Error())
  280. // Don't return error, custom OAuth is not critical
  281. }
  282. return nil
  283. }