-
Notifications
You must be signed in to change notification settings - Fork 28
/
wss.go
301 lines (262 loc) · 6.52 KB
/
wss.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package gotiktoklive
import (
"context"
"encoding/hex"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"time"
pb "github.com/Davincible/gotiktoklive/proto"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
"golang.org/x/net/proxy"
"google.golang.org/protobuf/proto"
)
func (l *Live) connect(addr string, params map[string]string) error {
u, err := url.Parse("https://tiktok.com/")
if err != nil {
return nil
}
// Take the cookies from the HTTP client cookie jar and pass them as a GET parameter.
cookies := l.t.c.Jar.Cookies(u)
headers := http.Header{}
var s string
for _, cookie := range cookies {
if s == "" {
s = cookie.String()
} else {
s += "; " + cookie.String()
}
}
if len(cookies) > 0 {
headers.Set("Cookie", s)
}
vs := url.Values{}
for key, value := range defaultGETParams {
vs.Add(key, value)
}
for key, value := range params {
vs.Add(key, value)
}
vs.Add("room_id", l.ID)
wsURL := fmt.Sprintf("%s?%s", addr, vs.Encode())
// Read proxies from HTTP env variables, HTTPS takes precedent
var proxyURI *url.URL
envVars := []string{"HTTP_PROXY", "HTTPS_PROXY"}
for _, envVar := range envVars {
if httpProxy := os.Getenv(envVar); httpProxy != "" {
uri, err := url.Parse(httpProxy)
if err != nil {
l.t.warnHandler(fmt.Errorf("Failed to parse %s url: %w", envVar, err))
} else {
proxyURI = uri
}
}
}
// If proxy manually defined, use that
if l.t.proxy != nil {
proxyURI = l.t.proxy
}
// Default proxy net dial
proxyNetDial := proxy.FromEnvironment()
// If custom URI is defined, genereate proxy net dial from that
if proxyURI != nil {
dial, err := proxy.FromURL(proxyURI, Direct)
if err != nil {
l.t.warnHandler(fmt.Errorf("Failed to configure proxy dialer: %w", err))
} else {
proxyNetDial = dial
}
}
dialer := ws.Dialer{
Header: ws.HandshakeHeaderHTTP(headers),
NetDial: func(ctx context.Context, a, b string) (net.Conn, error) {
return proxyNetDial.Dial(a, b)
},
// NetDial: proxy.Dial,
Protocols: []string{"echo-protocol"},
}
conn, _, _, err := dialer.Dial(context.Background(), wsURL)
if err != nil {
return fmt.Errorf("Failed to connect: %w", err)
}
l.wss = conn
return nil
}
func (l *Live) readSocket() {
defer l.wss.Close()
defer l.t.wg.Done()
want := ws.OpBinary
s := ws.StateClientSide
controlHandler := wsutil.ControlFrameHandler(l.wss, s)
rd := wsutil.Reader{
Source: l.wss,
State: s,
CheckUTF8: true,
SkipHeaderCheck: false,
OnIntermediate: controlHandler,
}
for {
hdr, err := rd.NextFrame()
if err != nil {
l.t.warnHandler(fmt.Errorf("Failed to read websocket message, attempting to reconnect: %w", err))
l.wss.Close()
if !l.reconnectWebsocket() {
return
}
}
// If msg is ping or close
if hdr.OpCode.IsControl() {
if err := controlHandler(hdr, &rd); err != nil {
l.t.errHandler(fmt.Errorf("websocket control handler failed: %w", err))
}
continue
}
// Reopen connection if it was closed
if hdr.OpCode == ws.OpClose {
l.t.warnHandler("Websocket connection was closed by server, attempting to reconnect...")
if !l.reconnectWebsocket() {
return
}
}
// Wrong OpCode
if hdr.OpCode&want == 0 {
if err := rd.Discard(); err != nil {
l.t.errHandler(err)
}
continue
}
// Read message
msgBytes, err := ioutil.ReadAll(&rd)
if err != nil {
l.t.errHandler(fmt.Errorf("Failed to read websocket message: %w", err))
}
if err := l.parseWssMsg(msgBytes); err != nil {
l.t.errHandler(fmt.Errorf("Failed to parse websocket message: %w", err))
}
// Gracefully shutdown
select {
case <-l.done():
return
case <-l.t.done():
l.t.infoHandler("Close websocket, global context done")
return
default:
}
}
}
func (l *Live) reconnectWebsocket() bool {
time.Sleep(3 * time.Second)
connected, err := l.tryConnectionUpgrade()
if err != nil {
l.t.warnHandler(fmt.Errorf("Failed to re-open websocket connection: %w", err))
} else {
l.t.infoHandler("Reconnected to websocket successfully")
}
if !connected {
l.t.wg.Add(1)
go l.startPolling()
}
return connected
}
func (l *Live) parseWssMsg(wssMsg []byte) error {
var rsp pb.WebcastWebsocketMessage
if err := proto.Unmarshal(wssMsg, &rsp); err != nil {
return fmt.Errorf("Failed to unmarshal proto WebcastWebsocketMessage: %w", err)
}
if rsp.Type == "msg" {
var response pb.WebcastResponse
if err := proto.Unmarshal(rsp.Binary, &response); err != nil {
return fmt.Errorf("Failed to unmarshal proto WebcastResponse: %w", err)
}
if err := l.sendAck(rsp.Id); err != nil {
return fmt.Errorf("Failed to send websocket ack msg: %w", err)
}
l.cursor = response.Cursor
if l.t.Debug {
l.t.debugHandler(fmt.Sprintf("Got %d messages, %s", len(response.Messages), response.Cursor))
}
for _, rawMsg := range response.Messages {
msg, err := parseMsg(rawMsg, l.t.warnHandler)
if err != nil {
return fmt.Errorf("Failed to parse response message: %w", err)
}
if msg != nil {
// If channel is full, discard the first message
if len(l.Events) == l.chanSize {
<-l.Events
}
l.Events <- msg
}
// If livestream has ended
if m, ok := msg.(ControlEvent); ok && m.Action == 3 {
go func() {
select {
case <-time.After(10 * time.Second):
l.close()
}
}()
}
}
return nil
}
if l.t.Debug {
l.t.debugHandler(fmt.Sprintf("Message type unknown, %s : '%s'", rsp.Type, string(rsp.Binary)))
}
return nil
}
func (l *Live) sendPing() {
defer l.t.wg.Done()
b, err := hex.DecodeString("3A026862")
if err != nil {
l.t.errHandler(err)
}
t := time.NewTicker(10000 * time.Millisecond)
defer t.Stop()
for {
select {
case <-l.done():
return
case <-l.t.done():
return
case <-t.C:
if err := wsutil.WriteClientBinary(l.wss, b); err != nil {
l.t.errHandler(fmt.Errorf("Failed to send ping: %w", err))
}
}
}
}
func (l *Live) sendAck(id uint64) error {
msg := pb.WebcastWebsocketAck{
Id: id,
Type: "ack",
}
b, err := proto.Marshal(&msg)
if err != nil {
return err
}
if err := wsutil.WriteClientBinary(l.wss, b); err != nil {
return err
}
return nil
}
func (l *Live) tryConnectionUpgrade() (bool, error) {
if l.wsURL != "" && l.wsParams != nil {
err := l.connect(l.wsURL, l.wsParams)
if err != nil {
return false, fmt.Errorf("Connection upgrade failed: %w", err)
}
if l.t.Debug {
l.t.debugHandler("Connected to websocket")
}
l.t.wg.Add(2)
go l.readSocket()
go l.sendPing()
l.t.infoHandler("Connected to websocket")
return true, nil
}
return false, nil
}