main.go 7.5 KB

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