ability.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. package model
  2. import (
  3. "errors"
  4. "fmt"
  5. "one-api/common"
  6. "strings"
  7. )
  8. type Ability struct {
  9. Group string `json:"group" gorm:"type:varchar(64);primaryKey;autoIncrement:false"`
  10. Model string `json:"model" gorm:"type:varchar(64);primaryKey;autoIncrement:false"`
  11. ChannelId int `json:"channel_id" gorm:"primaryKey;autoIncrement:false;index"`
  12. Enabled bool `json:"enabled"`
  13. Priority *int64 `json:"priority" gorm:"bigint;default:0;index"`
  14. Weight uint `json:"weight" gorm:"default:0;index"`
  15. }
  16. func GetGroupModels(group string) []string {
  17. var models []string
  18. // Find distinct models
  19. groupCol := "`group`"
  20. if common.UsingPostgreSQL {
  21. groupCol = `"group"`
  22. }
  23. DB.Table("abilities").Where(groupCol+" = ? and enabled = ?", group, true).Distinct("model").Pluck("model", &models)
  24. return models
  25. }
  26. func GetRandomSatisfiedChannel(group string, model string) (*Channel, error) {
  27. var abilities []Ability
  28. groupCol := "`group`"
  29. trueVal := "1"
  30. if common.UsingPostgreSQL {
  31. groupCol = `"group"`
  32. trueVal = "true"
  33. }
  34. var err error = nil
  35. maxPrioritySubQuery := DB.Model(&Ability{}).Select("MAX(priority)").Where(groupCol+" = ? and model = ? and enabled = "+trueVal, group, model)
  36. channelQuery := DB.Where(groupCol+" = ? and model = ? and enabled = "+trueVal+" and priority = (?)", group, model, maxPrioritySubQuery)
  37. if common.UsingSQLite || common.UsingPostgreSQL {
  38. err = channelQuery.Order("weight DESC").Find(&abilities).Error
  39. } else {
  40. err = channelQuery.Order("weight DESC").Find(&abilities).Error
  41. }
  42. if err != nil {
  43. return nil, err
  44. }
  45. channel := Channel{}
  46. if len(abilities) > 0 {
  47. // Randomly choose one
  48. weightSum := uint(0)
  49. for _, ability_ := range abilities {
  50. weightSum += ability_.Weight
  51. }
  52. if weightSum == 0 {
  53. // All weight is 0, randomly choose one
  54. channel.Id = abilities[common.GetRandomInt(len(abilities))].ChannelId
  55. } else {
  56. // Randomly choose one
  57. weight := common.GetRandomInt(int(weightSum))
  58. for _, ability_ := range abilities {
  59. weight -= int(ability_.Weight)
  60. //log.Printf("weight: %d, ability weight: %d", weight, *ability_.Weight)
  61. if weight <= 0 {
  62. channel.Id = ability_.ChannelId
  63. break
  64. }
  65. }
  66. }
  67. } else {
  68. return nil, errors.New("channel not found")
  69. }
  70. err = DB.First(&channel, "id = ?", channel.Id).Error
  71. return &channel, err
  72. }
  73. func (channel *Channel) AddAbilities() error {
  74. models_ := strings.Split(channel.Models, ",")
  75. groups_ := strings.Split(channel.Group, ",")
  76. abilities := make([]Ability, 0, len(models_))
  77. for _, model := range models_ {
  78. for _, group := range groups_ {
  79. ability := Ability{
  80. Group: group,
  81. Model: model,
  82. ChannelId: channel.Id,
  83. Enabled: channel.Status == common.ChannelStatusEnabled,
  84. Priority: channel.Priority,
  85. Weight: uint(channel.GetWeight()),
  86. }
  87. abilities = append(abilities, ability)
  88. }
  89. }
  90. return DB.Create(&abilities).Error
  91. }
  92. func (channel *Channel) DeleteAbilities() error {
  93. return DB.Where("channel_id = ?", channel.Id).Delete(&Ability{}).Error
  94. }
  95. // UpdateAbilities updates abilities of this channel.
  96. // Make sure the channel is completed before calling this function.
  97. func (channel *Channel) UpdateAbilities() error {
  98. // A quick and dirty way to update abilities
  99. // First delete all abilities of this channel
  100. err := channel.DeleteAbilities()
  101. if err != nil {
  102. return err
  103. }
  104. // Then add new abilities
  105. err = channel.AddAbilities()
  106. if err != nil {
  107. return err
  108. }
  109. return nil
  110. }
  111. func UpdateAbilityStatus(channelId int, status bool) error {
  112. return DB.Model(&Ability{}).Where("channel_id = ?", channelId).Select("enabled").Update("enabled", status).Error
  113. }
  114. func FixAbility() (int, error) {
  115. var channelIds []int
  116. count := 0
  117. // Find all channel ids from channel table
  118. err := DB.Model(&Channel{}).Pluck("id", &channelIds).Error
  119. if err != nil {
  120. common.SysError(fmt.Sprintf("Get channel ids from channel table failed: %s", err.Error()))
  121. return 0, err
  122. }
  123. // Delete abilities of channels that are not in channel table
  124. err = DB.Where("channel_id NOT IN (?)", channelIds).Delete(&Ability{}).Error
  125. if err != nil {
  126. common.SysError(fmt.Sprintf("Delete abilities of channels that are not in channel table failed: %s", err.Error()))
  127. return 0, err
  128. }
  129. common.SysLog(fmt.Sprintf("Delete abilities of channels that are not in channel table successfully, ids: %v", channelIds))
  130. count += len(channelIds)
  131. // Use channelIds to find channel not in abilities table
  132. var abilityChannelIds []int
  133. err = DB.Model(&Ability{}).Pluck("channel_id", &abilityChannelIds).Error
  134. if err != nil {
  135. common.SysError(fmt.Sprintf("Get channel ids from abilities table failed: %s", err.Error()))
  136. return 0, err
  137. }
  138. var channels []Channel
  139. err = DB.Where("id NOT IN (?)", abilityChannelIds).Find(&channels).Error
  140. if err != nil {
  141. return 0, err
  142. }
  143. for _, channel := range channels {
  144. err := channel.UpdateAbilities()
  145. if err != nil {
  146. common.SysError(fmt.Sprintf("Update abilities of channel %d failed: %s", channel.Id, err.Error()))
  147. } else {
  148. common.SysLog(fmt.Sprintf("Update abilities of channel %d successfully", channel.Id))
  149. count++
  150. }
  151. }
  152. InitChannelCache()
  153. return count, nil
  154. }