u
This commit is contained in:
@@ -1,39 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"live-streamer/streamer"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func GetCurrentVideo(c *gin.Context) {
|
||||
type response struct {
|
||||
Success bool `json:"success"`
|
||||
Data string `json:"data"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
videoPath, err := streamer.GlobalStreamer.GetCurrentVideoPath()
|
||||
if err != nil {
|
||||
c.JSON(http.StatusOK, response{
|
||||
Success: false,
|
||||
Message: err.Error(),
|
||||
})
|
||||
}
|
||||
c.JSON(http.StatusOK, response{
|
||||
Success: true,
|
||||
Data: videoPath,
|
||||
})
|
||||
}
|
||||
|
||||
func GetVideoList(c *gin.Context) {
|
||||
type response struct {
|
||||
Success bool `json:"success"`
|
||||
Data []string `json:"data"`
|
||||
}
|
||||
list := streamer.GlobalStreamer.GetVideoListPath()
|
||||
c.JSON(http.StatusOK, response{
|
||||
Success: true,
|
||||
Data: list,
|
||||
})
|
||||
}
|
||||
117
server/server.go
117
server/server.go
@@ -2,12 +2,16 @@ package server
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"live-streamer/config"
|
||||
mywebsocket "live-streamer/websocket"
|
||||
"log"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
uuid "github.com/gofrs/uuid/v5"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
@@ -20,18 +24,20 @@ var upgrader = websocket.Upgrader{
|
||||
},
|
||||
}
|
||||
|
||||
type InputFunc func(string)
|
||||
type InputFunc func(mywebsocket.Response)
|
||||
|
||||
type Server struct {
|
||||
addr string
|
||||
outputChan chan string
|
||||
dealInputFunc InputFunc
|
||||
clients []*Client
|
||||
clients map[string]*Client
|
||||
historyOutput string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
id string
|
||||
conn *websocket.Conn
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
var GlobalServer *Server
|
||||
@@ -39,22 +45,21 @@ var GlobalServer *Server
|
||||
func NewServer(addr string, dealInputFunc InputFunc) {
|
||||
GlobalServer = &Server{
|
||||
addr: addr,
|
||||
outputChan: make(chan string),
|
||||
dealInputFunc: dealInputFunc,
|
||||
clients: make(map[string]*Client),
|
||||
historyOutput: "",
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) Run() {
|
||||
router := gin.Default()
|
||||
router := gin.New()
|
||||
tpl, err := template.ParseFS(staticFiles, "static/*")
|
||||
if err != nil {
|
||||
log.Fatalf("Error parsing templates: %v", err)
|
||||
}
|
||||
router.SetHTMLTemplate(tpl)
|
||||
|
||||
router.GET("/ws", s.handleWebSocket)
|
||||
router.GET("/video/current", GetCurrentVideo)
|
||||
router.GET("/video/list", GetVideoList)
|
||||
router.GET("/ws", AuthMiddleware(), s.handleWebSocket)
|
||||
router.GET(
|
||||
"/", func(c *gin.Context) {
|
||||
c.HTML(200, "index.html", nil)
|
||||
@@ -66,16 +71,6 @@ func (s *Server) Run() {
|
||||
log.Fatalf("Error starting server: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
for {
|
||||
output := <-s.outputChan
|
||||
s.historyOutput += output
|
||||
for _, client := range s.clients {
|
||||
_ = client.conn.WriteMessage(websocket.TextMessage, []byte(output))
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Server) handleWebSocket(c *gin.Context) {
|
||||
@@ -83,43 +78,89 @@ func (s *Server) handleWebSocket(c *gin.Context) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer ws.Close()
|
||||
client := &Client{conn: ws}
|
||||
s.clients = append(s.clients, client)
|
||||
_ = client.conn.WriteMessage(websocket.TextMessage, []byte(s.historyOutput))
|
||||
|
||||
ws.SetCloseHandler(func(code int, text string) error {
|
||||
return nil
|
||||
})
|
||||
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
log.Printf("generating uuid error: %v", err)
|
||||
return
|
||||
}
|
||||
client := &Client{id: id.String(), conn: ws}
|
||||
s.mu.Lock()
|
||||
s.clients[client.id] = client
|
||||
s.mu.Unlock()
|
||||
// write history output
|
||||
s.Single(client.id, mywebsocket.MakeOutput(s.historyOutput))
|
||||
|
||||
defer func() {
|
||||
for i, c := range s.clients {
|
||||
if c == client {
|
||||
s.clients = append(s.clients[:i], s.clients[i+1:]...)
|
||||
break
|
||||
}
|
||||
client.mu.Lock()
|
||||
ws.Close()
|
||||
client.mu.Unlock()
|
||||
s.mu.Lock()
|
||||
delete(s.clients, client.id)
|
||||
s.mu.Unlock()
|
||||
if r := recover(); r != nil {
|
||||
log.Printf("webSocket handler panic: %v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
// recive message
|
||||
_, msg, err := ws.ReadMessage()
|
||||
client.mu.Lock()
|
||||
msg := mywebsocket.Response{}
|
||||
err := ws.ReadJSON(&msg)
|
||||
client.mu.Unlock()
|
||||
if err != nil {
|
||||
log.Printf("Websocket reading message error: %v", err)
|
||||
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
|
||||
log.Printf("websocket error: %v", err)
|
||||
}
|
||||
break
|
||||
}
|
||||
s.dealInputFunc(string(msg))
|
||||
s.dealInputFunc(msg)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) Print(msg ...any) {
|
||||
s.outputChan <- fmt.Sprint(msg...)
|
||||
func AuthMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if config.GlobalConfig.Auth.Token == "" ||
|
||||
c.Query("token") == config.GlobalConfig.Auth.Token {
|
||||
c.Next()
|
||||
} else {
|
||||
c.AbortWithStatus(http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) Println(msg ...any) {
|
||||
s.outputChan <- fmt.Sprintln(msg...)
|
||||
func (s *Server) Broadcast(obj mywebsocket.Response) {
|
||||
s.mu.Lock()
|
||||
if obj.Type == mywebsocket.TypeOutput {
|
||||
s.historyOutput += obj.Data.(string)
|
||||
}
|
||||
for _, client := range s.clients {
|
||||
obj.UserID = client.id
|
||||
obj.Timestamp = time.Now().UnixMilli()
|
||||
if err := client.conn.WriteJSON(obj); err != nil {
|
||||
log.Printf("websocket writing message error: %v", err)
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Server) Printf(format string, args ...interface{}) {
|
||||
s.outputChan <- fmt.Sprintf(format, args...)
|
||||
func (s *Server) Single(userID string, obj mywebsocket.Response) {
|
||||
s.mu.Lock()
|
||||
if client, ok := s.clients[userID]; ok {
|
||||
obj.UserID = userID
|
||||
obj.Timestamp = time.Now().UnixMilli()
|
||||
if err := client.conn.WriteJSON(obj); err != nil {
|
||||
log.Printf("websocket writing message error: %v", err)
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Server) Close() {
|
||||
close(s.outputChan)
|
||||
|
||||
}
|
||||
|
||||
@@ -25,6 +25,59 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#token-screen {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: linear-gradient(135deg, #6e8efb, #4a6cf7);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.token-container {
|
||||
background: white;
|
||||
padding: 30px;
|
||||
border-radius: 15px;
|
||||
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
|
||||
width: 90%;
|
||||
max-width: 400px;
|
||||
}
|
||||
|
||||
.token-container h2 {
|
||||
margin-bottom: 20px;
|
||||
color: #333;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.token-input-group {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.token-input-group input {
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
border: 2px solid #e0e0e0;
|
||||
border-radius: 8px;
|
||||
font-size: 16px;
|
||||
transition: border-color 0.3s ease;
|
||||
}
|
||||
|
||||
.token-input-group input:focus {
|
||||
border-color: #4a6cf7;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
#token-error {
|
||||
color: #dc3545;
|
||||
font-size: 14px;
|
||||
margin-top: 10px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.container-fluid {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
@@ -255,6 +308,24 @@
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div id="token-screen">
|
||||
<div class="token-container">
|
||||
<h2><i class="fas fa-lock me-2"></i>访问验证</h2>
|
||||
<div class="token-input-group">
|
||||
<input
|
||||
type="password"
|
||||
id="token-input"
|
||||
placeholder="请输入访问令牌"
|
||||
class="form-control"
|
||||
/>
|
||||
</div>
|
||||
<button class="btn btn-primary w-100" onclick="validateToken()">
|
||||
<i class="fas fa-sign-in-alt me-2"></i>验证并进入
|
||||
</button>
|
||||
<div id="token-error">访问令牌无效,请重试</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="container-fluid">
|
||||
<div class="header">
|
||||
<h2><i class="fas fa-video me-2"></i>Live Streamer</h2>
|
||||
@@ -295,78 +366,131 @@
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script>
|
||||
const ws = new WebSocket("ws://localhost:8080/ws");
|
||||
const statusDisplay = document.getElementById("status");
|
||||
const currentVideo = document.getElementById("current-video");
|
||||
const videoList = document.getElementById("video-list");
|
||||
let ws;
|
||||
let userID;
|
||||
|
||||
function validateToken() {
|
||||
const token = document.getElementById("token-input").value;
|
||||
|
||||
const wsProtocol =
|
||||
window.location.protocol === "https:" ? "wss:" : "ws:";
|
||||
const wsHost = window.location.host;
|
||||
|
||||
ws = new WebSocket(`${wsProtocol}//${wsHost}/ws?token=${token}`);
|
||||
|
||||
const statusDisplay = document.getElementById("status");
|
||||
const currentVideo = document.getElementById("current-video");
|
||||
const videoList = document.getElementById("video-list");
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
if (ws.readyState !== WebSocket.OPEN) {
|
||||
ws.close();
|
||||
document.getElementById("token-error").style.display = "block";
|
||||
}
|
||||
}, 3000);
|
||||
|
||||
ws.onopen = function () {
|
||||
console.log("Connected to WebSocket");
|
||||
|
||||
clearTimeout(timeout);
|
||||
document.getElementById("token-screen").style.display = "none";
|
||||
document.querySelector(".container-fluid").style.display = "flex";
|
||||
|
||||
statusDisplay.textContent = "WebSocket Status: Connected";
|
||||
statusDisplay.classList.add("connected");
|
||||
};
|
||||
|
||||
ws.onerror = function () {
|
||||
clearTimeout(timeout);
|
||||
document.getElementById("token-error").style.display = "block";
|
||||
};
|
||||
|
||||
ws.onmessage = function (evt) {
|
||||
let obj = JSON.parse(evt.data);
|
||||
if (!userID) {
|
||||
userID = obj.user_id;
|
||||
updateVideoList();
|
||||
updateCurrentVideo();
|
||||
}
|
||||
switch (obj.type) {
|
||||
case "Output":
|
||||
addToOutput(obj.data);
|
||||
break;
|
||||
case "GetCurrentVideoPath":
|
||||
document.querySelector("#current-video>span").innerHTML =
|
||||
obj.data;
|
||||
break;
|
||||
case "GetVideoList":
|
||||
if (obj.success) {
|
||||
const listContainer = document.querySelector(
|
||||
"#video-list-container .list-group"
|
||||
);
|
||||
listContainer.innerHTML = "";
|
||||
if (obj.success) {
|
||||
for (let item of obj.data) {
|
||||
listContainer.innerHTML += `<li class="list-group-item"><i class="fas fa-file-video me-2"></i>${item}</li>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "RemoveVideo":
|
||||
case "AddVideo":
|
||||
updateVideoList();
|
||||
updateCurrentVideo();
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
ws.onclose = function () {
|
||||
console.log("Disconnected from WebSocket");
|
||||
statusDisplay.textContent = "WebSocket Status: Disconnected";
|
||||
statusDisplay.classList.remove("connected");
|
||||
};
|
||||
}
|
||||
|
||||
const messagesArea = document.getElementById("messages");
|
||||
|
||||
ws.onopen = function () {
|
||||
statusDisplay.textContent = "WebSocket Status: Connected";
|
||||
statusDisplay.classList.add("connected");
|
||||
};
|
||||
|
||||
ws.onmessage = function (evt) {
|
||||
appendMessage(evt.data);
|
||||
};
|
||||
|
||||
ws.onclose = function () {
|
||||
statusDisplay.textContent = "WebSocket Status: Disconnected";
|
||||
statusDisplay.classList.remove("connected");
|
||||
};
|
||||
|
||||
function appendMessage(message) {
|
||||
function addToOutput(message) {
|
||||
const timestamp = new Date().toLocaleTimeString();
|
||||
messagesArea.value += `[${timestamp}] ${message}\n`;
|
||||
messagesArea.scrollTop = messagesArea.scrollHeight;
|
||||
}
|
||||
|
||||
function sendWs(type, args) {
|
||||
if (args) {
|
||||
ws.send(
|
||||
`{ "Type": "${type}", "Args": ${JSON.stringify(
|
||||
args
|
||||
)}, "user_id": "${userID}", "timestamp": ${Date.now()} }`
|
||||
);
|
||||
} else {
|
||||
ws.send(
|
||||
`{ "Type": "${type}", "user_id": "${userID}", "timestamp": ${Date.now()} }`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function updateCurrentVideo() {
|
||||
fetch("/video/current")
|
||||
.then((response) => response.json())
|
||||
.then((data) => {
|
||||
if (data.success) {
|
||||
document.querySelector("#current-video>span").innerHTML =
|
||||
data.data;
|
||||
}
|
||||
});
|
||||
sendWs("GetCurrentVideoPath");
|
||||
}
|
||||
|
||||
function updateVideoList() {
|
||||
fetch("/video/list")
|
||||
.then((response) => response.json())
|
||||
.then((data) => {
|
||||
const listContainer = document.querySelector(
|
||||
"#video-list-container .list-group"
|
||||
);
|
||||
listContainer.innerHTML = "";
|
||||
if (data.success) {
|
||||
for (let item of data.data) {
|
||||
listContainer.innerHTML += `<li class="list-group-item">
|
||||
<i class="fas fa-file-video me-2"></i>${item}</li>`;
|
||||
}
|
||||
}
|
||||
});
|
||||
sendWs("GetVideoList");
|
||||
}
|
||||
|
||||
updateCurrentVideo();
|
||||
updateVideoList();
|
||||
setInterval(updateCurrentVideo, 5000);
|
||||
setInterval(updateVideoList, 5000);
|
||||
window.previousVideo = function () {
|
||||
sendWs("StreamPrevVideo");
|
||||
};
|
||||
|
||||
function previousVideo() {
|
||||
ws.send("prev");
|
||||
}
|
||||
window.nextVideo = function () {
|
||||
sendWs("StreamNextVideo");
|
||||
};
|
||||
|
||||
function nextVideo() {
|
||||
ws.send("next");
|
||||
}
|
||||
|
||||
function closeConnection() {
|
||||
window.closeConnection = function () {
|
||||
if (confirm("确定要关闭服务器吗?")) {
|
||||
ws.send("quit");
|
||||
sendWs("Quit");
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user