channel.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. package model
  2. import (
  3. "gorm.io/gorm"
  4. "one-api/common"
  5. )
  6. type Channel struct {
  7. Id int `json:"id"`
  8. Type int `json:"type" gorm:"default:0"`
  9. Key string `json:"key" gorm:"not null;index"`
  10. OpenAIOrganization *string `json:"openai_organization"`
  11. Status int `json:"status" gorm:"default:1"`
  12. Name string `json:"name" gorm:"index"`
  13. Weight *uint `json:"weight" gorm:"default:0"`
  14. CreatedTime int64 `json:"created_time" gorm:"bigint"`
  15. TestTime int64 `json:"test_time" gorm:"bigint"`
  16. ResponseTime int `json:"response_time"` // in milliseconds
  17. BaseURL *string `json:"base_url" gorm:"column:base_url;default:''"`
  18. Other string `json:"other"`
  19. Balance float64 `json:"balance"` // in USD
  20. BalanceUpdatedTime int64 `json:"balance_updated_time" gorm:"bigint"`
  21. Models string `json:"models"`
  22. Group string `json:"group" gorm:"type:varchar(32);default:'default'"`
  23. UsedQuota int64 `json:"used_quota" gorm:"bigint;default:0"`
  24. ModelMapping *string `json:"model_mapping" gorm:"type:varchar(1024);default:''"`
  25. Priority *int64 `json:"priority" gorm:"bigint;default:0"`
  26. AutoBan *int `json:"auto_ban" gorm:"default:1"`
  27. }
  28. func GetAllChannels(startIdx int, num int, selectAll bool, idSort bool) ([]*Channel, error) {
  29. var channels []*Channel
  30. var err error
  31. order := "priority desc"
  32. if idSort {
  33. order = "id desc"
  34. }
  35. if selectAll {
  36. err = DB.Order(order).Find(&channels).Error
  37. } else {
  38. err = DB.Order(order).Limit(num).Offset(startIdx).Omit("key").Find(&channels).Error
  39. }
  40. return channels, err
  41. }
  42. func SearchChannels(keyword string, group string) (channels []*Channel, err error) {
  43. keyCol := "`key`"
  44. if common.UsingPostgreSQL {
  45. keyCol = `"key"`
  46. }
  47. if group != "" {
  48. groupCol := "`group`"
  49. if common.UsingPostgreSQL {
  50. groupCol = `"group"`
  51. }
  52. err = DB.Omit("key").Where("(id = ? or name LIKE ? or "+keyCol+" = ?) and "+groupCol+" LIKE ?", common.String2Int(keyword), keyword+"%", keyword, "%"+group+"%").Find(&channels).Error
  53. } else {
  54. err = DB.Omit("key").Where("id = ? or name LIKE ? or "+keyCol+" = ?", common.String2Int(keyword), keyword+"%", keyword).Find(&channels).Error
  55. }
  56. return channels, err
  57. }
  58. func GetChannelById(id int, selectAll bool) (*Channel, error) {
  59. channel := Channel{Id: id}
  60. var err error = nil
  61. if selectAll {
  62. err = DB.First(&channel, "id = ?", id).Error
  63. } else {
  64. err = DB.Omit("key").First(&channel, "id = ?", id).Error
  65. }
  66. return &channel, err
  67. }
  68. func BatchInsertChannels(channels []Channel) error {
  69. var err error
  70. err = DB.Create(&channels).Error
  71. if err != nil {
  72. return err
  73. }
  74. for _, channel_ := range channels {
  75. err = channel_.AddAbilities()
  76. if err != nil {
  77. return err
  78. }
  79. }
  80. return nil
  81. }
  82. func BatchDeleteChannels(ids []int) error {
  83. //使用事务 删除channel表和channel_ability表
  84. tx := DB.Begin()
  85. err := tx.Where("id in (?)", ids).Delete(&Channel{}).Error
  86. if err != nil {
  87. // 回滚事务
  88. tx.Rollback()
  89. return err
  90. }
  91. err = tx.Where("channel_id in (?)", ids).Delete(&Ability{}).Error
  92. if err != nil {
  93. // 回滚事务
  94. tx.Rollback()
  95. }
  96. // 提交事务
  97. tx.Commit()
  98. return err
  99. }
  100. func (channel *Channel) GetPriority() int64 {
  101. if channel.Priority == nil {
  102. return 0
  103. }
  104. return *channel.Priority
  105. }
  106. func (channel *Channel) GetBaseURL() string {
  107. if channel.BaseURL == nil {
  108. return ""
  109. }
  110. return *channel.BaseURL
  111. }
  112. func (channel *Channel) GetModelMapping() string {
  113. if channel.ModelMapping == nil {
  114. return ""
  115. }
  116. return *channel.ModelMapping
  117. }
  118. func (channel *Channel) Insert() error {
  119. var err error
  120. err = DB.Create(channel).Error
  121. if err != nil {
  122. return err
  123. }
  124. err = channel.AddAbilities()
  125. return err
  126. }
  127. func (channel *Channel) Update() error {
  128. var err error
  129. err = DB.Model(channel).Updates(channel).Error
  130. if err != nil {
  131. return err
  132. }
  133. DB.Model(channel).First(channel, "id = ?", channel.Id)
  134. err = channel.UpdateAbilities()
  135. return err
  136. }
  137. func (channel *Channel) UpdateResponseTime(responseTime int64) {
  138. err := DB.Model(channel).Select("response_time", "test_time").Updates(Channel{
  139. TestTime: common.GetTimestamp(),
  140. ResponseTime: int(responseTime),
  141. }).Error
  142. if err != nil {
  143. common.SysError("failed to update response time: " + err.Error())
  144. }
  145. }
  146. func (channel *Channel) UpdateBalance(balance float64) {
  147. err := DB.Model(channel).Select("balance_updated_time", "balance").Updates(Channel{
  148. BalanceUpdatedTime: common.GetTimestamp(),
  149. Balance: balance,
  150. }).Error
  151. if err != nil {
  152. common.SysError("failed to update balance: " + err.Error())
  153. }
  154. }
  155. func (channel *Channel) Delete() error {
  156. var err error
  157. err = DB.Delete(channel).Error
  158. if err != nil {
  159. return err
  160. }
  161. err = channel.DeleteAbilities()
  162. return err
  163. }
  164. func UpdateChannelStatusById(id int, status int) {
  165. err := UpdateAbilityStatus(id, status == common.ChannelStatusEnabled)
  166. if err != nil {
  167. common.SysError("failed to update ability status: " + err.Error())
  168. }
  169. err = DB.Model(&Channel{}).Where("id = ?", id).Update("status", status).Error
  170. if err != nil {
  171. common.SysError("failed to update channel status: " + err.Error())
  172. }
  173. }
  174. func UpdateChannelUsedQuota(id int, quota int) {
  175. if common.BatchUpdateEnabled {
  176. addNewRecord(BatchUpdateTypeChannelUsedQuota, id, quota)
  177. return
  178. }
  179. updateChannelUsedQuota(id, quota)
  180. }
  181. func updateChannelUsedQuota(id int, quota int) {
  182. err := DB.Model(&Channel{}).Where("id = ?", id).Update("used_quota", gorm.Expr("used_quota + ?", quota)).Error
  183. if err != nil {
  184. common.SysError("failed to update channel used quota: " + err.Error())
  185. }
  186. }
  187. func DeleteChannelByStatus(status int64) (int64, error) {
  188. result := DB.Where("status = ?", status).Delete(&Channel{})
  189. return result.RowsAffected, result.Error
  190. }
  191. func DeleteDisabledChannel() (int64, error) {
  192. result := DB.Where("status = ? or status = ?", common.ChannelStatusAutoDisabled, common.ChannelStatusManuallyDisabled).Delete(&Channel{})
  193. return result.RowsAffected, result.Error
  194. }