init
This commit is contained in:
commit
aadfaba7a6
6 files changed
+640
No files matched your search
@@ -0,0 +1,19 @@
|
|||||||
|
|
||||||
|
## 构建
|
||||||
|
|
||||||
|
阅读golang标准构建方式以更好构建到其他平台架构
|
||||||
|
|
||||||
|
```shell
|
||||||
|
go build
|
||||||
|
./xray-stats
|
||||||
|
```
|
||||||
|
|
||||||
|
## 开发
|
||||||
|
|
||||||
|
> 前置条件 安装对应平台的xray可执行文件并将其放到项目根目录
|
||||||
|
|
||||||
|
```shell
|
||||||
|
./xray
|
||||||
|
go run
|
||||||
|
```
|
||||||
|
打开 127.0.0.1:8080 网站即可查看控制界面
|
||||||
+48
@@ -0,0 +1,48 @@
|
|||||||
|
{
|
||||||
|
"log": {
|
||||||
|
"access": "./access.log",
|
||||||
|
"error": "./error.log",
|
||||||
|
"loglevel": "debug"
|
||||||
|
},
|
||||||
|
"stats": {},
|
||||||
|
"api": { "tag": "api", "services": ["StatsService", "ReflectionService"] },
|
||||||
|
"policy": {
|
||||||
|
"levels": { "0": { "statsUserUplink": true, "statsUserDownlink": true } },
|
||||||
|
"system": {
|
||||||
|
"statsInboundUplink": true, "statsInboundDownlink": true,
|
||||||
|
"statsOutboundUplink": true, "statsOutboundDownlink": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"inbounds": [
|
||||||
|
{
|
||||||
|
"listen": "127.0.0.1",
|
||||||
|
"tag": "tunnel-in",
|
||||||
|
"port": 4431,
|
||||||
|
"protocol": "tunnel",
|
||||||
|
"settings": {
|
||||||
|
"address": "speed.cloudflare.com",
|
||||||
|
"port": 443,
|
||||||
|
"network": "tcp"
|
||||||
|
},
|
||||||
|
"sniffing": { "enabled": true, "destOverride": ["tls"], "routeOnly": true }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"listen": "127.0.0.1",
|
||||||
|
"port": 10085,
|
||||||
|
"protocol": "dokodemo-door",
|
||||||
|
"settings": { "address": "127.0.0.1" },
|
||||||
|
"tag": "api"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"outbounds": [
|
||||||
|
{ "protocol": "freedom", "tag": "direct" },
|
||||||
|
{ "protocol": "blackhole", "tag": "block" }
|
||||||
|
],
|
||||||
|
"routing": {
|
||||||
|
"rules": [
|
||||||
|
{ "inboundTag": ["tunnel-in"], "domain": ["speed.cloudflare.com"], "outboundTag": "direct" },
|
||||||
|
{ "inboundTag": ["tunnel-in"], "outboundTag": "block" },
|
||||||
|
{ "inboundTag": ["api"], "outboundTag": "api", "type": "field" }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
module xray-stats
|
||||||
|
|
||||||
|
go 1.26.3
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/pires/go-proxyproto v0.11.0 // indirect
|
||||||
|
github.com/sagernet/sing v0.5.1 // indirect
|
||||||
|
github.com/xtls/xray-core v1.260327.0 // indirect
|
||||||
|
golang.org/x/net v0.57.0 // indirect
|
||||||
|
golang.org/x/sys v0.47.0 // indirect
|
||||||
|
golang.org/x/text v0.40.0 // indirect
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 // indirect
|
||||||
|
google.golang.org/grpc v1.84.0 // indirect
|
||||||
|
google.golang.org/protobuf v1.36.11 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
github.com/pires/go-proxyproto v0.11.0 h1:gUQpS85X/VJMdUsYyEgyn59uLJvGqPhJV5YvG68wXH4=
|
||||||
|
github.com/pires/go-proxyproto v0.11.0/go.mod h1:ZKAAyp3cgy5Y5Mo4n9AlScrkCZwUy0g3Jf+slqQVcuU=
|
||||||
|
github.com/sagernet/sing v0.5.1 h1:mhL/MZVq0TjuvHcpYcFtmSD1BFOxZ/+8ofbNZcg1k1Y=
|
||||||
|
github.com/sagernet/sing v0.5.1/go.mod h1:ARkL0gM13/Iv5VCZmci/NuoOlePoIsW0m7BWfln/Hak=
|
||||||
|
github.com/xtls/xray-core v1.260327.0 h1:g4TzxMwyPrxslZh6uD+FiG3lXKTrnNO+b4ky2OhogHE=
|
||||||
|
github.com/xtls/xray-core v1.260327.0/go.mod h1:OXMlhBloFry8mw0KwWLWLd3RQyXJzEYsCGlgsX36h60=
|
||||||
|
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
|
||||||
|
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
|
||||||
|
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||||
|
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||||
|
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||||
|
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
|
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||||
|
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
|
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
|
||||||
|
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
|
||||||
|
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||||
|
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww=
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800 h1:qEHAMpSaUhtD0p3NbEEI83HwNGFxEwaSJ1G9PLnCBZE=
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20260706201446-f0a921348800/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||||
|
google.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=
|
||||||
|
google.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||||
|
google.golang.org/grpc v1.84.0 h1:soMyaPJ8pAak5PIQ0DGBUir0XRo2fRoMqhNWMLlLxO0=
|
||||||
|
google.golang.org/grpc v1.84.0/go.mod h1:ljCht0DrxQrXBDRTZp52Qxh3Ffk8CdYm2sj4O2QN2C0=
|
||||||
|
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||||
|
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/subtle"
|
||||||
|
"embed"
|
||||||
|
"encoding/json"
|
||||||
|
"flag"
|
||||||
|
"io/fs"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
statsService "github.com/xtls/xray-core/app/stats/command"
|
||||||
|
"google.golang.org/grpc"
|
||||||
|
"google.golang.org/grpc/credentials/insecure"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed web
|
||||||
|
var webFS embed.FS
|
||||||
|
|
||||||
|
// ===== 对应 examples/structures.go =====
|
||||||
|
|
||||||
|
type BaseConfig struct {
|
||||||
|
APIAddress string
|
||||||
|
APIPort uint16
|
||||||
|
}
|
||||||
|
|
||||||
|
type XrayController struct {
|
||||||
|
SsClient statsService.StatsServiceClient
|
||||||
|
CmdConn *grpc.ClientConn
|
||||||
|
}
|
||||||
|
|
||||||
|
// 对应 examples/init.go 的 Init,改用 NewClient
|
||||||
|
func (x *XrayController) Init(cfg *BaseConfig) error {
|
||||||
|
addr := cfg.APIAddress + ":" + itoa(uint32(cfg.APIPort))
|
||||||
|
conn, err := grpc.NewClient(
|
||||||
|
"passthrough:///"+addr,
|
||||||
|
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
x.CmdConn = conn
|
||||||
|
x.SsClient = statsService.NewStatsServiceClient(conn)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func itoa(n uint32) string {
|
||||||
|
if n == 0 {
|
||||||
|
return "0"
|
||||||
|
}
|
||||||
|
var b [10]byte
|
||||||
|
i := len(b)
|
||||||
|
for n > 0 {
|
||||||
|
i--
|
||||||
|
b[i] = byte('0' + n%10)
|
||||||
|
n /= 10
|
||||||
|
}
|
||||||
|
return string(b[i:])
|
||||||
|
}
|
||||||
|
|
||||||
|
// HTTP
|
||||||
|
|
||||||
|
type Stat struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Value int64 `json:"value"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Server struct {
|
||||||
|
ctl *XrayController
|
||||||
|
token string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) checkAuth(r *http.Request) bool {
|
||||||
|
if s.token == "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
want := "Bearer " + s.token
|
||||||
|
return subtle.ConstantTimeCompare(
|
||||||
|
[]byte(r.Header.Get("Authorization")), []byte(want),
|
||||||
|
) == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.Method == http.MethodOptions {
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !s.checkAuth(r) {
|
||||||
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
resp, err := s.ctl.SsClient.QueryStats(ctx, &statsService.QueryStatsRequest{})
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
out := make([]Stat, 0, len(resp.Stat))
|
||||||
|
for _, st := range resp.Stat {
|
||||||
|
out = append(out, Stat{Name: st.Name, Value: st.Value})
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(map[string]any{"stat": out})
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
var (
|
||||||
|
listen = flag.String("listen", "127.0.0.1:8080", "HTTP listen address")
|
||||||
|
apiAddr = flag.String("api-address", "127.0.0.1", "Xray API address")
|
||||||
|
apiPort = flag.Uint("api-port", 10085, "Xray API port")
|
||||||
|
token = flag.String("token", "", "Bearer token, empty disables auth")
|
||||||
|
)
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
cfg := &BaseConfig{
|
||||||
|
APIAddress: *apiAddr,
|
||||||
|
APIPort: uint16(*apiPort),
|
||||||
|
}
|
||||||
|
|
||||||
|
ctl := new(XrayController)
|
||||||
|
if err := ctl.Init(cfg); err != nil {
|
||||||
|
log.Fatalf("init: %v", err)
|
||||||
|
}
|
||||||
|
defer ctl.CmdConn.Close()
|
||||||
|
|
||||||
|
srv := &Server{ctl: ctl, token: *token}
|
||||||
|
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("/stats", srv.handleStats)
|
||||||
|
|
||||||
|
sub, err := fs.Sub(webFS, "web")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("embed fs: %v", err)
|
||||||
|
}
|
||||||
|
mux.Handle("/", http.FileServer(http.FS(sub)))
|
||||||
|
|
||||||
|
log.Printf("listening %s | xray %s:%d | auth=%v",
|
||||||
|
*listen, *apiAddr, *apiPort, *token != "")
|
||||||
|
|
||||||
|
log.Fatal(http.ListenAndServe(*listen, mux))
|
||||||
|
}
|
||||||
+382
@@ -0,0 +1,382 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Xray 流量统计</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--bg: #0b0d12;
|
||||||
|
--panel: #151821;
|
||||||
|
--panel-2: #1c2029;
|
||||||
|
--border: #262b36;
|
||||||
|
--text: #e8ebf2;
|
||||||
|
--muted: #8891a8;
|
||||||
|
--accent: #4f8cff;
|
||||||
|
--red: #ff6b6b;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body {
|
||||||
|
margin: 0; background: var(--bg); color: var(--text);
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
|
||||||
|
"PingFang SC", "Microsoft YaHei", sans-serif;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
.hidden { display: none !important; }
|
||||||
|
button {
|
||||||
|
background: var(--accent); color: #fff; border: none;
|
||||||
|
padding: 8px 16px; border-radius: 8px; font-size: 14px;
|
||||||
|
cursor: pointer; font-weight: 500;
|
||||||
|
}
|
||||||
|
button:hover { opacity: .88; }
|
||||||
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
||||||
|
button.ghost { background: transparent; border: 1px solid var(--border); color: var(--text); }
|
||||||
|
input, select {
|
||||||
|
width: 100%; padding: 9px 12px; background: var(--panel-2);
|
||||||
|
border: 1px solid var(--border); border-radius: 8px;
|
||||||
|
color: var(--text); font-size: 13px; outline: none;
|
||||||
|
}
|
||||||
|
input:focus, select:focus { border-color: var(--accent); }
|
||||||
|
label { display: block; color: var(--muted); font-size: 12px; margin-bottom: 6px; }
|
||||||
|
|
||||||
|
.wrap { max-width: 1100px; margin: 0 auto; padding: 20px; }
|
||||||
|
header { display: flex; align-items: center; justify-content: space-between;
|
||||||
|
margin-bottom: 20px; gap: 12px; flex-wrap: wrap; }
|
||||||
|
header h1 { font-size: 18px; margin: 0; }
|
||||||
|
.status { color: var(--muted); font-size: 12px; margin-top: 4px; }
|
||||||
|
.actions { display: flex; gap: 8px; }
|
||||||
|
|
||||||
|
.panel {
|
||||||
|
background: var(--panel); border: 1px solid var(--border);
|
||||||
|
border-radius: 12px; padding: 16px; margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
.panel h2 { font-size: 14px; margin: 0 0 12px; color: var(--muted); font-weight: 500; }
|
||||||
|
|
||||||
|
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||||
|
gap: 12px; margin-bottom: 16px; }
|
||||||
|
.card { background: var(--panel); border: 1px solid var(--border);
|
||||||
|
border-radius: 12px; padding: 16px; }
|
||||||
|
.card .label { color: var(--muted); font-size: 12px; margin-bottom: 8px; }
|
||||||
|
.card .value { font-size: 22px; font-weight: 600; }
|
||||||
|
.card .sub { color: var(--muted); font-size: 12px; margin-top: 4px; }
|
||||||
|
|
||||||
|
table { width: 100%; border-collapse: collapse; }
|
||||||
|
th, td { padding: 10px 12px; text-align: left; font-size: 13px; }
|
||||||
|
th { color: var(--muted); font-weight: 500; border-bottom: 1px solid var(--border);
|
||||||
|
font-size: 12px; }
|
||||||
|
td { border-bottom: 1px solid var(--border); }
|
||||||
|
tr:last-child td { border-bottom: none; }
|
||||||
|
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
|
||||||
|
.tag { color: var(--accent); font-weight: 500; }
|
||||||
|
|
||||||
|
.row { display: flex; gap: 12px; flex-wrap: wrap; }
|
||||||
|
.row > div { flex: 1; min-width: 200px; }
|
||||||
|
|
||||||
|
.tabs { display: flex; gap: 6px; margin-bottom: 12px; }
|
||||||
|
.tabs button { background: transparent; color: var(--muted);
|
||||||
|
border: 1px solid var(--border); padding: 6px 14px; font-size: 13px; }
|
||||||
|
.tabs button.active { background: var(--accent); color: #fff; border-color: var(--accent); }
|
||||||
|
.empty { color: var(--muted); padding: 24px; text-align: center; }
|
||||||
|
.err { color: var(--red); font-size: 12px; margin-top: 6px; min-height: 16px; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<div class="wrap">
|
||||||
|
<header>
|
||||||
|
<div>
|
||||||
|
<h1>Xray 流量统计</h1>
|
||||||
|
<div class="status" id="status">未加载</div>
|
||||||
|
</div>
|
||||||
|
<div class="actions">
|
||||||
|
<button class="ghost" id="toggleSettings">设置</button>
|
||||||
|
<button id="refreshBtn">刷新</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div class="panel hidden" id="settingsPanel">
|
||||||
|
<h2>设置</h2>
|
||||||
|
<div class="row">
|
||||||
|
<div>
|
||||||
|
<label>API URL</label>
|
||||||
|
<input type="text" id="apiUrl" placeholder="/stats">
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label>Token(留空表示不鉴权)</label>
|
||||||
|
<input type="text" id="apiToken" placeholder="">
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label>自动刷新</label>
|
||||||
|
<select id="refreshSel">
|
||||||
|
<option value="0">关闭</option>
|
||||||
|
<option value="5">5 秒</option>
|
||||||
|
<option value="10">10 秒</option>
|
||||||
|
<option value="30">30 秒</option>
|
||||||
|
<option value="60">60 秒</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div style="margin-top:14px; display:flex; gap:8px;">
|
||||||
|
<button id="saveBtn">保存并刷新</button>
|
||||||
|
<button class="ghost" id="resetBtn">恢复默认</button>
|
||||||
|
</div>
|
||||||
|
<div class="err" id="settingsErr"></div>
|
||||||
|
<div style="color:var(--muted); font-size:12px; margin-top:10px;">
|
||||||
|
提示:可以用 <code>?token=xxx</code> 或 <code>?api=/stats&token=xxx</code>
|
||||||
|
从 URL 直接带入配置。
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="cards" id="cards"></div>
|
||||||
|
|
||||||
|
<div class="panel">
|
||||||
|
<div class="tabs" id="tabs">
|
||||||
|
<button data-view="user" class="active">用户</button>
|
||||||
|
<button data-view="inbound">入站</button>
|
||||||
|
<button data-view="outbound">出站</button>
|
||||||
|
</div>
|
||||||
|
<div id="tableWrap"><div class="empty">暂无数据</div></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const DEFAULTS = {
|
||||||
|
apiUrl: '/stats',
|
||||||
|
apiToken: '',
|
||||||
|
refresh: 10
|
||||||
|
};
|
||||||
|
const LS_KEY = 'xray_stats_cfg_v1';
|
||||||
|
|
||||||
|
const state = {
|
||||||
|
cfg: { ...DEFAULTS },
|
||||||
|
agg: null,
|
||||||
|
view: 'user',
|
||||||
|
lastUpdated: null,
|
||||||
|
count: 0
|
||||||
|
};
|
||||||
|
let timer = null;
|
||||||
|
|
||||||
|
/* ---------- 配置读写 ---------- */
|
||||||
|
function loadCfg() {
|
||||||
|
// 1) URL query 优先
|
||||||
|
const q = new URLSearchParams(location.search);
|
||||||
|
const cfg = { ...DEFAULTS };
|
||||||
|
if (q.has('api')) cfg.apiUrl = q.get('api');
|
||||||
|
if (q.has('token')) cfg.apiToken = q.get('token');
|
||||||
|
if (q.has('refresh')) cfg.refresh = Number(q.get('refresh')) || 0;
|
||||||
|
|
||||||
|
// 2) 再用 localStorage 覆盖(URL 没给的字段)
|
||||||
|
try {
|
||||||
|
const saved = JSON.parse(localStorage.getItem(LS_KEY) || '{}');
|
||||||
|
if (!q.has('api') && saved.apiUrl) cfg.apiUrl = saved.apiUrl;
|
||||||
|
if (!q.has('token') && saved.apiToken) cfg.apiToken = saved.apiToken;
|
||||||
|
if (!q.has('refresh') && saved.refresh != null) cfg.refresh = saved.refresh;
|
||||||
|
} catch (e) {}
|
||||||
|
|
||||||
|
return cfg;
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveCfg() {
|
||||||
|
localStorage.setItem(LS_KEY, JSON.stringify(state.cfg));
|
||||||
|
}
|
||||||
|
|
||||||
|
function fillSettings() {
|
||||||
|
document.getElementById('apiUrl').value = state.cfg.apiUrl;
|
||||||
|
document.getElementById('apiToken').value = state.cfg.apiToken;
|
||||||
|
document.getElementById('refreshSel').value = String(state.cfg.refresh);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 工具 ---------- */
|
||||||
|
function humanBytes(n) {
|
||||||
|
n = Number(n) || 0;
|
||||||
|
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
|
||||||
|
let i = 0;
|
||||||
|
while (n >= 1024 && i < units.length - 1) { n /= 1024; i++; }
|
||||||
|
return (i === 0 ? n : n.toFixed(2)) + ' ' + units[i];
|
||||||
|
}
|
||||||
|
function escapeHtml(s) {
|
||||||
|
return String(s).replace(/[&<>"']/g, c => ({
|
||||||
|
'&':'&','<':'<','>':'>','"':'"',"'":'''
|
||||||
|
}[c]));
|
||||||
|
}
|
||||||
|
function sum(obj, dir) {
|
||||||
|
return Object.values(obj).reduce((a, d) => a + (d[dir] || 0), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 解析 stats ---------- */
|
||||||
|
function parseStats(json) {
|
||||||
|
const agg = { user: {}, inbound: {}, outbound: {} };
|
||||||
|
for (const item of (json && json.stat) || []) {
|
||||||
|
const parts = (item.name || '').split('>>>');
|
||||||
|
if (parts.length !== 4) continue;
|
||||||
|
const [type, tag, traffic, dir] = parts;
|
||||||
|
if (traffic !== 'traffic') continue;
|
||||||
|
if (!agg[type]) continue;
|
||||||
|
if (dir !== 'uplink' && dir !== 'downlink') continue;
|
||||||
|
if (!agg[type][tag]) agg[type][tag] = { uplink: 0, downlink: 0 };
|
||||||
|
agg[type][tag][dir] += Number(item.value || 0);
|
||||||
|
}
|
||||||
|
return agg;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 渲染 ---------- */
|
||||||
|
function renderCards() {
|
||||||
|
const uUp = sum(state.agg.user, 'uplink');
|
||||||
|
const uDown = sum(state.agg.user, 'downlink');
|
||||||
|
const iUp = sum(state.agg.inbound, 'uplink');
|
||||||
|
const iDown = sum(state.agg.inbound, 'downlink');
|
||||||
|
const oUp = sum(state.agg.outbound, 'uplink');
|
||||||
|
const oDown = sum(state.agg.outbound, 'downlink');
|
||||||
|
|
||||||
|
document.getElementById('cards').innerHTML = `
|
||||||
|
<div class="card">
|
||||||
|
<div class="label">用户总流量</div>
|
||||||
|
<div class="value">${humanBytes(uUp + uDown)}</div>
|
||||||
|
<div class="sub">↑ ${humanBytes(uUp)} · ↓ ${humanBytes(uDown)}</div>
|
||||||
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="label">入站总流量</div>
|
||||||
|
<div class="value">${humanBytes(iUp + iDown)}</div>
|
||||||
|
<div class="sub">↑ ${humanBytes(iUp)} · ↓ ${humanBytes(iDown)}</div>
|
||||||
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="label">出站总流量</div>
|
||||||
|
<div class="value">${humanBytes(oUp + oDown)}</div>
|
||||||
|
<div class="sub">↑ ${humanBytes(oUp)} · ↓ ${humanBytes(oDown)}</div>
|
||||||
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="label">最近更新</div>
|
||||||
|
<div class="value" style="font-size:16px">
|
||||||
|
${state.lastUpdated ? state.lastUpdated.toLocaleTimeString() : '-'}
|
||||||
|
</div>
|
||||||
|
<div class="sub">共 ${state.count} 条记录</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderTable() {
|
||||||
|
const data = state.agg[state.view] || {};
|
||||||
|
const rows = Object.entries(data).map(([tag, d]) => ({
|
||||||
|
tag, uplink: d.uplink, downlink: d.downlink,
|
||||||
|
total: d.uplink + d.downlink
|
||||||
|
})).sort((a, b) => b.total - a.total);
|
||||||
|
|
||||||
|
const wrap = document.getElementById('tableWrap');
|
||||||
|
if (!rows.length) {
|
||||||
|
wrap.innerHTML = '<div class="empty">无数据</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let html = '<table><thead><tr><th>名称</th><th class="num">上行</th>'
|
||||||
|
+ '<th class="num">下行</th><th class="num">总计</th></tr></thead><tbody>';
|
||||||
|
for (const r of rows) {
|
||||||
|
html += `<tr>
|
||||||
|
<td><span class="tag">${escapeHtml(r.tag)}</span></td>
|
||||||
|
<td class="num">${humanBytes(r.uplink)}</td>
|
||||||
|
<td class="num">${humanBytes(r.downlink)}</td>
|
||||||
|
<td class="num">${humanBytes(r.total)}</td>
|
||||||
|
</tr>`;
|
||||||
|
}
|
||||||
|
html += '</tbody></table>';
|
||||||
|
wrap.innerHTML = html;
|
||||||
|
}
|
||||||
|
|
||||||
|
function render() {
|
||||||
|
if (!state.agg) return;
|
||||||
|
renderCards();
|
||||||
|
renderTable();
|
||||||
|
}
|
||||||
|
|
||||||
|
function setStatus(msg) {
|
||||||
|
document.getElementById('status').textContent = msg;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 拉数据 ---------- */
|
||||||
|
async function fetchStats() {
|
||||||
|
const { apiUrl, apiToken } = state.cfg;
|
||||||
|
setStatus('加载中…');
|
||||||
|
|
||||||
|
try {
|
||||||
|
const headers = {};
|
||||||
|
if (apiToken) headers['Authorization'] = 'Bearer ' + apiToken;
|
||||||
|
|
||||||
|
const res = await fetch(apiUrl, { cache: 'no-store', headers });
|
||||||
|
|
||||||
|
if (res.status === 401) {
|
||||||
|
setStatus('未授权:请检查 Token');
|
||||||
|
document.getElementById('settingsPanel').classList.remove('hidden');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!res.ok) throw new Error('HTTP ' + res.status);
|
||||||
|
|
||||||
|
const json = await res.json();
|
||||||
|
state.agg = parseStats(json);
|
||||||
|
state.lastUpdated = new Date();
|
||||||
|
state.count = (json.stat || []).length;
|
||||||
|
render();
|
||||||
|
setStatus('已更新');
|
||||||
|
} catch (e) {
|
||||||
|
setStatus('加载失败:' + e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 定时刷新 ---------- */
|
||||||
|
function setupRefresh() {
|
||||||
|
if (timer) clearInterval(timer);
|
||||||
|
timer = null;
|
||||||
|
const sec = Number(state.cfg.refresh) || 0;
|
||||||
|
if (sec > 0) timer = setInterval(fetchStats, sec * 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 事件 ---------- */
|
||||||
|
function bind() {
|
||||||
|
document.getElementById('toggleSettings').onclick = () => {
|
||||||
|
document.getElementById('settingsPanel').classList.toggle('hidden');
|
||||||
|
};
|
||||||
|
|
||||||
|
document.getElementById('refreshBtn').onclick = fetchStats;
|
||||||
|
|
||||||
|
document.getElementById('saveBtn').onclick = () => {
|
||||||
|
const apiUrl = document.getElementById('apiUrl').value.trim() || DEFAULTS.apiUrl;
|
||||||
|
const apiToken = document.getElementById('apiToken').value.trim();
|
||||||
|
const refresh = Number(document.getElementById('refreshSel').value) || 0;
|
||||||
|
state.cfg = { apiUrl, apiToken, refresh };
|
||||||
|
saveCfg();
|
||||||
|
document.getElementById('settingsErr').textContent = '';
|
||||||
|
setupRefresh();
|
||||||
|
fetchStats();
|
||||||
|
};
|
||||||
|
|
||||||
|
document.getElementById('resetBtn').onclick = () => {
|
||||||
|
state.cfg = { ...DEFAULTS };
|
||||||
|
saveCfg();
|
||||||
|
fillSettings();
|
||||||
|
setupRefresh();
|
||||||
|
fetchStats();
|
||||||
|
};
|
||||||
|
|
||||||
|
document.getElementById('tabs').addEventListener('click', e => {
|
||||||
|
const btn = e.target.closest('button[data-view]');
|
||||||
|
if (!btn) return;
|
||||||
|
state.view = btn.dataset.view;
|
||||||
|
document.querySelectorAll('#tabs button').forEach(b =>
|
||||||
|
b.classList.toggle('active', b === btn));
|
||||||
|
if (state.agg) renderTable();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 启动 ---------- */
|
||||||
|
(function init() {
|
||||||
|
state.cfg = loadCfg();
|
||||||
|
fillSettings();
|
||||||
|
bind();
|
||||||
|
setupRefresh();
|
||||||
|
fetchStats();
|
||||||
|
|
||||||
|
// 首次访问且没配置过,展开设置面板
|
||||||
|
if (!localStorage.getItem(LS_KEY) && !location.search) {
|
||||||
|
document.getElementById('settingsPanel').classList.remove('hidden');
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in new issue
Block a user