u
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"embed"
|
||||
"html/template"
|
||||
"live-streamer/config"
|
||||
"live-streamer/streamer"
|
||||
mywebsocket "live-streamer/websocket"
|
||||
"log"
|
||||
"net/http"
|
||||
@@ -24,20 +25,20 @@ var upgrader = websocket.Upgrader{
|
||||
},
|
||||
}
|
||||
|
||||
type InputFunc func(mywebsocket.Response)
|
||||
type InputFunc func(mywebsocket.RequestType)
|
||||
|
||||
type Server struct {
|
||||
addr string
|
||||
dealInputFunc InputFunc
|
||||
clients map[string]*Client
|
||||
historyOutput string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
id string
|
||||
conn *websocket.Conn
|
||||
mu sync.Mutex
|
||||
id string
|
||||
conn *websocket.Conn
|
||||
mu sync.Mutex
|
||||
hasSentSize int
|
||||
}
|
||||
|
||||
var GlobalServer *Server
|
||||
@@ -47,7 +48,6 @@ func NewServer(addr string, dealInputFunc InputFunc) {
|
||||
addr: addr,
|
||||
dealInputFunc: dealInputFunc,
|
||||
clients: make(map[string]*Client),
|
||||
historyOutput: "",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,12 +88,10 @@ func (s *Server) handleWebSocket(c *gin.Context) {
|
||||
log.Printf("generating uuid error: %v", err)
|
||||
return
|
||||
}
|
||||
client := &Client{id: id.String(), conn: ws}
|
||||
client := &Client{id: id.String(), conn: ws, hasSentSize: 0}
|
||||
s.mu.Lock()
|
||||
s.clients[client.id] = client
|
||||
s.mu.Unlock()
|
||||
// write history output
|
||||
s.Single(client.id, mywebsocket.MakeOutput(s.historyOutput))
|
||||
|
||||
defer func() {
|
||||
client.mu.Lock()
|
||||
@@ -107,10 +105,24 @@ func (s *Server) handleWebSocket(c *gin.Context) {
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(1 * time.Second)
|
||||
for range ticker.C {
|
||||
streamer.GlobalStreamer.TruncateOutput()
|
||||
currentVideoPath, _ := streamer.GlobalStreamer.GetCurrentVideoPath()
|
||||
s.Broadcast(mywebsocket.Date{
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
CurrentVideoPath: currentVideoPath,
|
||||
VideoList: streamer.GlobalStreamer.GetVideoListPath(),
|
||||
Output: streamer.GlobalStreamer.GetOutput(),
|
||||
})
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
// recive message
|
||||
client.mu.Lock()
|
||||
msg := mywebsocket.Response{}
|
||||
msg := mywebsocket.Request{}
|
||||
err := ws.ReadJSON(&msg)
|
||||
client.mu.Unlock()
|
||||
if err != nil {
|
||||
@@ -119,7 +131,7 @@ func (s *Server) handleWebSocket(c *gin.Context) {
|
||||
}
|
||||
break
|
||||
}
|
||||
s.dealInputFunc(msg)
|
||||
s.dealInputFunc(msg.Type)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,13 +146,9 @@ func AuthMiddleware() gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) Broadcast(obj mywebsocket.Response) {
|
||||
func (s *Server) Broadcast(obj mywebsocket.Date) {
|
||||
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)
|
||||
@@ -149,10 +157,9 @@ func (s *Server) Broadcast(obj mywebsocket.Response) {
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Server) Single(userID string, obj mywebsocket.Response) {
|
||||
func (s *Server) Single(userID string, obj mywebsocket.Date) {
|
||||
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)
|
||||
|
||||
@@ -367,117 +367,63 @@
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script>
|
||||
let ws;
|
||||
let userID;
|
||||
|
||||
function validateToken() {
|
||||
function connectWebSocket() {
|
||||
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";
|
||||
document.getElementById("status").textContent =
|
||||
"WebSocket Status: Connected";
|
||||
document.getElementById("status").classList.add("connected");
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
messagesArea.value = obj.output;
|
||||
messagesArea.scrollTop = messagesArea.scrollHeight;
|
||||
document.querySelector("#current-video>span").innerHTML =
|
||||
obj.currentVideoPath;
|
||||
const listContainer = document.querySelector(
|
||||
"#video-list-container .list-group"
|
||||
);
|
||||
listContainer.innerHTML = "";
|
||||
obj.videoList.forEach((item) => {
|
||||
listContainer.innerHTML += `<li class="list-group-item"><i class="fas fa-file-video me-2"></i>${item}</li>`;
|
||||
});
|
||||
};
|
||||
|
||||
ws.onerror = function () {
|
||||
document.getElementById("token-error").style.display = "block";
|
||||
};
|
||||
|
||||
ws.onclose = function () {
|
||||
console.log("Disconnected from WebSocket");
|
||||
statusDisplay.textContent = "WebSocket Status: Disconnected";
|
||||
statusDisplay.classList.remove("connected");
|
||||
document.getElementById("status").textContent =
|
||||
"WebSocket Status: Disconnected";
|
||||
document.getElementById("status").classList.remove("connected");
|
||||
setTimeout(connectWebSocket, 3000);
|
||||
};
|
||||
}
|
||||
|
||||
function validateToken() {
|
||||
connectWebSocket();
|
||||
}
|
||||
|
||||
const messagesArea = document.getElementById("messages");
|
||||
|
||||
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 sendWs(type) {
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(`{ "type": "${type}" }`);
|
||||
}
|
||||
}
|
||||
|
||||
function updateCurrentVideo() {
|
||||
sendWs("GetCurrentVideoPath");
|
||||
}
|
||||
|
||||
function updateVideoList() {
|
||||
sendWs("GetVideoList");
|
||||
}
|
||||
|
||||
window.previousVideo = function () {
|
||||
sendWs("StreamPrevVideo");
|
||||
};
|
||||
@@ -489,6 +435,9 @@
|
||||
window.closeConnection = function () {
|
||||
if (confirm("确定要关闭服务器吗?")) {
|
||||
sendWs("Quit");
|
||||
if (ws) {
|
||||
ws.close();
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
Reference in New Issue
Block a user