main.go 8.0 KB

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