xray.go 1.9 KB

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