2019-12-08 03:59:58 -05:00
|
|
|
package controller
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
2019-12-10 04:57:57 -05:00
|
|
|
"sync"
|
|
|
|
"time"
|
2019-12-08 03:59:58 -05:00
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
2019-12-10 04:57:57 -05:00
|
|
|
"github.com/gorilla/websocket"
|
2019-12-08 03:59:58 -05:00
|
|
|
|
2020-11-10 21:07:45 -05:00
|
|
|
"github.com/naiba/nezha/model"
|
|
|
|
"github.com/naiba/nezha/pkg/mygin"
|
|
|
|
pb "github.com/naiba/nezha/proto"
|
|
|
|
"github.com/naiba/nezha/service/dao"
|
2019-12-08 03:59:58 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
type commonPage struct {
|
|
|
|
r *gin.Engine
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cp *commonPage) serve() {
|
|
|
|
cr := cp.r.Group("")
|
|
|
|
cr.Use(mygin.Authorize(mygin.AuthorizeOption{}))
|
|
|
|
cr.GET("/", cp.home)
|
2019-12-10 04:57:57 -05:00
|
|
|
cr.GET("/ws", cp.ws)
|
2019-12-08 03:59:58 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cp *commonPage) home(c *gin.Context) {
|
2019-12-09 05:14:31 -05:00
|
|
|
dao.ServerLock.RLock()
|
|
|
|
defer dao.ServerLock.RUnlock()
|
2019-12-20 10:58:09 -05:00
|
|
|
data := gin.H{
|
2019-12-09 05:14:31 -05:00
|
|
|
"Servers": dao.ServerList,
|
2019-12-20 10:58:09 -05:00
|
|
|
}
|
|
|
|
u, ok := c.Get(model.CtxKeyAuthorizedUser)
|
|
|
|
if ok {
|
|
|
|
data["Admin"] = u
|
|
|
|
}
|
|
|
|
c.HTML(http.StatusOK, "page/home", mygin.CommonEnvironment(c, data))
|
2019-12-08 03:59:58 -05:00
|
|
|
}
|
2019-12-10 04:57:57 -05:00
|
|
|
|
|
|
|
var upgrader = websocket.Upgrader{}
|
|
|
|
|
|
|
|
func (cp *commonPage) ws(c *gin.Context) {
|
|
|
|
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
|
|
|
|
if err != nil {
|
|
|
|
mygin.ShowErrorPage(c, mygin.ErrInfo{
|
|
|
|
Code: http.StatusInternalServerError,
|
|
|
|
Title: "网络错误",
|
|
|
|
Msg: "Websocket协议切换失败",
|
|
|
|
Link: "/",
|
|
|
|
Btn: "返回首页",
|
|
|
|
}, true)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer conn.Close()
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
wg.Add(2)
|
|
|
|
go func() {
|
|
|
|
var mt int
|
|
|
|
var message []byte
|
|
|
|
for {
|
|
|
|
mt, message, err = conn.ReadMessage()
|
|
|
|
if err != nil {
|
|
|
|
wg.Done()
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if mt == websocket.TextMessage && string(message) == "track" {
|
|
|
|
dao.SendCommand(&pb.Command{
|
|
|
|
Type: model.MTReportState,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
dao.ServerLock.RLock()
|
|
|
|
err = conn.WriteJSON(dao.ServerList)
|
|
|
|
dao.ServerLock.RUnlock()
|
|
|
|
if err != nil {
|
|
|
|
wg.Done()
|
|
|
|
break
|
|
|
|
}
|
|
|
|
time.Sleep(time.Second * 2)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
wg.Wait()
|
|
|
|
}
|