ability.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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" gorm:"default:1"`
  11. }
  12. func GetRandomSatisfiedChannel(group string, model string) (*Channel, error) {
  13. if group == "default" {
  14. return GetRandomChannel()
  15. }
  16. ability := Ability{}
  17. var err error = nil
  18. if common.UsingSQLite {
  19. err = DB.Where("`group` = ? and model = ? and enabled = 1", group, model).Order("RANDOM()").Limit(1).First(&ability).Error
  20. } else {
  21. err = DB.Where("`group` = ? and model = ? and enabled = 1", group, model).Order("RAND()").Limit(1).First(&ability).Error
  22. }
  23. if err != nil {
  24. return nil, err
  25. }
  26. channel := Channel{}
  27. err = DB.First(&channel, "id = ?", ability.ChannelId).Error
  28. return &channel, err
  29. }
  30. func (channel *Channel) AddAbilities() error {
  31. models_ := strings.Split(channel.Models, ",")
  32. abilities := make([]Ability, 0, len(models_))
  33. for _, model := range models_ {
  34. ability := Ability{
  35. Group: channel.Group,
  36. Model: model,
  37. ChannelId: channel.Id,
  38. Enabled: channel.Status == common.ChannelStatusEnabled,
  39. }
  40. abilities = append(abilities, ability)
  41. }
  42. return DB.Create(&abilities).Error
  43. }
  44. func (channel *Channel) DeleteAbilities() error {
  45. return DB.Where("channel_id = ?", channel.Id).Delete(&Ability{}).Error
  46. }
  47. // UpdateAbilities updates abilities of this channel.
  48. // Make sure the channel is completed before calling this function.
  49. func (channel *Channel) UpdateAbilities() error {
  50. // A quick and dirty way to update abilities
  51. // First delete all abilities of this channel
  52. err := channel.DeleteAbilities()
  53. if err != nil {
  54. return err
  55. }
  56. // Then add new abilities
  57. err = channel.AddAbilities()
  58. if err != nil {
  59. return err
  60. }
  61. return nil
  62. }
  63. func UpdateAbilityStatus(channelId int, status bool) error {
  64. return DB.Model(&Ability{}).Where("channel_id = ?", channelId).Update("enabled", status).Error
  65. }