ability.go 6.6 KB

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