ability.go 6.8 KB

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