main.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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/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. log.Println(http.ListenAndServe("0.0.0.0:8005", nil))
  103. })
  104. go common.Monitor()
  105. common.SysLog("pprof enabled")
  106. }
  107. // Initialize HTTP server
  108. server := gin.New()
  109. server.Use(gin.CustomRecovery(func(c *gin.Context, err any) {
  110. common.SysLog(fmt.Sprintf("panic detected: %v", err))
  111. c.JSON(http.StatusInternalServerError, gin.H{
  112. "error": gin.H{
  113. "message": fmt.Sprintf("Panic detected, error: %v. Please submit a issue here: https://github.com/Calcium-Ion/new-api", err),
  114. "type": "new_api_panic",
  115. },
  116. })
  117. }))
  118. // This will cause SSE not to work!!!
  119. //server.Use(gzip.Gzip(gzip.DefaultCompression))
  120. server.Use(middleware.RequestId())
  121. middleware.SetUpLogger(server)
  122. // Initialize session store
  123. store := cookie.NewStore([]byte(common.SessionSecret))
  124. store.Options(sessions.Options{
  125. Path: "/",
  126. MaxAge: 2592000, // 30 days
  127. HttpOnly: true,
  128. Secure: false,
  129. SameSite: http.SameSiteStrictMode,
  130. })
  131. server.Use(sessions.Sessions("session", store))
  132. InjectUmamiAnalytics()
  133. InjectGoogleAnalytics()
  134. // 设置路由
  135. router.SetRouter(server, buildFS, indexPage)
  136. var port = os.Getenv("PORT")
  137. if port == "" {
  138. port = strconv.Itoa(*common.Port)
  139. }
  140. // Log startup success message
  141. common.LogStartupSuccess(startTime, port)
  142. err = server.Run(":" + port)
  143. if err != nil {
  144. common.FatalLog("failed to start HTTP server: " + err.Error())
  145. }
  146. }
  147. func InjectUmamiAnalytics() {
  148. analyticsInjectBuilder := &strings.Builder{}
  149. if os.Getenv("UMAMI_WEBSITE_ID") != "" {
  150. umamiSiteID := os.Getenv("UMAMI_WEBSITE_ID")
  151. umamiScriptURL := os.Getenv("UMAMI_SCRIPT_URL")
  152. if umamiScriptURL == "" {
  153. umamiScriptURL = "https://analytics.umami.is/script.js"
  154. }
  155. analyticsInjectBuilder.WriteString("<script defer src=\"")
  156. analyticsInjectBuilder.WriteString(umamiScriptURL)
  157. analyticsInjectBuilder.WriteString("\" data-website-id=\"")
  158. analyticsInjectBuilder.WriteString(umamiSiteID)
  159. analyticsInjectBuilder.WriteString("\"></script>")
  160. }
  161. analyticsInject := analyticsInjectBuilder.String()
  162. indexPage = bytes.ReplaceAll(indexPage, []byte("<!--umami-->\n"), []byte(analyticsInject))
  163. }
  164. func InjectGoogleAnalytics() {
  165. analyticsInjectBuilder := &strings.Builder{}
  166. if os.Getenv("GOOGLE_ANALYTICS_ID") != "" {
  167. gaID := os.Getenv("GOOGLE_ANALYTICS_ID")
  168. // Google Analytics 4 (gtag.js)
  169. analyticsInjectBuilder.WriteString("<script async src=\"https://www.googletagmanager.com/gtag/js?id=")
  170. analyticsInjectBuilder.WriteString(gaID)
  171. analyticsInjectBuilder.WriteString("\"></script>")
  172. analyticsInjectBuilder.WriteString("<script>")
  173. analyticsInjectBuilder.WriteString("window.dataLayer = window.dataLayer || [];")
  174. analyticsInjectBuilder.WriteString("function gtag(){dataLayer.push(arguments);}")
  175. analyticsInjectBuilder.WriteString("gtag('js', new Date());")
  176. analyticsInjectBuilder.WriteString("gtag('config', '")
  177. analyticsInjectBuilder.WriteString(gaID)
  178. analyticsInjectBuilder.WriteString("');")
  179. analyticsInjectBuilder.WriteString("</script>")
  180. }
  181. analyticsInject := analyticsInjectBuilder.String()
  182. indexPage = bytes.ReplaceAll(indexPage, []byte("<!--Google Analytics-->\n"), []byte(analyticsInject))
  183. }
  184. func InitResources() error {
  185. // Initialize resources here if needed
  186. // This is a placeholder function for future resource initialization
  187. err := godotenv.Load(".env")
  188. if err != nil {
  189. if common.DebugEnabled {
  190. common.SysLog("No .env file found, using default environment variables. If needed, please create a .env file and set the relevant variables.")
  191. }
  192. }
  193. // 加载环境变量
  194. common.InitEnv()
  195. logger.SetupLogger()
  196. // Initialize model settings
  197. ratio_setting.InitRatioSettings()
  198. service.InitHttpClient()
  199. service.InitTokenEncoders()
  200. // Initialize SQL Database
  201. err = model.InitDB()
  202. if err != nil {
  203. common.FatalLog("failed to initialize database: " + err.Error())
  204. return err
  205. }
  206. model.CheckSetup()
  207. // Initialize options, should after model.InitDB()
  208. model.InitOptionMap()
  209. // 初始化模型
  210. model.GetPricing()
  211. // Initialize SQL Database
  212. err = model.InitLogDB()
  213. if err != nil {
  214. return err
  215. }
  216. // Initialize Redis
  217. err = common.InitRedisClient()
  218. if err != nil {
  219. return err
  220. }
  221. return nil
  222. }