-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcli_offer.go
165 lines (154 loc) · 4.28 KB
/
cli_offer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package main
import (
"bufio"
"context"
"crypto/rand"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"sync"
"time"
"github.com/ipsn/go-ipfs/core"
"github.com/ipsn/go-ipfs/core/coreapi"
coreiface "github.com/ipsn/go-ipfs/core/coreapi/interface"
"github.com/ipsn/go-ipfs/core/coreapi/interface/options"
"github.com/pions/webrtc"
"github.com/pions/webrtc/pkg/datachannel"
"github.com/pions/webrtc/pkg/ice"
)
var debugEnabled = true
func main() {
ctx, cancelFn := context.WithCancel(context.Background())
defer cancelFn()
// Get ID
id, err := parseFlags()
assertNoErr(err)
fmt.Printf("Visit browser-answer.html#%v or go run cli_answer.go %v\n", id, id)
// Create IPFS
pubsub, err := newIPFSPubSub(ctx)
assertNoErr(err)
// Create peer conn
pc, err := webrtc.New(webrtc.RTCConfiguration{
IceServers: []webrtc.RTCIceServer{{URLs: []string{"stun:stun.l.google.com:19302"}}},
})
assertNoErr(err)
// Create the chat channel
channel, err := pc.CreateDataChannel("chat", nil)
assertNoErr(err)
setupChatChannel(channel)
// Debug state change info
pc.OnICEConnectionStateChange(func(state ice.ConnectionState) {
debugf("RTC connection state change: %v", state)
})
// Subscribe to offer/answer topic
topic := "wis-poc-" + id
sub, err := pubsub.Subscribe(ctx, topic, options.PubSub.Discover(true))
assertNoErr(err)
debugf("Subscribe to %v complete", topic)
// Listen for first answer
answerCh := make(chan *webrtc.RTCSessionDescription, 1)
go func() {
var desc webrtc.RTCSessionDescription
for {
msg, err := sub.Next(ctx)
assertNoErr(err)
assertNoErr(json.Unmarshal(msg.Data(), &desc))
debugf("Received data: %v", desc.Type)
if desc.Type == webrtc.RTCSdpTypeAnswer {
answerCh <- &desc
break
}
}
}()
// Create the offer and keep sending until received
offer, err := pc.CreateOffer(nil)
assertNoErr(err)
offerBytes, err := json.Marshal(offer)
assertNoErr(err)
var answer *webrtc.RTCSessionDescription
WaitForAnswer:
for {
debugf("Sending offer")
assertNoErr(pubsub.Publish(ctx, topic, offerBytes))
select {
case answer = <-answerCh:
fmt.Printf("Got answer")
break WaitForAnswer
case <-time.After(2 * time.Second):
}
}
// Now that we have an answer, set it and block forever (the chat channel does the work now)
assertNoErr(pc.SetRemoteDescription(*answer))
select {}
}
func newIPFSPubSub(ctx context.Context) (coreiface.PubSubAPI, error) {
cfg := &core.BuildCfg{
Online: true,
ExtraOpts: map[string]bool{"pubsub": true},
}
if node, err := core.NewNode(ctx, cfg); err != nil {
return nil, err
} else if api, err := coreapi.NewCoreAPI(node); err != nil {
return nil, err
} else {
return api.PubSub(), nil
}
}
func setupChatChannel(channel *webrtc.RTCDataChannel) {
channel.OnClose(func() { printChatLn("**system** chat closed") })
channel.OnOpen(func() {
printChatLn("**system** chat started")
// Just read stdin forever and try to send it over or panic
r := bufio.NewReader(os.Stdin)
for {
text, _ := r.ReadString('\n')
printChatLn("**me** " + text)
err := channel.Send(datachannel.PayloadString{Data: []byte(text)})
assertNoErr(err)
}
})
channel.OnMessage(func(p datachannel.Payload) {
if p.PayloadType() != datachannel.PayloadTypeString {
panic("Expected string payload")
}
printChatLn("**them** " + string(p.(datachannel.PayloadString).Data))
})
}
var chatLnMutex sync.Mutex
func printChatLn(line string) {
chatLnMutex.Lock()
defer chatLnMutex.Unlock()
fmt.Println(line)
}
func parseFlags() (id string, err error) {
fs := flag.NewFlagSet("", flag.ExitOnError)
fs.BoolVar(&debugEnabled, "v", false, "Show debug information")
fs.StringVar(&id, "id", "", "The identifier to put offer for (optional, generated when not present)")
assertNoErr(fs.Parse(os.Args[1:]))
if fs.NArg() > 0 {
return "", fmt.Errorf("Unrecognized args: %v", fs.Args())
}
// Generate ID if not there
if id == "" {
const base58Chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
var idBytes [20]byte
if _, err := rand.Read(idBytes[:]); err == nil {
for _, idByte := range idBytes {
id += string(base58Chars[int(idByte)%len(base58Chars)])
}
}
}
return
}
func debugf(format string, v ...interface{}) {
if debugEnabled {
log.Printf(format, v...)
}
}
func assertNoErr(err error) {
if err != nil {
panic(err)
}
}