main.go 8.7 KB

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