channel-billing.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. package controller
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/gin-gonic/gin"
  7. "io"
  8. "net/http"
  9. "one-api/common"
  10. "one-api/model"
  11. "strconv"
  12. "time"
  13. )
  14. type OpenAISubscriptionResponse struct {
  15. HasPaymentMethod bool `json:"has_payment_method"`
  16. HardLimitUSD float64 `json:"hard_limit_usd"`
  17. }
  18. type OpenAIUsageResponse struct {
  19. TotalUsage float64 `json:"total_usage"` // unit: 0.01 dollar
  20. }
  21. func updateChannelBalance(channel *model.Channel) (float64, error) {
  22. baseURL := common.ChannelBaseURLs[channel.Type]
  23. switch channel.Type {
  24. case common.ChannelTypeAzure:
  25. return 0, errors.New("尚未实现")
  26. case common.ChannelTypeCustom:
  27. baseURL = channel.BaseURL
  28. }
  29. url := fmt.Sprintf("%s/v1/dashboard/billing/subscription", baseURL)
  30. client := &http.Client{}
  31. req, err := http.NewRequest("GET", url, nil)
  32. if err != nil {
  33. return 0, err
  34. }
  35. auth := fmt.Sprintf("Bearer %s", channel.Key)
  36. req.Header.Add("Authorization", auth)
  37. res, err := client.Do(req)
  38. if err != nil {
  39. return 0, err
  40. }
  41. body, err := io.ReadAll(res.Body)
  42. if err != nil {
  43. return 0, err
  44. }
  45. err = res.Body.Close()
  46. if err != nil {
  47. return 0, err
  48. }
  49. subscription := OpenAISubscriptionResponse{}
  50. err = json.Unmarshal(body, &subscription)
  51. if err != nil {
  52. return 0, err
  53. }
  54. now := time.Now()
  55. startDate := fmt.Sprintf("%s-01", now.Format("2006-01"))
  56. //endDate := now.Format("2006-01-02")
  57. url = fmt.Sprintf("%s/v1/dashboard/billing/usage?start_date=%s&end_date=%s", baseURL, startDate, "2023-06-01")
  58. req, err = http.NewRequest("GET", url, nil)
  59. if err != nil {
  60. return 0, err
  61. }
  62. req.Header.Add("Authorization", auth)
  63. res, err = client.Do(req)
  64. if err != nil {
  65. return 0, err
  66. }
  67. body, err = io.ReadAll(res.Body)
  68. if err != nil {
  69. return 0, err
  70. }
  71. err = res.Body.Close()
  72. if err != nil {
  73. return 0, err
  74. }
  75. usage := OpenAIUsageResponse{}
  76. err = json.Unmarshal(body, &usage)
  77. if err != nil {
  78. return 0, err
  79. }
  80. balance := subscription.HardLimitUSD - usage.TotalUsage/100
  81. channel.UpdateBalance(balance)
  82. return balance, nil
  83. }
  84. func UpdateChannelBalance(c *gin.Context) {
  85. id, err := strconv.Atoi(c.Param("id"))
  86. if err != nil {
  87. c.JSON(http.StatusOK, gin.H{
  88. "success": false,
  89. "message": err.Error(),
  90. })
  91. return
  92. }
  93. channel, err := model.GetChannelById(id, true)
  94. if err != nil {
  95. c.JSON(http.StatusOK, gin.H{
  96. "success": false,
  97. "message": err.Error(),
  98. })
  99. return
  100. }
  101. balance, err := updateChannelBalance(channel)
  102. if err != nil {
  103. c.JSON(http.StatusOK, gin.H{
  104. "success": false,
  105. "message": err.Error(),
  106. })
  107. return
  108. }
  109. c.JSON(http.StatusOK, gin.H{
  110. "success": true,
  111. "message": "",
  112. "balance": balance,
  113. })
  114. return
  115. }
  116. func updateAllChannelsBalance() error {
  117. channels, err := model.GetAllChannels(0, 0, true)
  118. if err != nil {
  119. return err
  120. }
  121. for _, channel := range channels {
  122. if channel.Status != common.ChannelStatusEnabled {
  123. continue
  124. }
  125. balance, err := updateChannelBalance(channel)
  126. if err != nil {
  127. continue
  128. } else {
  129. // err is nil & balance <= 0 means quota is used up
  130. if balance <= 0 {
  131. disableChannel(channel.Id, channel.Name, "余额不足")
  132. }
  133. }
  134. }
  135. return nil
  136. }
  137. func UpdateAllChannelsBalance(c *gin.Context) {
  138. // TODO: make it async
  139. err := updateAllChannelsBalance()
  140. if err != nil {
  141. c.JSON(http.StatusOK, gin.H{
  142. "success": false,
  143. "message": err.Error(),
  144. })
  145. return
  146. }
  147. c.JSON(http.StatusOK, gin.H{
  148. "success": true,
  149. "message": "",
  150. })
  151. return
  152. }