billing.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package controller
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "one-api/common"
  5. "one-api/model"
  6. )
  7. func GetSubscription(c *gin.Context) {
  8. var remainQuota int
  9. var usedQuota int
  10. var err error
  11. var token *model.Token
  12. var expiredTime int64
  13. if common.DisplayTokenStatEnabled {
  14. tokenId := c.GetInt("token_id")
  15. token, err = model.GetTokenById(tokenId)
  16. expiredTime = token.ExpiredTime
  17. remainQuota = token.RemainQuota
  18. usedQuota = token.UsedQuota
  19. } else {
  20. userId := c.GetInt("id")
  21. remainQuota, err = model.GetUserQuota(userId)
  22. usedQuota, err = model.GetUserUsedQuota(userId)
  23. }
  24. if expiredTime <= 0 {
  25. expiredTime = 0
  26. }
  27. if err != nil {
  28. openAIError := OpenAIError{
  29. Message: err.Error(),
  30. Type: "one_api_error",
  31. }
  32. c.JSON(200, gin.H{
  33. "error": openAIError,
  34. })
  35. return
  36. }
  37. quota := remainQuota + usedQuota
  38. amount := float64(quota)
  39. if common.DisplayInCurrencyEnabled {
  40. amount /= common.QuotaPerUnit
  41. }
  42. if token != nil && token.UnlimitedQuota {
  43. amount = 100000000
  44. }
  45. subscription := OpenAISubscriptionResponse{
  46. Object: "billing_subscription",
  47. HasPaymentMethod: true,
  48. SoftLimitUSD: amount,
  49. HardLimitUSD: amount,
  50. SystemHardLimitUSD: amount,
  51. AccessUntil: expiredTime,
  52. }
  53. c.JSON(200, subscription)
  54. return
  55. }
  56. func GetUsage(c *gin.Context) {
  57. var quota int
  58. var err error
  59. var token *model.Token
  60. if common.DisplayTokenStatEnabled {
  61. tokenId := c.GetInt("token_id")
  62. token, err = model.GetTokenById(tokenId)
  63. quota = token.UsedQuota
  64. } else {
  65. userId := c.GetInt("id")
  66. quota, err = model.GetUserUsedQuota(userId)
  67. }
  68. if err != nil {
  69. openAIError := OpenAIError{
  70. Message: err.Error(),
  71. Type: "one_api_error",
  72. }
  73. c.JSON(200, gin.H{
  74. "error": openAIError,
  75. })
  76. return
  77. }
  78. amount := float64(quota)
  79. if common.DisplayInCurrencyEnabled {
  80. amount /= common.QuotaPerUnit
  81. }
  82. usage := OpenAIUsageResponse{
  83. Object: "list",
  84. TotalUsage: amount * 100,
  85. }
  86. c.JSON(200, usage)
  87. return
  88. }