channel.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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(64);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. return err
  96. }
  97. // 提交事务
  98. tx.Commit()
  99. return err
  100. }
  101. func (channel *Channel) GetPriority() int64 {
  102. if channel.Priority == nil {
  103. return 0
  104. }
  105. return *channel.Priority
  106. }
  107. func (channel *Channel) GetWeight() int {
  108. if channel.Weight == nil {
  109. return 0
  110. }
  111. return int(*channel.Weight)
  112. }
  113. func (channel *Channel) GetBaseURL() string {
  114. if channel.BaseURL == nil {
  115. return ""
  116. }
  117. return *channel.BaseURL
  118. }
  119. func (channel *Channel) GetModelMapping() string {
  120. if channel.ModelMapping == nil {
  121. return ""
  122. }
  123. return *channel.ModelMapping
  124. }
  125. func (channel *Channel) Insert() error {
  126. var err error
  127. err = DB.Create(channel).Error
  128. if err != nil {
  129. return err
  130. }
  131. err = channel.AddAbilities()
  132. return err
  133. }
  134. func (channel *Channel) Update() error {
  135. var err error
  136. err = DB.Model(channel).Updates(channel).Error
  137. if err != nil {
  138. return err
  139. }
  140. DB.Model(channel).First(channel, "id = ?", channel.Id)
  141. err = channel.UpdateAbilities()
  142. return err
  143. }
  144. func (channel *Channel) UpdateResponseTime(responseTime int64) {
  145. err := DB.Model(channel).Select("response_time", "test_time").Updates(Channel{
  146. TestTime: common.GetTimestamp(),
  147. ResponseTime: int(responseTime),
  148. }).Error
  149. if err != nil {
  150. common.SysError("failed to update response time: " + err.Error())
  151. }
  152. }
  153. func (channel *Channel) UpdateBalance(balance float64) {
  154. err := DB.Model(channel).Select("balance_updated_time", "balance").Updates(Channel{
  155. BalanceUpdatedTime: common.GetTimestamp(),
  156. Balance: balance,
  157. }).Error
  158. if err != nil {
  159. common.SysError("failed to update balance: " + err.Error())
  160. }
  161. }
  162. func (channel *Channel) Delete() error {
  163. var err error
  164. err = DB.Delete(channel).Error
  165. if err != nil {
  166. return err
  167. }
  168. err = channel.DeleteAbilities()
  169. return err
  170. }
  171. func UpdateChannelStatusById(id int, status int) {
  172. err := UpdateAbilityStatus(id, status == common.ChannelStatusEnabled)
  173. if err != nil {
  174. common.SysError("failed to update ability status: " + err.Error())
  175. }
  176. err = DB.Model(&Channel{}).Where("id = ?", id).Update("status", status).Error
  177. if err != nil {
  178. common.SysError("failed to update channel status: " + err.Error())
  179. }
  180. }
  181. func UpdateChannelUsedQuota(id int, quota int) {
  182. if common.BatchUpdateEnabled {
  183. addNewRecord(BatchUpdateTypeChannelUsedQuota, id, quota)
  184. return
  185. }
  186. updateChannelUsedQuota(id, quota)
  187. }
  188. func updateChannelUsedQuota(id int, quota int) {
  189. err := DB.Model(&Channel{}).Where("id = ?", id).Update("used_quota", gorm.Expr("used_quota + ?", quota)).Error
  190. if err != nil {
  191. common.SysError("failed to update channel used quota: " + err.Error())
  192. }
  193. }
  194. func DeleteChannelByStatus(status int64) (int64, error) {
  195. result := DB.Where("status = ?", status).Delete(&Channel{})
  196. return result.RowsAffected, result.Error
  197. }
  198. func DeleteDisabledChannel() (int64, error) {
  199. result := DB.Where("status = ? or status = ?", common.ChannelStatusAutoDisabled, common.ChannelStatusManuallyDisabled).Delete(&Channel{})
  200. return result.RowsAffected, result.Error
  201. }