channel.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package service
  2. import (
  3. "fmt"
  4. "net/http"
  5. "one-api/common"
  6. "one-api/dto"
  7. "one-api/model"
  8. "one-api/setting"
  9. "strings"
  10. )
  11. // disable & notify
  12. func DisableChannel(channelId int, channelName string, reason string) {
  13. model.UpdateChannelStatusById(channelId, common.ChannelStatusAutoDisabled, reason)
  14. subject := fmt.Sprintf("通道「%s」(#%d)已被禁用", channelName, channelId)
  15. content := fmt.Sprintf("通道「%s」(#%d)已被禁用,原因:%s", channelName, channelId, reason)
  16. NotifyRootUser(subject, content, dto.NotifyTypeChannelUpdate)
  17. }
  18. func EnableChannel(channelId int, channelName string) {
  19. model.UpdateChannelStatusById(channelId, common.ChannelStatusEnabled, "")
  20. subject := fmt.Sprintf("通道「%s」(#%d)已被启用", channelName, channelId)
  21. content := fmt.Sprintf("通道「%s」(#%d)已被启用", channelName, channelId)
  22. NotifyRootUser(subject, content, dto.NotifyTypeChannelUpdate)
  23. }
  24. func ShouldDisableChannel(channelType int, err *dto.OpenAIErrorWithStatusCode) bool {
  25. if !common.AutomaticDisableChannelEnabled {
  26. return false
  27. }
  28. if err == nil {
  29. return false
  30. }
  31. if err.LocalError {
  32. return false
  33. }
  34. if err.StatusCode == http.StatusUnauthorized {
  35. return true
  36. }
  37. if err.StatusCode == http.StatusForbidden {
  38. switch channelType {
  39. case common.ChannelTypeGemini:
  40. return true
  41. }
  42. }
  43. switch err.Error.Code {
  44. case "invalid_api_key":
  45. return true
  46. case "account_deactivated":
  47. return true
  48. case "billing_not_active":
  49. return true
  50. }
  51. switch err.Error.Type {
  52. case "insufficient_quota":
  53. return true
  54. case "insufficient_user_quota":
  55. return true
  56. // https://docs.anthropic.com/claude/reference/errors
  57. case "authentication_error":
  58. return true
  59. case "permission_error":
  60. return true
  61. case "forbidden":
  62. return true
  63. }
  64. lowerMessage := strings.ToLower(err.Error.Message)
  65. search, _ := AcSearch(lowerMessage, setting.AutomaticDisableKeywords, true)
  66. if search {
  67. return true
  68. }
  69. return false
  70. }
  71. func ShouldEnableChannel(err error, openaiWithStatusErr *dto.OpenAIErrorWithStatusCode, status int) bool {
  72. if !common.AutomaticEnableChannelEnabled {
  73. return false
  74. }
  75. if err != nil {
  76. return false
  77. }
  78. if openaiWithStatusErr != nil {
  79. return false
  80. }
  81. if status != common.ChannelStatusAutoDisabled {
  82. return false
  83. }
  84. return true
  85. }