ability.go 6.9 KB

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