ability.go 7.5 KB

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