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"`
  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. groups_ := strings.Split(channel.Group, ",")
  30. abilities := make([]Ability, 0, len(models_))
  31. for _, model := range models_ {
  32. for _, group := range groups_ {
  33. ability := Ability{
  34. Group: group,
  35. Model: model,
  36. ChannelId: channel.Id,
  37. Enabled: channel.Status == common.ChannelStatusEnabled,
  38. }
  39. abilities = append(abilities, ability)
  40. }
  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).Select("enabled").Update("enabled", status).Error
  65. }