This commit is contained in:
Nite07 2024-10-24 05:06:19 +08:00
parent 35db859788
commit 020f2eea9b
7 changed files with 218 additions and 272 deletions

33
main.go
View File

@ -1,32 +1,55 @@
package main package main
import ( import (
"bufio"
"fmt"
"live-streamer/config" "live-streamer/config"
"live-streamer/server" "live-streamer/server"
"live-streamer/streamer" "live-streamer/streamer"
"live-streamer/utils" "live-streamer/utils"
"live-streamer/websocket"
"log" "log"
"os"
"github.com/fsnotify/fsnotify" "github.com/fsnotify/fsnotify"
) )
var GlobalStreamer *streamer.Streamer var GlobalStreamer *streamer.Streamer
var outputer websocket.Outputer
func main() { func main() {
server.NewServer(":8080", websocketRequestHandler) server.NewServer(":8080", websocketRequestHandler)
server.GlobalServer.Run() server.GlobalServer.Run()
outputer = server.GlobalServer
if !utils.HasFFMPEG() { if !utils.HasFFMPEG() {
log.Fatal("ffmpeg not found") log.Fatal("ffmpeg not found")
} }
GlobalStreamer = streamer.NewStreamer(config.GlobalConfig.VideoList, outputer) GlobalStreamer = streamer.NewStreamer(config.GlobalConfig.VideoList)
go startWatcher() go startWatcher()
go input()
GlobalStreamer.Stream() GlobalStreamer.Stream()
GlobalStreamer.Close() GlobalStreamer.Close()
} }
func input() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text() // 获取用户输入的内容
switch line {
case "list":
fmt.Println(GlobalStreamer.GetVideoListPath())
case "index":
fmt.Println(GlobalStreamer.GetCurrentIndex())
case "next":
GlobalStreamer.Next()
case "prev":
GlobalStreamer.Prev()
case "quit":
GlobalStreamer.Close()
os.Exit(0)
case "current":
fmt.Println(GlobalStreamer.GetCurrentVideoPath())
}
}
}
func startWatcher() { func startWatcher() {
watcher, err := fsnotify.NewWatcher() watcher, err := fsnotify.NewWatcher()
if err != nil { if err != nil {
@ -56,11 +79,9 @@ func startWatcher() {
if utils.IsSupportedVideo(event.Name) { if utils.IsSupportedVideo(event.Name) {
log.Println("new video added:", event.Name) log.Println("new video added:", event.Name)
GlobalStreamer.Add(event.Name) GlobalStreamer.Add(event.Name)
server.GlobalServer.Broadcast(websocket.MakeResponse(websocket.TypeAddVideo, true, event.Name, ""))
} }
} }
if event.Op&fsnotify.Remove == fsnotify.Remove { if event.Op&fsnotify.Remove == fsnotify.Remove {
server.GlobalServer.Broadcast(websocket.MakeResponse(websocket.TypeRemoveVideo, true, event.Name, ""))
log.Println("video removed:", event.Name) log.Println("video removed:", event.Name)
GlobalStreamer.Remove(event.Name) GlobalStreamer.Remove(event.Name)
} }

View File

@ -4,6 +4,7 @@ import (
"embed" "embed"
"html/template" "html/template"
"live-streamer/config" "live-streamer/config"
"live-streamer/streamer"
mywebsocket "live-streamer/websocket" mywebsocket "live-streamer/websocket"
"log" "log"
"net/http" "net/http"
@ -24,20 +25,20 @@ var upgrader = websocket.Upgrader{
}, },
} }
type InputFunc func(mywebsocket.Response) type InputFunc func(mywebsocket.RequestType)
type Server struct { type Server struct {
addr string addr string
dealInputFunc InputFunc dealInputFunc InputFunc
clients map[string]*Client clients map[string]*Client
historyOutput string
mu sync.Mutex mu sync.Mutex
} }
type Client struct { type Client struct {
id string id string
conn *websocket.Conn conn *websocket.Conn
mu sync.Mutex mu sync.Mutex
hasSentSize int
} }
var GlobalServer *Server var GlobalServer *Server
@ -47,7 +48,6 @@ func NewServer(addr string, dealInputFunc InputFunc) {
addr: addr, addr: addr,
dealInputFunc: dealInputFunc, dealInputFunc: dealInputFunc,
clients: make(map[string]*Client), clients: make(map[string]*Client),
historyOutput: "",
} }
} }
@ -88,12 +88,10 @@ func (s *Server) handleWebSocket(c *gin.Context) {
log.Printf("generating uuid error: %v", err) log.Printf("generating uuid error: %v", err)
return return
} }
client := &Client{id: id.String(), conn: ws} client := &Client{id: id.String(), conn: ws, hasSentSize: 0}
s.mu.Lock() s.mu.Lock()
s.clients[client.id] = client s.clients[client.id] = client
s.mu.Unlock() s.mu.Unlock()
// write history output
s.Single(client.id, mywebsocket.MakeOutput(s.historyOutput))
defer func() { defer func() {
client.mu.Lock() 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 { for {
// recive message // recive message
client.mu.Lock() client.mu.Lock()
msg := mywebsocket.Response{} msg := mywebsocket.Request{}
err := ws.ReadJSON(&msg) err := ws.ReadJSON(&msg)
client.mu.Unlock() client.mu.Unlock()
if err != nil { if err != nil {
@ -119,7 +131,7 @@ func (s *Server) handleWebSocket(c *gin.Context) {
} }
break 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() s.mu.Lock()
if obj.Type == mywebsocket.TypeOutput {
s.historyOutput += obj.Data.(string)
}
for _, client := range s.clients { for _, client := range s.clients {
obj.UserID = client.id
obj.Timestamp = time.Now().UnixMilli() obj.Timestamp = time.Now().UnixMilli()
if err := client.conn.WriteJSON(obj); err != nil { if err := client.conn.WriteJSON(obj); err != nil {
log.Printf("websocket writing message error: %v", err) log.Printf("websocket writing message error: %v", err)
@ -149,10 +157,9 @@ func (s *Server) Broadcast(obj mywebsocket.Response) {
s.mu.Unlock() s.mu.Unlock()
} }
func (s *Server) Single(userID string, obj mywebsocket.Response) { func (s *Server) Single(userID string, obj mywebsocket.Date) {
s.mu.Lock() s.mu.Lock()
if client, ok := s.clients[userID]; ok { if client, ok := s.clients[userID]; ok {
obj.UserID = userID
obj.Timestamp = time.Now().UnixMilli() obj.Timestamp = time.Now().UnixMilli()
if err := client.conn.WriteJSON(obj); err != nil { if err := client.conn.WriteJSON(obj); err != nil {
log.Printf("websocket writing message error: %v", err) log.Printf("websocket writing message error: %v", err)

View File

@ -367,117 +367,63 @@
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script> <script>
let ws; let ws;
let userID;
function validateToken() { function connectWebSocket() {
const token = document.getElementById("token-input").value; const token = document.getElementById("token-input").value;
const wsProtocol = const wsProtocol =
window.location.protocol === "https:" ? "wss:" : "ws:"; window.location.protocol === "https:" ? "wss:" : "ws:";
const wsHost = window.location.host; const wsHost = window.location.host;
ws = new WebSocket(`${wsProtocol}//${wsHost}/ws?token=${token}`); 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 () { ws.onopen = function () {
console.log("Connected to WebSocket"); console.log("Connected to WebSocket");
clearTimeout(timeout);
document.getElementById("token-screen").style.display = "none"; document.getElementById("token-screen").style.display = "none";
document.querySelector(".container-fluid").style.display = "flex"; document.querySelector(".container-fluid").style.display = "flex";
document.getElementById("status").textContent =
statusDisplay.textContent = "WebSocket Status: Connected"; "WebSocket Status: Connected";
statusDisplay.classList.add("connected"); document.getElementById("status").classList.add("connected");
};
ws.onerror = function () {
clearTimeout(timeout);
document.getElementById("token-error").style.display = "block";
}; };
ws.onmessage = function (evt) { ws.onmessage = function (evt) {
let obj = JSON.parse(evt.data); let obj = JSON.parse(evt.data);
if (!userID) { messagesArea.value = obj.output;
userID = obj.user_id; messagesArea.scrollTop = messagesArea.scrollHeight;
updateVideoList(); document.querySelector("#current-video>span").innerHTML =
updateCurrentVideo(); obj.currentVideoPath;
} const listContainer = document.querySelector(
switch (obj.type) { "#video-list-container .list-group"
case "Output": );
addToOutput(obj.data); listContainer.innerHTML = "";
break; obj.videoList.forEach((item) => {
case "GetCurrentVideoPath": listContainer.innerHTML += `<li class="list-group-item"><i class="fas fa-file-video me-2"></i>${item}</li>`;
document.querySelector("#current-video>span").innerHTML = });
obj.data; };
break;
case "GetVideoList": ws.onerror = function () {
if (obj.success) { document.getElementById("token-error").style.display = "block";
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 () { ws.onclose = function () {
console.log("Disconnected from WebSocket"); console.log("Disconnected from WebSocket");
statusDisplay.textContent = "WebSocket Status: Disconnected"; document.getElementById("status").textContent =
statusDisplay.classList.remove("connected"); "WebSocket Status: Disconnected";
document.getElementById("status").classList.remove("connected");
setTimeout(connectWebSocket, 3000);
}; };
} }
function validateToken() {
connectWebSocket();
}
const messagesArea = document.getElementById("messages"); const messagesArea = document.getElementById("messages");
function addToOutput(message) { function sendWs(type) {
const timestamp = new Date().toLocaleTimeString(); if (ws && ws.readyState === WebSocket.OPEN) {
messagesArea.value += `[${timestamp}] ${message}\n`; ws.send(`{ "type": "${type}" }`);
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() {
sendWs("GetCurrentVideoPath");
}
function updateVideoList() {
sendWs("GetVideoList");
}
window.previousVideo = function () { window.previousVideo = function () {
sendWs("StreamPrevVideo"); sendWs("StreamPrevVideo");
}; };
@ -489,6 +435,9 @@
window.closeConnection = function () { window.closeConnection = function () {
if (confirm("确定要关闭服务器吗?")) { if (confirm("确定要关闭服务器吗?")) {
sendWs("Quit"); sendWs("Quit");
if (ws) {
ws.close();
}
} }
}; };
</script> </script>

View File

@ -7,8 +7,8 @@ import (
"fmt" "fmt"
"io" "io"
"live-streamer/config" "live-streamer/config"
"live-streamer/websocket"
"log" "log"
"math"
"os/exec" "os/exec"
"strings" "strings"
"sync" "sync"
@ -21,23 +21,60 @@ type Streamer struct {
cmd *exec.Cmd cmd *exec.Cmd
ctx context.Context ctx context.Context
cancel context.CancelFunc cancel context.CancelFunc
output strings.Builder
manualControl bool
mu sync.Mutex mu sync.Mutex
outputer websocket.Outputer
} }
var GlobalStreamer *Streamer var GlobalStreamer *Streamer
func NewStreamer(videoList []config.InputItem, outputer websocket.Outputer) *Streamer { func NewStreamer(videoList []config.InputItem) *Streamer {
GlobalStreamer = &Streamer{ GlobalStreamer = &Streamer{
videoList: videoList, videoList: videoList,
currentVideoIndex: 0, currentVideoIndex: 0,
cmd: nil, cmd: nil,
ctx: nil, ctx: nil,
outputer: outputer,
} }
return GlobalStreamer return GlobalStreamer
} }
func (s *Streamer) start() {
s.mu.Lock()
s.ctx, s.cancel = context.WithCancel(context.Background())
currentVideo := s.videoList[s.currentVideoIndex]
videoPath := currentVideo.Path
s.cmd = exec.CommandContext(s.ctx, "ffmpeg", s.buildFFmpegArgs(currentVideo)...)
s.mu.Unlock()
s.writeOutput(fmt.Sprintln("start stream: ", videoPath))
pipe, err := s.cmd.StderrPipe()
if err != nil {
log.Printf("failed to get pipe: %v", err)
return
}
reader := bufio.NewReader(pipe)
if err := s.cmd.Start(); err != nil {
s.writeOutput(fmt.Sprintf("starting ffmpeg error: %v\n", err))
return
}
go s.log(reader)
<-s.ctx.Done()
s.writeOutput(fmt.Sprintf("stop stream: %s\n", videoPath))
if s.manualControl {
s.manualControl = false
} else {
// stream next video
s.currentVideoIndex++
if s.currentVideoIndex >= len(s.videoList) {
s.currentVideoIndex = 0
}
}
}
func (s *Streamer) Stream() { func (s *Streamer) Stream() {
for { for {
if len(s.videoList) == 0 { if len(s.videoList) == 0 {
@ -48,52 +85,17 @@ func (s *Streamer) Stream() {
} }
} }
func (s *Streamer) start() {
s.Stop()
s.ctx, s.cancel = context.WithCancel(context.Background())
currentVideo := s.videoList[s.currentVideoIndex]
videoPath := currentVideo.Path
s.outputer.Broadcast(websocket.MakeOutput(fmt.Sprint("start stream: ", videoPath)))
s.mu.Lock()
s.cmd = exec.CommandContext(s.ctx, "ffmpeg", s.buildFFmpegArgs(currentVideo)...)
s.mu.Unlock()
pipe, err := s.cmd.StderrPipe()
if err != nil {
log.Printf("failed to get pipe: %v", err)
return
}
reader := bufio.NewReader(pipe)
if err := s.cmd.Start(); err != nil {
s.outputer.Broadcast(websocket.MakeOutput(fmt.Sprintf("starting ffmpeg error: %v\n", err)))
return
}
go s.log(reader)
<-s.ctx.Done()
s.outputer.Broadcast(websocket.MakeOutput(fmt.Sprintf("stop stream: %s", videoPath)))
// stream next video
s.currentVideoIndex++
if s.currentVideoIndex >= len(s.videoList) {
s.currentVideoIndex = 0
}
}
func (s *Streamer) Stop() { func (s *Streamer) Stop() {
s.mu.Lock()
defer s.mu.Unlock()
if s.cancel != nil { if s.cancel != nil {
stopped := make(chan error) stopped := make(chan error)
go func() { go func() {
stopped <- s.cmd.Wait() if s.cmd != nil {
stopped <- s.cmd.Wait()
}
}() }()
s.cancel() s.cancel()
s.mu.Lock()
if s.cmd != nil && s.cmd.Process != nil { if s.cmd != nil && s.cmd.Process != nil {
select { select {
case <-stopped: case <-stopped:
@ -104,15 +106,24 @@ func (s *Streamer) Stop() {
} }
s.cmd = nil s.cmd = nil
} }
s.mu.Unlock()
} }
} }
func (s *Streamer) writeOutput(str string) {
s.mu.Lock()
defer s.mu.Unlock()
s.output.WriteString(str)
}
func (s *Streamer) Add(videoPath string) { func (s *Streamer) Add(videoPath string) {
s.mu.Lock()
defer s.mu.Unlock()
s.videoList = append(s.videoList, config.InputItem{Path: videoPath}) s.videoList = append(s.videoList, config.InputItem{Path: videoPath})
} }
func (s *Streamer) Remove(videoPath string) { func (s *Streamer) Remove(videoPath string) {
s.mu.Lock()
defer s.mu.Unlock()
for i, item := range s.videoList { for i, item := range s.videoList {
if item.Path == videoPath { if item.Path == videoPath {
s.videoList = append(s.videoList[:i], s.videoList[i+1:]...) s.videoList = append(s.videoList[:i], s.videoList[i+1:]...)
@ -128,18 +139,24 @@ func (s *Streamer) Remove(videoPath string) {
} }
func (s *Streamer) Prev() { func (s *Streamer) Prev() {
s.mu.Lock()
s.manualControl = true
s.currentVideoIndex-- s.currentVideoIndex--
if s.currentVideoIndex < 0 { if s.currentVideoIndex < 0 {
s.currentVideoIndex = len(s.videoList) - 1 s.currentVideoIndex = len(s.videoList) - 1
} }
s.mu.Unlock()
s.Stop() s.Stop()
} }
func (s *Streamer) Next() { func (s *Streamer) Next() {
s.mu.Lock()
s.manualControl = true
s.currentVideoIndex++ s.currentVideoIndex++
if s.currentVideoIndex >= len(s.videoList) { if s.currentVideoIndex >= len(s.videoList) {
s.currentVideoIndex = 0 s.currentVideoIndex = 0
} }
s.mu.Unlock()
s.Stop() s.Stop()
} }
@ -157,11 +174,11 @@ func (s *Streamer) log(reader *bufio.Reader) {
if n > 0 { if n > 0 {
videoPath, _ := s.GetCurrentVideoPath() videoPath, _ := s.GetCurrentVideoPath()
buf = append([]byte(videoPath), buf...) buf = append([]byte(videoPath), buf...)
s.outputer.Broadcast(websocket.MakeOutput(string(buf[:n+len(videoPath)]))) s.writeOutput(string(buf[:n+len(videoPath)]))
} }
if err != nil { if err != nil {
if err != io.EOF { if err != io.EOF {
s.outputer.Broadcast(websocket.MakeOutput(fmt.Sprintf("reading ffmpeg output error: %v\n", err))) s.writeOutput(fmt.Sprintf("reading ffmpeg output error: %v\n", err))
} }
break break
} }
@ -169,6 +186,60 @@ func (s *Streamer) log(reader *bufio.Reader) {
} }
} }
func (s *Streamer) GetCurrentVideoPath() (string, error) {
s.mu.Lock()
defer s.mu.Unlock()
if len(s.videoList) == 0 {
return "", errors.New("no video streaming")
}
return s.videoList[s.currentVideoIndex].Path, nil
}
func (s *Streamer) GetVideoList() []config.InputItem {
s.mu.Lock()
defer s.mu.Unlock()
return s.videoList
}
func (s *Streamer) GetVideoListPath() []string {
s.mu.Lock()
defer s.mu.Unlock()
var videoList []string
for _, item := range s.videoList {
videoList = append(videoList, item.Path)
}
return videoList
}
func (s *Streamer) GetCurrentIndex() int {
s.mu.Lock()
defer s.mu.Unlock()
return s.currentVideoIndex
}
func (s *Streamer) GetOutput() string {
s.mu.Lock()
defer s.mu.Unlock()
return s.output.String()
}
func (s *Streamer) TruncateOutput() int {
s.mu.Lock()
defer s.mu.Unlock()
currentSize := s.output.Len()
if currentSize > math.MaxInt {
newStart := currentSize - math.MaxInt
trimmedOutput := s.output.String()[newStart:]
s.output.Reset()
s.output.WriteString(trimmedOutput)
}
return currentSize
}
func (s *Streamer) Close() {
s.Stop()
}
func (s *Streamer) buildFFmpegArgs(videoItem config.InputItem) []string { func (s *Streamer) buildFFmpegArgs(videoItem config.InputItem) []string {
videoPath := videoItem.Path videoPath := videoItem.Path
@ -209,30 +280,3 @@ func (s *Streamer) buildFFmpegArgs(videoItem config.InputItem) []string {
return args return args
} }
func (s *Streamer) GetCurrentVideoPath() (string, error) {
if len(s.videoList) == 0 {
return "", errors.New("no video streaming")
}
return s.videoList[s.currentVideoIndex].Path, nil
}
func (s *Streamer) GetVideoList() []config.InputItem {
return s.videoList
}
func (s *Streamer) GetVideoListPath() []string {
var videoList []string
for _, item := range s.videoList {
videoList = append(videoList, item.Path)
}
return videoList
}
func (s *Streamer) GetCurrentIndex() int {
return s.currentVideoIndex
}
func (s *Streamer) Close() {
s.Stop()
}

View File

@ -1,6 +0,0 @@
package websocket
type Outputer interface {
Broadcast(v Response)
Single(userID string, v Response)
}

View File

@ -1,47 +1,20 @@
package websocket package websocket
type MessageType string type RequestType string
var ( const (
TypeOutput MessageType = "Output" TypeStreamNextVideo RequestType = "StreamNextVideo"
TypeStreamNextVideo MessageType = "StreamNextVideo" TypeStreamPrevVideo RequestType = "StreamPrevVideo"
TypeStreamPrevVideo MessageType = "StreamPrevVideo" TypeQuit RequestType = "Quit"
TypeGetCurrentVideoPath MessageType = "GetCurrentVideoPath"
TypeGetVideoList MessageType = "GetVideoList"
TypeQuit MessageType = "Quit"
TypeRemoveVideo MessageType = "RemoveVideo"
TypeAddVideo MessageType = "AddVideo"
) )
type Request struct { type Request struct {
Type MessageType `json:"type"` Type RequestType `json:"type"`
Args []string `json:"args"`
UserID string `json:"user_id"`
Timestamp int64 `json:"timestamp"`
} }
type Response struct { type Date struct {
Type MessageType `json:"type"` Timestamp int64 `json:"timestamp"`
Success bool `json:"success"` CurrentVideoPath string `json:"currentVideoPath"`
Data any `json:"data"` VideoList []string `json:"videoList"`
Message string `json:"message"` Output string `json:"output"`
UserID string `json:"user_id"`
Timestamp int64 `json:"timestamp"`
}
func MakeResponse(messageType MessageType, success bool, data any, message string) Response {
return Response{
Type: messageType,
Success: success,
Data: data,
Message: message,
}
}
func MakeOutput(output string) Response {
return Response{
Success: true,
Type: TypeOutput,
Data: output,
}
} }

View File

@ -1,60 +1,18 @@
package main package main
import ( import (
"live-streamer/server"
"live-streamer/websocket" "live-streamer/websocket"
"os"
) )
func websocketRequestHandler(req websocket.Response) { func websocketRequestHandler(reqType websocket.RequestType) {
if req.UserID == "" { switch reqType {
return
}
var resp websocket.Response
switch websocket.MessageType(req.Type) {
case websocket.TypeStreamNextVideo: case websocket.TypeStreamNextVideo:
GlobalStreamer.Next() GlobalStreamer.Next()
resp = websocket.Response{
Type: websocket.TypeStreamNextVideo,
Success: true,
}
server.GlobalServer.Broadcast(resp)
case websocket.TypeStreamPrevVideo: case websocket.TypeStreamPrevVideo:
GlobalStreamer.Prev() GlobalStreamer.Prev()
resp = websocket.Response{
Type: websocket.TypeStreamPrevVideo,
Success: true,
}
server.GlobalServer.Broadcast(resp)
case websocket.TypeGetCurrentVideoPath:
videoPath, err := GlobalStreamer.GetCurrentVideoPath()
if err != nil {
resp = websocket.Response{
Type: websocket.TypeGetCurrentVideoPath,
Success: false,
Message: err.Error(),
}
} else {
resp = websocket.Response{
Type: websocket.TypeGetCurrentVideoPath,
Success: true,
Data: videoPath,
}
}
server.GlobalServer.Single(req.UserID, resp)
case websocket.TypeGetVideoList:
resp = websocket.Response{
Type: websocket.TypeGetVideoList,
Success: true,
Data: GlobalStreamer.GetVideoListPath(),
}
server.GlobalServer.Single(req.UserID, resp)
case websocket.TypeQuit: case websocket.TypeQuit:
server.GlobalServer.Close()
GlobalStreamer.Close() GlobalStreamer.Close()
resp = websocket.Response{ os.Exit(0)
Type: websocket.TypeQuit,
Success: true,
}
server.GlobalServer.Broadcast(resp)
} }
} }