mirror of
https://github.com/alireza0/x-ui.git
synced 2026-03-19 07:15:48 +00:00
first commit
This commit is contained in:
22
web/controller/base_controller.go
Normal file
22
web/controller/base_controller.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"x-ui/web/session"
|
||||
)
|
||||
|
||||
type BaseController struct {
|
||||
}
|
||||
|
||||
func NewBaseController(g *gin.RouterGroup) *BaseController {
|
||||
return &BaseController{}
|
||||
}
|
||||
|
||||
func (a *BaseController) before(c *gin.Context) {
|
||||
if !session.IsLogin(c) {
|
||||
pureJsonMsg(c, false, "登录时效已过,请重新登录")
|
||||
c.Abort()
|
||||
} else {
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
72
web/controller/index_controller.go
Normal file
72
web/controller/index_controller.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
"x-ui/logger"
|
||||
"x-ui/web/service"
|
||||
"x-ui/web/session"
|
||||
)
|
||||
|
||||
type LoginForm struct {
|
||||
Username string `json:"username" form:"username"`
|
||||
Password string `json:"password" form:"password"`
|
||||
}
|
||||
|
||||
type IndexController struct {
|
||||
BaseController
|
||||
|
||||
userService service.UserService
|
||||
}
|
||||
|
||||
func NewIndexController(g *gin.RouterGroup) *IndexController {
|
||||
a := &IndexController{}
|
||||
a.initRouter(g)
|
||||
return a
|
||||
}
|
||||
|
||||
func (a *IndexController) initRouter(g *gin.RouterGroup) {
|
||||
g.GET("/", a.index)
|
||||
g.POST("/login", a.login)
|
||||
g.GET("/logout", a.logout)
|
||||
}
|
||||
|
||||
func (a *IndexController) index(c *gin.Context) {
|
||||
html(c, "login.html", "登录", nil)
|
||||
}
|
||||
|
||||
func (a *IndexController) login(c *gin.Context) {
|
||||
var form LoginForm
|
||||
err := c.ShouldBind(&form)
|
||||
if err != nil {
|
||||
pureJsonMsg(c, false, "数据格式错误")
|
||||
return
|
||||
}
|
||||
if form.Username == "" {
|
||||
pureJsonMsg(c, false, "请输入用户名")
|
||||
return
|
||||
}
|
||||
if form.Password == "" {
|
||||
pureJsonMsg(c, false, "请输入密码")
|
||||
return
|
||||
}
|
||||
user := a.userService.CheckUser(form.Username, form.Password)
|
||||
if user == nil {
|
||||
logger.Infof("wrong username or password: \"%s\" \"%s\"", form.Username, form.Password)
|
||||
pureJsonMsg(c, false, "用户名或密码错误")
|
||||
return
|
||||
}
|
||||
|
||||
err = session.SetLoginUser(c, user)
|
||||
logger.Info("user", user.Id, "login success")
|
||||
jsonMsg(c, "登录", err)
|
||||
}
|
||||
|
||||
func (a *IndexController) logout(c *gin.Context) {
|
||||
user := session.GetLoginUser(c)
|
||||
if user != nil {
|
||||
logger.Info("user", user.Id, "logout")
|
||||
}
|
||||
session.ClearSession(c)
|
||||
c.Redirect(http.StatusTemporaryRedirect, "")
|
||||
}
|
||||
256
web/controller/server_controller.go
Normal file
256
web/controller/server_controller.go
Normal file
@@ -0,0 +1,256 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/shirou/gopsutil/cpu"
|
||||
"github.com/shirou/gopsutil/disk"
|
||||
"github.com/shirou/gopsutil/host"
|
||||
"github.com/shirou/gopsutil/load"
|
||||
"github.com/shirou/gopsutil/mem"
|
||||
"github.com/shirou/gopsutil/net"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"time"
|
||||
"x-ui/logger"
|
||||
)
|
||||
|
||||
type ProcessState string
|
||||
|
||||
const (
|
||||
Running ProcessState = "running"
|
||||
Stop ProcessState = "stop"
|
||||
Error ProcessState = "error"
|
||||
)
|
||||
|
||||
type Status struct {
|
||||
Cpu float64 `json:"cpu"`
|
||||
Mem struct {
|
||||
Current uint64 `json:"current"`
|
||||
Total uint64 `json:"total"`
|
||||
} `json:"mem"`
|
||||
Swap struct {
|
||||
Current uint64 `json:"current"`
|
||||
Total uint64 `json:"total"`
|
||||
} `json:"swap"`
|
||||
Disk struct {
|
||||
Current uint64 `json:"current"`
|
||||
Total uint64 `json:"total"`
|
||||
} `json:"disk"`
|
||||
Xray struct {
|
||||
State ProcessState `json:"state"`
|
||||
ErrorMsg string `json:"errorMsg"`
|
||||
Version string `json:"version"`
|
||||
} `json:"xray"`
|
||||
Uptime uint64 `json:"uptime"`
|
||||
Loads []float64 `json:"loads"`
|
||||
TcpCount int `json:"tcpCount"`
|
||||
UdpCount int `json:"udpCount"`
|
||||
NetIO struct {
|
||||
Up uint64 `json:"up"`
|
||||
Down uint64 `json:"down"`
|
||||
} `json:"netIO"`
|
||||
NetTraffic struct {
|
||||
Sent uint64 `json:"sent"`
|
||||
Recv uint64 `json:"recv"`
|
||||
} `json:"netTraffic"`
|
||||
}
|
||||
|
||||
type Release struct {
|
||||
TagName string `json:"tag_name"`
|
||||
}
|
||||
|
||||
func stopServerController(a *ServerController) {
|
||||
a.stopTask()
|
||||
}
|
||||
|
||||
type ServerController struct {
|
||||
BaseController
|
||||
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
|
||||
lastStatus *Status
|
||||
lastRefreshTime time.Time
|
||||
lastGetStatusTime time.Time
|
||||
}
|
||||
|
||||
func NewServerController(g *gin.RouterGroup) *ServerController {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
a := &ServerController{
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
lastGetStatusTime: time.Now(),
|
||||
}
|
||||
a.initRouter(g)
|
||||
go a.runTask()
|
||||
runtime.SetFinalizer(a, stopServerController)
|
||||
return a
|
||||
}
|
||||
|
||||
func (a *ServerController) initRouter(g *gin.RouterGroup) {
|
||||
g.POST("/server/status", a.status)
|
||||
g.POST("/server/getXrayVersion", a.getXrayVersion)
|
||||
}
|
||||
|
||||
func (a *ServerController) refreshStatus() {
|
||||
status := &Status{}
|
||||
|
||||
now := time.Now()
|
||||
|
||||
percents, err := cpu.Percent(time.Second*2, false)
|
||||
if err != nil {
|
||||
logger.Warning("get cpu percent failed:", err)
|
||||
} else {
|
||||
status.Cpu = percents[0]
|
||||
}
|
||||
|
||||
upTime, err := host.Uptime()
|
||||
if err != nil {
|
||||
logger.Warning("get uptime failed:", err)
|
||||
} else {
|
||||
status.Uptime = upTime
|
||||
}
|
||||
|
||||
memInfo, err := mem.VirtualMemory()
|
||||
if err != nil {
|
||||
logger.Warning("get virtual memory failed:", err)
|
||||
} else {
|
||||
status.Mem.Current = memInfo.Used
|
||||
status.Mem.Total = memInfo.Total
|
||||
}
|
||||
|
||||
swapInfo, err := mem.SwapMemory()
|
||||
if err != nil {
|
||||
logger.Warning("get swap memory failed:", err)
|
||||
} else {
|
||||
status.Swap.Current = swapInfo.Used
|
||||
status.Swap.Total = swapInfo.Total
|
||||
}
|
||||
|
||||
distInfo, err := disk.Usage("/")
|
||||
if err != nil {
|
||||
logger.Warning("get dist usage failed:", err)
|
||||
} else {
|
||||
status.Disk.Current = distInfo.Used
|
||||
status.Disk.Total = distInfo.Total
|
||||
}
|
||||
|
||||
avgState, err := load.Avg()
|
||||
if err != nil {
|
||||
logger.Warning("get load avg failed:", err)
|
||||
} else {
|
||||
status.Loads = []float64{avgState.Load1, avgState.Load5, avgState.Load15}
|
||||
}
|
||||
|
||||
ioStats, err := net.IOCounters(false)
|
||||
if err != nil {
|
||||
logger.Warning("get io counters failed:", err)
|
||||
} else if len(ioStats) > 0 {
|
||||
ioStat := ioStats[0]
|
||||
status.NetTraffic.Sent = ioStat.BytesSent
|
||||
status.NetTraffic.Recv = ioStat.BytesRecv
|
||||
|
||||
if a.lastStatus != nil {
|
||||
duration := now.Sub(a.lastRefreshTime)
|
||||
seconds := float64(duration) / float64(time.Second)
|
||||
up := uint64(float64(status.NetTraffic.Sent-a.lastStatus.NetTraffic.Sent) / seconds)
|
||||
down := uint64(float64(status.NetTraffic.Recv-a.lastStatus.NetTraffic.Recv) / seconds)
|
||||
status.NetIO.Up = up
|
||||
status.NetIO.Down = down
|
||||
}
|
||||
} else {
|
||||
logger.Warning("can not find io counters")
|
||||
}
|
||||
|
||||
tcpConnStats, err := net.Connections("tcp")
|
||||
if err != nil {
|
||||
logger.Warning("get connections failed:", err)
|
||||
} else {
|
||||
status.TcpCount = len(tcpConnStats)
|
||||
}
|
||||
|
||||
udpConnStats, err := net.Connections("udp")
|
||||
if err != nil {
|
||||
logger.Warning("get connections failed:", err)
|
||||
} else {
|
||||
status.UdpCount = len(udpConnStats)
|
||||
}
|
||||
|
||||
// TODO 临时
|
||||
status.Xray.State = Running
|
||||
status.Xray.ErrorMsg = ""
|
||||
status.Xray.Version = "1.0.0"
|
||||
|
||||
a.lastStatus = status
|
||||
a.lastRefreshTime = now
|
||||
}
|
||||
|
||||
func (a *ServerController) runTask() {
|
||||
for {
|
||||
select {
|
||||
case <-a.ctx.Done():
|
||||
break
|
||||
default:
|
||||
}
|
||||
now := time.Now()
|
||||
if now.Sub(a.lastGetStatusTime) > time.Minute*3 {
|
||||
time.Sleep(time.Second * 2)
|
||||
continue
|
||||
}
|
||||
a.refreshStatus()
|
||||
}
|
||||
}
|
||||
|
||||
func (a *ServerController) stopTask() {
|
||||
a.cancel()
|
||||
}
|
||||
|
||||
func (a *ServerController) status(c *gin.Context) {
|
||||
a.lastGetStatusTime = time.Now()
|
||||
|
||||
jsonMsgObj(c, "", a.lastStatus, nil)
|
||||
}
|
||||
|
||||
var lastVersions []string
|
||||
var lastGetReleaseTime time.Time
|
||||
|
||||
func (a *ServerController) getXrayVersion(c *gin.Context) {
|
||||
now := time.Now()
|
||||
if now.Sub(lastGetReleaseTime) <= time.Minute {
|
||||
jsonMsgObj(c, "", lastVersions, nil)
|
||||
return
|
||||
}
|
||||
url := "https://api.github.com/repos/XTLS/Xray-core/releases"
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
jsonMsg(c, "获取版本失败,请稍后尝试", err)
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
buffer := bytes.NewBuffer(make([]byte, 8192))
|
||||
buffer.Reset()
|
||||
_, err = buffer.ReadFrom(resp.Body)
|
||||
if err != nil {
|
||||
jsonMsg(c, "获取版本失败,请稍后尝试", err)
|
||||
return
|
||||
}
|
||||
|
||||
releases := make([]Release, 0)
|
||||
err = json.Unmarshal(buffer.Bytes(), &releases)
|
||||
if err != nil {
|
||||
jsonMsg(c, "获取版本失败,请向作者反馈此问题", err)
|
||||
return
|
||||
}
|
||||
versions := make([]string, 0, len(releases))
|
||||
for _, release := range releases {
|
||||
versions = append(versions, release.TagName)
|
||||
}
|
||||
lastVersions = versions
|
||||
lastGetReleaseTime = time.Now()
|
||||
|
||||
jsonMsgObj(c, "", versions, nil)
|
||||
}
|
||||
97
web/controller/util.go
Normal file
97
web/controller/util.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"x-ui/config"
|
||||
"x-ui/logger"
|
||||
"x-ui/web/entity"
|
||||
)
|
||||
|
||||
func getUriId(c *gin.Context) int64 {
|
||||
s := struct {
|
||||
Id int64 `uri:"id"`
|
||||
}{}
|
||||
|
||||
_ = c.BindUri(&s)
|
||||
return s.Id
|
||||
}
|
||||
|
||||
func getRemoteIp(c *gin.Context) string {
|
||||
value := c.GetHeader("X-Forwarded-For")
|
||||
if value != "" {
|
||||
ips := strings.Split(value, ",")
|
||||
return ips[0]
|
||||
} else {
|
||||
addr := c.Request.RemoteAddr
|
||||
ip, _, _ := net.SplitHostPort(addr)
|
||||
return ip
|
||||
}
|
||||
}
|
||||
|
||||
func jsonMsg(c *gin.Context, msg string, err error) {
|
||||
jsonMsgObj(c, msg, nil, err)
|
||||
}
|
||||
|
||||
func jsonObj(c *gin.Context, obj interface{}, err error) {
|
||||
jsonMsgObj(c, "", obj, err)
|
||||
}
|
||||
|
||||
func jsonMsgObj(c *gin.Context, msg string, obj interface{}, err error) {
|
||||
m := entity.Msg{
|
||||
Obj: obj,
|
||||
}
|
||||
if err == nil {
|
||||
m.Success = true
|
||||
if msg != "" {
|
||||
m.Msg = msg + "成功"
|
||||
}
|
||||
} else {
|
||||
m.Success = false
|
||||
m.Msg = msg + "失败: " + err.Error()
|
||||
logger.Warning(msg, err)
|
||||
}
|
||||
c.JSON(http.StatusOK, m)
|
||||
}
|
||||
|
||||
func pureJsonMsg(c *gin.Context, success bool, msg string) {
|
||||
if success {
|
||||
c.JSON(http.StatusOK, entity.Msg{
|
||||
Success: true,
|
||||
Msg: msg,
|
||||
})
|
||||
} else {
|
||||
c.JSON(http.StatusOK, entity.Msg{
|
||||
Success: false,
|
||||
Msg: msg,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func html(c *gin.Context, name string, title string, data gin.H) {
|
||||
if data == nil {
|
||||
data = gin.H{}
|
||||
}
|
||||
data["title"] = title
|
||||
data["request_uri"] = c.Request.RequestURI
|
||||
data["base_path"] = config.GetBasePath()
|
||||
c.HTML(http.StatusOK, name, getContext(data))
|
||||
}
|
||||
|
||||
func getContext(h gin.H) gin.H {
|
||||
a := gin.H{
|
||||
"cur_ver": config.GetVersion(),
|
||||
}
|
||||
if h != nil {
|
||||
for key, value := range h {
|
||||
a[key] = value
|
||||
}
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func isAjax(c *gin.Context) bool {
|
||||
return c.GetHeader("X-Requested-With") == "XMLHttpRequest"
|
||||
}
|
||||
31
web/controller/xui_controller.go
Normal file
31
web/controller/xui_controller.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type XUIController struct {
|
||||
BaseController
|
||||
}
|
||||
|
||||
func NewXUIController(g *gin.RouterGroup) *XUIController {
|
||||
a := &XUIController{}
|
||||
a.initRouter(g)
|
||||
return a
|
||||
}
|
||||
|
||||
func (a *XUIController) initRouter(g *gin.RouterGroup) {
|
||||
g = g.Group("/xui")
|
||||
|
||||
g.GET("/", a.index)
|
||||
g.GET("/accounts", a.index)
|
||||
g.GET("/setting", a.setting)
|
||||
}
|
||||
|
||||
func (a *XUIController) index(c *gin.Context) {
|
||||
html(c, "index.html", "系统状态", nil)
|
||||
}
|
||||
|
||||
func (a *XUIController) setting(c *gin.Context) {
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user