Files
waf-platform/EdgeUser/internal/web/actions/default/servers/traffic-stats/download.go

106 lines
2.7 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/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeUser/internal/configloaders"
"github.com/TeaOSLab/EdgeUser/internal/web/actions/actionutils"
"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
ServerId int64
}) {
// 是否显示带宽
config, err := configloaders.LoadUIConfig()
if err != nil {
this.ErrorPage(err)
return
}
if config == nil || !config.ShowBandwidthCharts {
return
}
// 用户名
var username = "unknown"
userResp, err := this.RPC().UserRPC().FindEnabledUser(this.UserContext(), &pb.FindEnabledUserRequest{UserId: this.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.UserContext(), &pb.FindDailyServerBandwidthStatsBetweenDaysRequest{
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())
}