ability.go 6.4 KB

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