ability.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "gorm.io/gorm"
  6. "one-api/common"
  7. "strings"
  8. )
  9. type Ability struct {
  10. Group string `json:"group" gorm:"type:varchar(64);primaryKey;autoIncrement:false"`
  11. Model string `json:"model" gorm:"type:varchar(64);primaryKey;autoIncrement:false"`
  12. ChannelId int `json:"channel_id" gorm:"primaryKey;autoIncrement:false;index"`
  13. Enabled bool `json:"enabled"`
  14. Priority *int64 `json:"priority" gorm:"bigint;default:0;index"`
  15. Weight uint `json:"weight" gorm:"default:0;index"`
  16. }
  17. func GetGroupModels(group string) []string {
  18. var models []string
  19. // Find distinct models
  20. groupCol := "`group`"
  21. if common.UsingPostgreSQL {
  22. groupCol = `"group"`
  23. }
  24. DB.Table("abilities").Where(groupCol+" = ? and enabled = ?", group, true).Distinct("model").Pluck("model", &models)
  25. return models
  26. }
  27. func getPriority(group string, model string, retry int) (int, error) {
  28. groupCol := "`group`"
  29. trueVal := "1"
  30. if common.UsingPostgreSQL {
  31. groupCol = `"group"`
  32. trueVal = "true"
  33. }
  34. var priorities []int
  35. err := DB.Model(&Ability{}).
  36. Select("DISTINCT(priority)").
  37. Where(groupCol+" = ? and model = ? and enabled = "+trueVal, group, model).
  38. Order("priority DESC"). // 按优先级降序排序
  39. Pluck("priority", &priorities).Error // Pluck用于将查询的结果直接扫描到一个切片中
  40. if err != nil {
  41. // 处理错误
  42. return 0, err
  43. }
  44. // 确定要使用的优先级
  45. var priorityToUse int
  46. if retry >= len(priorities) {
  47. // 如果重试次数大于优先级数,则使用最小的优先级
  48. priorityToUse = priorities[len(priorities)-1]
  49. } else {
  50. priorityToUse = priorities[retry]
  51. }
  52. return priorityToUse, nil
  53. }
  54. func getChannelQuery(group string, model string, retry int) *gorm.DB {
  55. groupCol := "`group`"
  56. trueVal := "1"
  57. if common.UsingPostgreSQL {
  58. groupCol = `"group"`
  59. trueVal = "true"
  60. }
  61. maxPrioritySubQuery := DB.Model(&Ability{}).Select("MAX(priority)").Where(groupCol+" = ? and model = ? and enabled = "+trueVal, group, model)
  62. channelQuery := DB.Where(groupCol+" = ? and model = ? and enabled = "+trueVal+" and priority = (?)", group, model, maxPrioritySubQuery)
  63. if retry != 0 {
  64. priority, err := getPriority(group, model, retry)
  65. if err != nil {
  66. common.SysError(fmt.Sprintf("Get priority failed: %s", err.Error()))
  67. } else {
  68. channelQuery = DB.Where(groupCol+" = ? and model = ? and enabled = "+trueVal+" and priority = ?", group, model, priority)
  69. }
  70. }
  71. return channelQuery
  72. }
  73. func GetRandomSatisfiedChannel(group string, model string, retry int) (*Channel, error) {
  74. var abilities []Ability
  75. var err error = nil
  76. channelQuery := getChannelQuery(group, model, retry)
  77. if common.UsingSQLite || common.UsingPostgreSQL {
  78. err = channelQuery.Order("weight DESC").Find(&abilities).Error
  79. } else {
  80. err = channelQuery.Order("weight DESC").Find(&abilities).Error
  81. }
  82. if err != nil {
  83. return nil, err
  84. }
  85. channel := Channel{}
  86. if len(abilities) > 0 {
  87. // Randomly choose one
  88. weightSum := uint(0)
  89. for _, ability_ := range abilities {
  90. weightSum += ability_.Weight + 10
  91. }
  92. // Randomly choose one
  93. weight := common.GetRandomInt(int(weightSum))
  94. for _, ability_ := range abilities {
  95. weight -= int(ability_.Weight) + 10
  96. //log.Printf("weight: %d, ability weight: %d", weight, *ability_.Weight)
  97. if weight <= 0 {
  98. channel.Id = ability_.ChannelId
  99. break
  100. }
  101. }
  102. } else {
  103. return nil, errors.New("channel not found")
  104. }
  105. err = DB.First(&channel, "id = ?", channel.Id).Error
  106. return &channel, err
  107. }
  108. func (channel *Channel) AddAbilities() error {
  109. models_ := strings.Split(channel.Models, ",")
  110. groups_ := strings.Split(channel.Group, ",")
  111. abilities := make([]Ability, 0, len(models_))
  112. for _, model := range models_ {
  113. for _, group := range groups_ {
  114. ability := Ability{
  115. Group: group,
  116. Model: model,
  117. ChannelId: channel.Id,
  118. Enabled: channel.Status == common.ChannelStatusEnabled,
  119. Priority: channel.Priority,
  120. Weight: uint(channel.GetWeight()),
  121. }
  122. abilities = append(abilities, ability)
  123. }
  124. }
  125. return DB.Create(&abilities).Error
  126. }
  127. func (channel *Channel) DeleteAbilities() error {
  128. return DB.Where("channel_id = ?", channel.Id).Delete(&Ability{}).Error
  129. }
  130. // UpdateAbilities updates abilities of this channel.
  131. // Make sure the channel is completed before calling this function.
  132. func (channel *Channel) UpdateAbilities() error {
  133. // A quick and dirty way to update abilities
  134. // First delete all abilities of this channel
  135. err := channel.DeleteAbilities()
  136. if err != nil {
  137. return err
  138. }
  139. // Then add new abilities
  140. err = channel.AddAbilities()
  141. if err != nil {
  142. return err
  143. }
  144. return nil
  145. }
  146. func UpdateAbilityStatus(channelId int, status bool) error {
  147. return DB.Model(&Ability{}).Where("channel_id = ?", channelId).Select("enabled").Update("enabled", status).Error
  148. }
  149. func FixAbility() (int, error) {
  150. var channelIds []int
  151. count := 0
  152. // Find all channel ids from channel table
  153. err := DB.Model(&Channel{}).Pluck("id", &channelIds).Error
  154. if err != nil {
  155. common.SysError(fmt.Sprintf("Get channel ids from channel table failed: %s", err.Error()))
  156. return 0, err
  157. }
  158. // Delete abilities of channels that are not in channel table
  159. err = DB.Where("channel_id NOT IN (?)", channelIds).Delete(&Ability{}).Error
  160. if err != nil {
  161. common.SysError(fmt.Sprintf("Delete abilities of channels that are not in channel table failed: %s", err.Error()))
  162. return 0, err
  163. }
  164. common.SysLog(fmt.Sprintf("Delete abilities of channels that are not in channel table successfully, ids: %v", channelIds))
  165. count += len(channelIds)
  166. // Use channelIds to find channel not in abilities table
  167. var abilityChannelIds []int
  168. err = DB.Model(&Ability{}).Pluck("channel_id", &abilityChannelIds).Error
  169. if err != nil {
  170. common.SysError(fmt.Sprintf("Get channel ids from abilities table failed: %s", err.Error()))
  171. return 0, err
  172. }
  173. var channels []Channel
  174. if len(abilityChannelIds) == 0 {
  175. err = DB.Find(&channels).Error
  176. } else {
  177. err = DB.Where("id NOT IN (?)", abilityChannelIds).Find(&channels).Error
  178. }
  179. if err != nil {
  180. return 0, err
  181. }
  182. for _, channel := range channels {
  183. err := channel.UpdateAbilities()
  184. if err != nil {
  185. common.SysError(fmt.Sprintf("Update abilities of channel %d failed: %s", channel.Id, err.Error()))
  186. } else {
  187. common.SysLog(fmt.Sprintf("Update abilities of channel %d successfully", channel.Id))
  188. count++
  189. }
  190. }
  191. InitChannelCache()
  192. return count, nil
  193. }