Skip to content

Commit

Permalink
Fix webrtc:ws source after 1.9.5 #1425
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexxIT committed Oct 31, 2024
1 parent 8cca8de commit 3f5f132
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 10 deletions.
20 changes: 10 additions & 10 deletions internal/api/ws/ws.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,21 @@ var log zerolog.Logger
type Message struct {
Type string `json:"type"`
Value any `json:"value,omitempty"`
Raw []byte `json:"-"`
}

func (m *Message) String() (value string) {
_ = json.Unmarshal(m.Raw, &value)
if s, ok := m.Value.(string); ok {
return s
}
return
}

func (m *Message) Unmarshal(v any) error {
return json.Unmarshal(m.Raw, v)
b, err := json.Marshal(m.Value)
if err != nil {
return err
}
return json.Unmarshal(b, v)
}

type WSHandler func(tr *Transport, msg *Message) error
Expand Down Expand Up @@ -113,20 +118,15 @@ func apiWS(w http.ResponseWriter, r *http.Request) {
})

for {
var raw struct {
Type string `json:"type"`
Value json.RawMessage `json:"value"`
}
if err = ws.ReadJSON(&raw); err != nil {
msg := new(Message)
if err = ws.ReadJSON(msg); err != nil {
if !websocket.IsCloseError(err, websocket.CloseNoStatusReceived) {
log.Trace().Err(err).Caller().Send()
}
_ = ws.Close()
break
}

msg := &Message{Type: raw.Type, Raw: raw.Value}

log.Trace().Str("type", msg.Type).Msg("[api] ws msg")

if handler := wsHandlers[msg.Type]; handler != nil {
Expand Down
38 changes: 38 additions & 0 deletions internal/webrtc/webrtc_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package webrtc

import (
"encoding/json"
"testing"

"github.com/AlexxIT/go2rtc/internal/api/ws"
pion "github.com/pion/webrtc/v3"
"github.com/stretchr/testify/require"
)

func TestWebRTCAPIv1(t *testing.T) {
raw := `{"type":"webrtc/offer","value":"v=0\n..."}`
msg := new(ws.Message)
err := json.Unmarshal([]byte(raw), msg)
require.Nil(t, err)

require.Equal(t, "v=0\n...", msg.String())
}

func TestWebRTCAPIv2(t *testing.T) {
raw := `{"type":"webrtc","value":{"type":"offer","sdp":"v=0\n...","ice_servers":[{"urls":["stun:stun.l.google.com:19302"]}]}}`
msg := new(ws.Message)
err := json.Unmarshal([]byte(raw), msg)
require.Nil(t, err)

var offer struct {
Type string `json:"type"`
SDP string `json:"sdp"`
ICEServers []pion.ICEServer `json:"ice_servers"`
}
err = msg.Unmarshal(&offer)
require.Nil(t, err)

require.Equal(t, "offer", offer.Type)
require.Equal(t, "v=0\n...", offer.SDP)
require.Equal(t, "stun:stun.l.google.com:19302", offer.ICEServers[0].URLs[0])
}

0 comments on commit 3f5f132

Please sign in to comment.