ability.go 2.0 KB

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