main.go 8.6 KB

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