api.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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. })
  53. case "vless":
  54. account = serial.ToTypedMessage(&vless.Account{
  55. Id: user["id"].(string),
  56. Flow: user["flow"].(string),
  57. })
  58. case "trojan":
  59. account = serial.ToTypedMessage(&trojan.Account{
  60. Password: user["password"].(string),
  61. })
  62. case "shadowsocks":
  63. account = serial.ToTypedMessage(&shadowsocks.Account{
  64. Password: user["password"].(string),
  65. })
  66. default:
  67. return nil
  68. }
  69. client := *x.HandlerServiceClient
  70. _, err := client.AlterInbound(context.Background(), &command.AlterInboundRequest{
  71. Tag: inboundTag,
  72. Operation: serial.ToTypedMessage(&command.AddUserOperation{
  73. User: &protocol.User{
  74. Email: user["email"].(string),
  75. Account: account,
  76. },
  77. }),
  78. })
  79. return err
  80. }
  81. func (x *XrayAPI) RemoveUser(inboundTag string, email string) error {
  82. client := *x.HandlerServiceClient
  83. _, err := client.AlterInbound(context.Background(), &command.AlterInboundRequest{
  84. Tag: inboundTag,
  85. Operation: serial.ToTypedMessage(&command.RemoveUserOperation{
  86. Email: email,
  87. }),
  88. })
  89. return err
  90. }
  91. func (x *XrayAPI) GetTraffic(reset bool) ([]*Traffic, []*ClientTraffic, error) {
  92. if x.grpcClient == nil {
  93. return nil, nil, common.NewError("xray api is not initialized")
  94. }
  95. var trafficRegex = regexp.MustCompile("(inbound|outbound)>>>([^>]+)>>>traffic>>>(downlink|uplink)")
  96. var ClientTrafficRegex = regexp.MustCompile("(user)>>>([^>]+)>>>traffic>>>(downlink|uplink)")
  97. client := *x.StatsServiceClient
  98. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  99. defer cancel()
  100. request := &statsService.QueryStatsRequest{
  101. Reset_: reset,
  102. }
  103. resp, err := client.QueryStats(ctx, request)
  104. if err != nil {
  105. return nil, nil, err
  106. }
  107. tagTrafficMap := map[string]*Traffic{}
  108. emailTrafficMap := map[string]*ClientTraffic{}
  109. clientTraffics := make([]*ClientTraffic, 0)
  110. traffics := make([]*Traffic, 0)
  111. for _, stat := range resp.GetStat() {
  112. matchs := trafficRegex.FindStringSubmatch(stat.Name)
  113. if len(matchs) < 3 {
  114. matchs := ClientTrafficRegex.FindStringSubmatch(stat.Name)
  115. if len(matchs) < 3 {
  116. continue
  117. } else {
  118. isUser := matchs[1] == "user"
  119. email := matchs[2]
  120. isDown := matchs[3] == "downlink"
  121. if !isUser {
  122. continue
  123. }
  124. traffic, ok := emailTrafficMap[email]
  125. if !ok {
  126. traffic = &ClientTraffic{
  127. Email: email,
  128. }
  129. emailTrafficMap[email] = traffic
  130. clientTraffics = append(clientTraffics, traffic)
  131. }
  132. if isDown {
  133. traffic.Down = stat.Value
  134. } else {
  135. traffic.Up = stat.Value
  136. }
  137. }
  138. continue
  139. }
  140. isInbound := matchs[1] == "inbound"
  141. tag := matchs[2]
  142. isDown := matchs[3] == "downlink"
  143. if tag == "api" {
  144. continue
  145. }
  146. traffic, ok := tagTrafficMap[tag]
  147. if !ok {
  148. traffic = &Traffic{
  149. IsInbound: isInbound,
  150. Tag: tag,
  151. }
  152. tagTrafficMap[tag] = traffic
  153. traffics = append(traffics, traffic)
  154. }
  155. if isDown {
  156. traffic.Down = stat.Value
  157. } else {
  158. traffic.Up = stat.Value
  159. }
  160. }
  161. return traffics, clientTraffics, nil
  162. }