ability.go 5.0 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 + 10
  51. }
  52. // Randomly choose one
  53. weight := common.GetRandomInt(int(weightSum))
  54. for _, ability_ := range abilities {
  55. weight -= int(ability_.Weight)
  56. //log.Printf("weight: %d, ability weight: %d", weight, *ability_.Weight)
  57. if weight <= 0 {
  58. channel.Id = ability_.ChannelId
  59. break
  60. }
  61. }
  62. } else {
  63. return nil, errors.New("channel not found")
  64. }
  65. err = DB.First(&channel, "id = ?", channel.Id).Error
  66. return &channel, err
  67. }
  68. func (channel *Channel) AddAbilities() error {
  69. models_ := strings.Split(channel.Models, ",")
  70. groups_ := strings.Split(channel.Group, ",")
  71. abilities := make([]Ability, 0, len(models_))
  72. for _, model := range models_ {
  73. for _, group := range groups_ {
  74. ability := Ability{
  75. Group: group,
  76. Model: model,
  77. ChannelId: channel.Id,
  78. Enabled: channel.Status == common.ChannelStatusEnabled,
  79. Priority: channel.Priority,
  80. Weight: uint(channel.GetWeight()),
  81. }
  82. abilities = append(abilities, ability)
  83. }
  84. }
  85. return DB.Create(&abilities).Error
  86. }
  87. func (channel *Channel) DeleteAbilities() error {
  88. return DB.Where("channel_id = ?", channel.Id).Delete(&Ability{}).Error
  89. }
  90. // UpdateAbilities updates abilities of this channel.
  91. // Make sure the channel is completed before calling this function.
  92. func (channel *Channel) UpdateAbilities() error {
  93. // A quick and dirty way to update abilities
  94. // First delete all abilities of this channel
  95. err := channel.DeleteAbilities()
  96. if err != nil {
  97. return err
  98. }
  99. // Then add new abilities
  100. err = channel.AddAbilities()
  101. if err != nil {
  102. return err
  103. }
  104. return nil
  105. }
  106. func UpdateAbilityStatus(channelId int, status bool) error {
  107. return DB.Model(&Ability{}).Where("channel_id = ?", channelId).Select("enabled").Update("enabled", status).Error
  108. }
  109. func FixAbility() (int, error) {
  110. var channelIds []int
  111. count := 0
  112. // Find all channel ids from channel table
  113. err := DB.Model(&Channel{}).Pluck("id", &channelIds).Error
  114. if err != nil {
  115. common.SysError(fmt.Sprintf("Get channel ids from channel table failed: %s", err.Error()))
  116. return 0, err
  117. }
  118. // Delete abilities of channels that are not in channel table
  119. err = DB.Where("channel_id NOT IN (?)", channelIds).Delete(&Ability{}).Error
  120. if err != nil {
  121. common.SysError(fmt.Sprintf("Delete abilities of channels that are not in channel table failed: %s", err.Error()))
  122. return 0, err
  123. }
  124. common.SysLog(fmt.Sprintf("Delete abilities of channels that are not in channel table successfully, ids: %v", channelIds))
  125. count += len(channelIds)
  126. // Use channelIds to find channel not in abilities table
  127. var abilityChannelIds []int
  128. err = DB.Model(&Ability{}).Pluck("channel_id", &abilityChannelIds).Error
  129. if err != nil {
  130. common.SysError(fmt.Sprintf("Get channel ids from abilities table failed: %s", err.Error()))
  131. return 0, err
  132. }
  133. var channels []Channel
  134. if len(abilityChannelIds) == 0 {
  135. err = DB.Find(&channels).Error
  136. } else {
  137. err = DB.Where("id NOT IN (?)", abilityChannelIds).Find(&channels).Error
  138. }
  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. InitChannelCache()
  152. return count, nil
  153. }