main.go 7.0 KB

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