xray.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. package service
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "go.uber.org/atomic"
  6. "sync"
  7. "x-ui/xray"
  8. )
  9. var p *xray.Process
  10. var lock sync.Mutex
  11. var result string
  12. type XrayService struct {
  13. inboundService InboundService
  14. settingService SettingService
  15. isNeedXrayRestart atomic.Bool
  16. }
  17. func (s *XrayService) IsXrayRunning() bool {
  18. return p != nil && p.IsRunning()
  19. }
  20. func (s *XrayService) GetXrayErr() error {
  21. if p == nil {
  22. return nil
  23. }
  24. return p.GetErr()
  25. }
  26. func (s *XrayService) GetXrayResult() string {
  27. if result != "" {
  28. return result
  29. }
  30. if s.IsXrayRunning() {
  31. return ""
  32. }
  33. if p == nil {
  34. return ""
  35. }
  36. result = p.GetResult()
  37. return result
  38. }
  39. func (s *XrayService) GetXrayVersion() string {
  40. if p == nil {
  41. return "Unknown"
  42. }
  43. return p.GetVersion()
  44. }
  45. func (s *XrayService) GetXrayConfig() (*xray.Config, error) {
  46. templateConfig, err := s.settingService.GetXrayConfigTemplate()
  47. if err != nil {
  48. return nil, err
  49. }
  50. xrayConfig := &xray.Config{}
  51. err = json.Unmarshal([]byte(templateConfig), xrayConfig)
  52. if err != nil {
  53. return nil, err
  54. }
  55. inbounds, err := s.inboundService.GetAllInbounds()
  56. if err != nil {
  57. return nil, err
  58. }
  59. for _, inbound := range inbounds {
  60. if !inbound.Enable {
  61. continue
  62. }
  63. inboundConfig := inbound.GenXrayInboundConfig()
  64. xrayConfig.InboundConfigs = append(xrayConfig.InboundConfigs, *inboundConfig)
  65. }
  66. return xrayConfig, nil
  67. }
  68. func (s *XrayService) GetXrayTraffic() ([]*xray.Traffic, error) {
  69. if !s.IsXrayRunning() {
  70. return nil, errors.New("xray is not running")
  71. }
  72. return p.GetTraffic(true)
  73. }
  74. func (s *XrayService) RestartXray() error {
  75. lock.Lock()
  76. defer lock.Unlock()
  77. xrayConfig, err := s.GetXrayConfig()
  78. if err != nil {
  79. return err
  80. }
  81. if p != nil {
  82. if p.GetConfig().Equals(xrayConfig) {
  83. return nil
  84. }
  85. p.Stop()
  86. }
  87. p = xray.NewProcess(xrayConfig)
  88. result = ""
  89. return p.Start()
  90. }
  91. func (s *XrayService) StopXray() error {
  92. lock.Lock()
  93. defer lock.Unlock()
  94. if s.IsXrayRunning() {
  95. return p.Stop()
  96. }
  97. return errors.New("xray is not running")
  98. }
  99. func (s *XrayService) SetIsNeedRestart(needRestart bool) {
  100. s.isNeedXrayRestart.Store(needRestart)
  101. }
  102. func (s *XrayService) IsNeedRestart() bool {
  103. return s.isNeedXrayRestart.Load()
  104. }