ability.go 5.0 KB

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