main.go 7.6 KB

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