2019-12-08 03:59:58 -05:00
|
|
|
package controller
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
2019-12-10 04:57:57 -05:00
|
|
|
"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"
|
|
|
|
"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{
|
2021-01-08 08:04:50 -05:00
|
|
|
"Servers": dao.SortedServerList,
|
2020-12-23 20:54:17 -05:00
|
|
|
"CustomCode": dao.Conf.Site.CustomCode,
|
2019-12-20 10:58:09 -05:00
|
|
|
}
|
|
|
|
u, ok := c.Get(model.CtxKeyAuthorizedUser)
|
|
|
|
if ok {
|
|
|
|
data["Admin"] = u
|
|
|
|
}
|
2020-12-09 06:05:40 -05:00
|
|
|
c.HTML(http.StatusOK, "theme-"+dao.Conf.Site.Theme+"/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()
|
2020-12-19 10:27:59 -05:00
|
|
|
for {
|
|
|
|
dao.ServerLock.RLock()
|
2021-01-08 08:04:50 -05:00
|
|
|
err = conn.WriteJSON(dao.SortedServerList)
|
2020-12-19 10:27:59 -05:00
|
|
|
dao.ServerLock.RUnlock()
|
|
|
|
if err != nil {
|
|
|
|
break
|
2019-12-10 04:57:57 -05:00
|
|
|
}
|
2020-12-19 10:27:59 -05:00
|
|
|
time.Sleep(time.Second * 2)
|
|
|
|
}
|
2019-12-10 04:57:57 -05:00
|
|
|
}
|