ability.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package model
  2. import (
  3. "one-api/common"
  4. "strings"
  5. )
  6. type Ability struct {
  7. Group string `json:"group" gorm:"type:varchar(32);primaryKey;autoIncrement:false"`
  8. Model string `json:"model" gorm:"primaryKey;autoIncrement:false"`
  9. ChannelId int `json:"channel_id" gorm:"primaryKey;autoIncrement:false;index"`
  10. Enabled bool `json:"enabled"`
  11. Priority int64 `json:"priority" gorm:"bigint;default:0"`
  12. }
  13. func GetRandomSatisfiedChannel(group string, model string) (*Channel, error) {
  14. ability := Ability{}
  15. var err error = nil
  16. if common.UsingSQLite {
  17. err = DB.Where("`group` = ? and model = ? and enabled = 1", group, model).Order("CASE WHEN priority <> 0 THEN priority ELSE RANDOM() END DESC ").Limit(1).First(&ability).Error
  18. } else {
  19. err = DB.Where("`group` = ? and model = ? and enabled = 1", group, model).Order("CASE WHEN priority <> 0 THEN priority ELSE RAND() END DESC").Limit(1).First(&ability).Error
  20. }
  21. if err != nil {
  22. return nil, err
  23. }
  24. channel := Channel{}
  25. channel.Id = ability.ChannelId
  26. err = DB.First(&channel, "id = ?", ability.ChannelId).Error
  27. return &channel, err
  28. }
  29. func (channel *Channel) AddAbilities() error {
  30. models_ := strings.Split(channel.Models, ",")
  31. groups_ := strings.Split(channel.Group, ",")
  32. abilities := make([]Ability, 0, len(models_))
  33. for _, model := range models_ {
  34. for _, group := range groups_ {
  35. ability := Ability{
  36. Group: group,
  37. Model: model,
  38. ChannelId: channel.Id,
  39. Enabled: channel.Status == common.ChannelStatusEnabled,
  40. Priority: channel.Priority,
  41. }
  42. abilities = append(abilities, ability)
  43. }
  44. }
  45. return DB.Create(&abilities).Error
  46. }
  47. func (channel *Channel) DeleteAbilities() error {
  48. return DB.Where("channel_id = ?", channel.Id).Delete(&Ability{}).Error
  49. }
  50. // UpdateAbilities updates abilities of this channel.
  51. // Make sure the channel is completed before calling this function.
  52. func (channel *Channel) UpdateAbilities() error {
  53. // A quick and dirty way to update abilities
  54. // First delete all abilities of this channel
  55. err := channel.DeleteAbilities()
  56. if err != nil {
  57. return err
  58. }
  59. // Then add new abilities
  60. err = channel.AddAbilities()
  61. if err != nil {
  62. return err
  63. }
  64. return nil
  65. }
  66. func UpdateAbilityStatus(channelId int, status bool) error {
  67. return DB.Model(&Ability{}).Where("channel_id = ?", channelId).Select("enabled").Update("enabled", status).Error
  68. }