Files
waf-platform/EdgeAdmin/internal/web/actions/default/servers/traffic-stats/download.go
2026-02-04 20:27:13 +08:00

98 lines
2.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. Official site: https://goedge.cn .
package trafficstats
import (
"bytes"
"fmt"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/iwind/TeaGo/lists"
"github.com/iwind/TeaGo/types"
"github.com/tealeg/xlsx/v3"
"strconv"
"strings"
)
type DownloadAction struct {
actionutils.ParentAction
}
func (this *DownloadAction) Init() {
this.Nav("", "", "")
}
func (this *DownloadAction) RunGet(params struct {
DayFrom string
DayTo string
UserId int64
ServerId int64
}) {
// 用户名
var username = "unknown"
if params.UserId > 0 {
userResp, err := this.RPC().UserRPC().FindEnabledUser(this.AdminContext(), &pb.FindEnabledUserRequest{UserId: params.UserId})
if err != nil {
this.ErrorPage(err)
return
}
if userResp.User != nil {
username = userResp.User.Username
}
}
params.DayFrom = strings.ReplaceAll(params.DayFrom, "-", "")
params.DayTo = strings.ReplaceAll(params.DayTo, "-", "")
bandwidthStatsResp, err := this.RPC().ServerBandwidthStatRPC().FindDailyServerBandwidthStatsBetweenDays(this.AdminContext(), &pb.FindDailyServerBandwidthStatsBetweenDaysRequest{
UserId: params.UserId,
ServerId: params.ServerId,
DayFrom: params.DayFrom,
DayTo: params.DayTo,
})
if err != nil {
this.ErrorPage(err)
return
}
var wb = xlsx.NewFile()
sheet, err := wb.AddSheet("default")
if err != nil {
this.ErrorPage(err)
return
}
// 头部
{
var row = sheet.AddRow()
row.SetHeight(25)
row.AddCell().SetString("时间")
row.AddCell().SetString("带宽Mbps")
row.AddCell().SetString("带宽Gbps")
}
var stats = bandwidthStatsResp.Stats
lists.Reverse(stats)
for _, stat := range stats {
var row = sheet.AddRow()
row.SetHeight(25)
row.AddCell().SetString(stat.Day[:4] + "-" + stat.Day[4:6] + "-" + stat.Day[6:] + " " + stat.TimeAt[:2] + ":" + stat.TimeAt[2:])
row.AddCell().SetString(fmt.Sprintf("%.4f", float64(stat.Bits)/(1<<20)))
row.AddCell().SetString(fmt.Sprintf("%.4f", float64(stat.Bits)/(1<<30)))
}
this.AddHeader("Content-Type", "application/vnd.ms-excel")
this.AddHeader("Content-Disposition", "attachment; filename=\"BANDWIDTH-"+username+"-"+types.String(params.ServerId)+"-"+params.DayFrom+"-"+params.DayTo+".xlsx\"")
this.AddHeader("Cache-Control", "max-age=0")
var buf = bytes.NewBuffer([]byte{})
err = wb.Write(buf)
if err != nil {
this.ErrorPage(err)
return
}
this.AddHeader("Content-Length", strconv.Itoa(buf.Len()))
_, _ = this.Write(buf.Bytes())
}