91 lines
2.7 KiB
Go
91 lines
2.7 KiB
Go
package boot
|
|
|
|
import (
|
|
"encoding/json"
|
|
"g365sfu/bytebuffer"
|
|
"g365sfu/logger"
|
|
"g365sfu/sfu"
|
|
"g365sfu/socket"
|
|
"g365sfu/turn"
|
|
"net/http"
|
|
"os"
|
|
|
|
"github.com/joho/godotenv"
|
|
"github.com/pion/webrtc/v4"
|
|
)
|
|
|
|
func Bootstrap() {
|
|
godotenv.Load()
|
|
sfu.InitWebRTCEngines()
|
|
if os.Getenv("SECRET") == "" {
|
|
logger.LogErrorMessage("server failed to start because not set secret key in .env variables")
|
|
return
|
|
}
|
|
http.HandleFunc("/", socket.HandleWebSocket)
|
|
port := os.Getenv("PORT")
|
|
if port == "" {
|
|
port = "1001"
|
|
}
|
|
sfu.OnLocalICECandidate = OnLocalICECandidate
|
|
sfu.OnServerOffer = OnServerOffer
|
|
turnServer, err := turn.Start(turn.Config{
|
|
ListenAddr: "0.0.0.0:3478",
|
|
PublicIP: os.Getenv("TURN_PUBLIC_IP"),
|
|
Realm: "g365sfu",
|
|
Username: os.Getenv("TURN_USER"),
|
|
Password: os.Getenv("TURN_PASS"),
|
|
})
|
|
if err != nil {
|
|
logger.LogWarnMessage("TURN start failed: " + err.Error())
|
|
} else {
|
|
logger.LogInfoMessage("TURN started on 0.0.0.0:3478")
|
|
defer turnServer.Close()
|
|
}
|
|
logger.LogInfoMessage("server started at x.x.x.x:" + port)
|
|
http.ListenAndServe(":"+port, nil)
|
|
}
|
|
|
|
// Коллбек для обработки новых ICE кандидатов от сервера к пиру
|
|
func OnLocalICECandidate(roomID string, peerID string, candidate webrtc.ICECandidateInit) {
|
|
room, exists := sfu.GetRoom(roomID)
|
|
if !exists {
|
|
logger.LogWarnMessage("tried to send local ICE candidate to non existing room " + roomID)
|
|
return
|
|
}
|
|
jsonCandidate, _ := json.Marshal(candidate)
|
|
buffer := bytebuffer.Allocate(
|
|
1 + 4 + len([]byte(roomID)) + 4 + len([]byte(peerID)) + 4 + len(jsonCandidate),
|
|
)
|
|
buffer.Put(0x04)
|
|
buffer.PutUint32(uint32(len([]byte(roomID))))
|
|
buffer.PutBytes([]byte(roomID))
|
|
buffer.PutUint32(uint32(len([]byte(peerID))))
|
|
buffer.PutBytes([]byte(peerID))
|
|
buffer.PutUint32(uint32(len([]byte(jsonCandidate))))
|
|
buffer.PutBytes([]byte(jsonCandidate))
|
|
buffer.Flip()
|
|
room.Server.WriteBinary(buffer.Bytes())
|
|
}
|
|
|
|
// Обработка нового оффера от сервера для конкретного пира (при renegotiation)
|
|
func OnServerOffer(roomID string, peerID string, offer webrtc.SessionDescription) {
|
|
room, exists := sfu.GetRoom(roomID)
|
|
if !exists {
|
|
logger.LogWarnMessage("tried to send server offer to non existing room " + roomID)
|
|
return
|
|
}
|
|
jsonOffer, _ := json.Marshal(offer)
|
|
buffer := bytebuffer.Allocate(
|
|
1 + 4 + len([]byte(roomID)) + 4 + len([]byte(peerID)) + 4 + len(jsonOffer),
|
|
)
|
|
buffer.Put(0x08)
|
|
buffer.PutUint32(uint32(len([]byte(roomID))))
|
|
buffer.PutBytes([]byte(roomID))
|
|
buffer.PutUint32(uint32(len([]byte(peerID))))
|
|
buffer.PutBytes([]byte(peerID))
|
|
buffer.PutUint32(uint32(len([]byte(jsonOffer))))
|
|
buffer.PutBytes([]byte(jsonOffer))
|
|
buffer.Flip()
|
|
room.Server.WriteBinary(buffer.Bytes())
|
|
}
|