channel.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package service
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/QuantumNous/new-api/common"
  6. "github.com/QuantumNous/new-api/dto"
  7. "github.com/QuantumNous/new-api/model"
  8. "github.com/QuantumNous/new-api/setting/operation_setting"
  9. "github.com/QuantumNous/new-api/types"
  10. )
  11. func formatNotifyType(channelId int, status int) string {
  12. return fmt.Sprintf("%s_%d_%d", dto.NotifyTypeChannelUpdate, channelId, status)
  13. }
  14. // disable & notify
  15. func DisableChannel(channelError types.ChannelError, reason string) {
  16. common.SysLog(fmt.Sprintf("通道「%s」(#%d)发生错误,准备禁用,原因:%s", channelError.ChannelName, channelError.ChannelId, reason))
  17. // 检查是否启用自动禁用功能
  18. if !channelError.AutoBan {
  19. common.SysLog(fmt.Sprintf("通道「%s」(#%d)未启用自动禁用功能,跳过禁用操作", channelError.ChannelName, channelError.ChannelId))
  20. return
  21. }
  22. success := model.UpdateChannelStatus(channelError.ChannelId, channelError.UsingKey, common.ChannelStatusAutoDisabled, reason)
  23. if success {
  24. subject := fmt.Sprintf("通道「%s」(#%d)已被禁用", channelError.ChannelName, channelError.ChannelId)
  25. content := fmt.Sprintf("通道「%s」(#%d)已被禁用,原因:%s", channelError.ChannelName, channelError.ChannelId, reason)
  26. NotifyRootUser(formatNotifyType(channelError.ChannelId, common.ChannelStatusAutoDisabled), subject, content)
  27. }
  28. }
  29. func EnableChannel(channelId int, usingKey string, channelName string) {
  30. success := model.UpdateChannelStatus(channelId, usingKey, common.ChannelStatusEnabled, "")
  31. if success {
  32. subject := fmt.Sprintf("通道「%s」(#%d)已被启用", channelName, channelId)
  33. content := fmt.Sprintf("通道「%s」(#%d)已被启用", channelName, channelId)
  34. NotifyRootUser(formatNotifyType(channelId, common.ChannelStatusEnabled), subject, content)
  35. }
  36. }
  37. func ShouldDisableChannel(err *types.NewAPIError) bool {
  38. if !common.AutomaticDisableChannelEnabled {
  39. return false
  40. }
  41. if err == nil {
  42. return false
  43. }
  44. if types.IsChannelError(err) {
  45. return true
  46. }
  47. if types.IsSkipRetryError(err) {
  48. return false
  49. }
  50. if operation_setting.ShouldDisableByStatusCode(err.StatusCode) {
  51. return true
  52. }
  53. lowerMessage := strings.ToLower(err.Error())
  54. search, _ := AcSearch(lowerMessage, operation_setting.AutomaticDisableKeywords, true)
  55. return search
  56. }
  57. func ShouldEnableChannel(newAPIError *types.NewAPIError, status int) bool {
  58. if !common.AutomaticEnableChannelEnabled {
  59. return false
  60. }
  61. if newAPIError != nil {
  62. return false
  63. }
  64. if status != common.ChannelStatusAutoDisabled {
  65. return false
  66. }
  67. return true
  68. }