ability.go 2.1 KB

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