api.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package xray
  2. import (
  3. "context"
  4. "fmt"
  5. "regexp"
  6. "time"
  7. "x-ui/util/common"
  8. "github.com/xtls/xray-core/app/proxyman/command"
  9. statsService "github.com/xtls/xray-core/app/stats/command"
  10. "github.com/xtls/xray-core/common/protocol"
  11. "github.com/xtls/xray-core/common/serial"
  12. "github.com/xtls/xray-core/proxy/shadowsocks"
  13. "github.com/xtls/xray-core/proxy/trojan"
  14. "github.com/xtls/xray-core/proxy/vless"
  15. "github.com/xtls/xray-core/proxy/vmess"
  16. "google.golang.org/grpc"
  17. "google.golang.org/grpc/credentials/insecure"
  18. )
  19. type XrayAPI struct {
  20. HandlerServiceClient *command.HandlerServiceClient
  21. StatsServiceClient *statsService.StatsServiceClient
  22. grpcClient *grpc.ClientConn
  23. isConnected bool
  24. }
  25. func (x *XrayAPI) Init(apiPort int) (err error) {
  26. if apiPort == 0 {
  27. return common.NewError("xray api port wrong:", apiPort)
  28. }
  29. x.grpcClient, err = grpc.Dial(fmt.Sprintf("127.0.0.1:%v", apiPort), grpc.WithTransportCredentials(insecure.NewCredentials()))
  30. if err != nil {
  31. return err
  32. }
  33. x.isConnected = true
  34. hsClient := command.NewHandlerServiceClient(x.grpcClient)
  35. ssClient := statsService.NewStatsServiceClient(x.grpcClient)
  36. x.HandlerServiceClient = &hsClient
  37. x.StatsServiceClient = &ssClient
  38. return
  39. }
  40. func (x *XrayAPI) Close() {
  41. x.grpcClient.Close()
  42. x.HandlerServiceClient = nil
  43. x.StatsServiceClient = nil
  44. x.isConnected = false
  45. }
  46. func (x *XrayAPI) AddUser(Protocol string, inboundTag string, user map[string]interface{}) error {
  47. var account *serial.TypedMessage
  48. switch Protocol {
  49. case "vmess":
  50. account = serial.ToTypedMessage(&vmess.Account{
  51. Id: user["id"].(string),
  52. AlterId: uint32(user["alterId"].(uint16)),
  53. })
  54. case "vless":
  55. account = serial.ToTypedMessage(&vless.Account{
  56. Id: user["id"].(string),
  57. Flow: user["flow"].(string),
  58. })
  59. case "trojan":
  60. account = serial.ToTypedMessage(&trojan.Account{
  61. Password: user["password"].(string),
  62. })
  63. case "shadowsocks":
  64. account = serial.ToTypedMessage(&shadowsocks.Account{
  65. Password: user["password"].(string),
  66. })
  67. default:
  68. return nil
  69. }
  70. client := *x.HandlerServiceClient
  71. _, err := client.AlterInbound(context.Background(), &command.AlterInboundRequest{
  72. Tag: inboundTag,
  73. Operation: serial.ToTypedMessage(&command.AddUserOperation{
  74. User: &protocol.User{
  75. Email: user["email"].(string),
  76. Account: account,
  77. },
  78. }),
  79. })
  80. return err
  81. }
  82. func (x *XrayAPI) RemoveUser(inboundTag string, email string) error {
  83. client := *x.HandlerServiceClient
  84. _, err := client.AlterInbound(context.Background(), &command.AlterInboundRequest{
  85. Tag: inboundTag,
  86. Operation: serial.ToTypedMessage(&command.RemoveUserOperation{
  87. Email: email,
  88. }),
  89. })
  90. return err
  91. }
  92. func (x *XrayAPI) GetTraffic(reset bool) ([]*Traffic, []*ClientTraffic, error) {
  93. if x.grpcClient == nil {
  94. return nil, nil, common.NewError("xray api is not initialized")
  95. }
  96. var trafficRegex = regexp.MustCompile("(inbound|outbound)>>>([^>]+)>>>traffic>>>(downlink|uplink)")
  97. var ClientTrafficRegex = regexp.MustCompile("(user)>>>([^>]+)>>>traffic>>>(downlink|uplink)")
  98. client := *x.StatsServiceClient
  99. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  100. defer cancel()
  101. request := &statsService.QueryStatsRequest{
  102. Reset_: reset,
  103. }
  104. resp, err := client.QueryStats(ctx, request)
  105. if err != nil {
  106. return nil, nil, err
  107. }
  108. tagTrafficMap := map[string]*Traffic{}
  109. emailTrafficMap := map[string]*ClientTraffic{}
  110. clientTraffics := make([]*ClientTraffic, 0)
  111. traffics := make([]*Traffic, 0)
  112. for _, stat := range resp.GetStat() {
  113. matchs := trafficRegex.FindStringSubmatch(stat.Name)
  114. if len(matchs) < 3 {
  115. matchs := ClientTrafficRegex.FindStringSubmatch(stat.Name)
  116. if len(matchs) < 3 {
  117. continue
  118. } else {
  119. isUser := matchs[1] == "user"
  120. email := matchs[2]
  121. isDown := matchs[3] == "downlink"
  122. if !isUser {
  123. continue
  124. }
  125. traffic, ok := emailTrafficMap[email]
  126. if !ok {
  127. traffic = &ClientTraffic{
  128. Email: email,
  129. }
  130. emailTrafficMap[email] = traffic
  131. clientTraffics = append(clientTraffics, traffic)
  132. }
  133. if isDown {
  134. traffic.Down = stat.Value
  135. } else {
  136. traffic.Up = stat.Value
  137. }
  138. }
  139. continue
  140. }
  141. isInbound := matchs[1] == "inbound"
  142. tag := matchs[2]
  143. isDown := matchs[3] == "downlink"
  144. if tag == "api" {
  145. continue
  146. }
  147. traffic, ok := tagTrafficMap[tag]
  148. if !ok {
  149. traffic = &Traffic{
  150. IsInbound: isInbound,
  151. Tag: tag,
  152. }
  153. tagTrafficMap[tag] = traffic
  154. traffics = append(traffics, traffic)
  155. }
  156. if isDown {
  157. traffic.Down = stat.Value
  158. } else {
  159. traffic.Up = stat.Value
  160. }
  161. }
  162. return traffics, clientTraffics, nil
  163. }