forked from hr3lxphr6j/bililive-go
/
douyu.go
320 lines (294 loc) · 7.52 KB
/
douyu.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package douyu
import (
"bytes"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"text/template"
"time"
"github.com/hr3lxphr6j/requests"
"github.com/luckycat0426/bililive-go/src/live"
"github.com/luckycat0426/bililive-go/src/live/internal"
"github.com/luckycat0426/bililive-go/src/pkg/utils"
"github.com/robertkrimen/otto"
"github.com/satori/go.uuid"
"github.com/tidwall/gjson"
)
/*
From https://github.com/zhangn1985/ykdl
Thanks
*/
const (
domain = "www.douyu.com"
cnName = "斗鱼"
liveInfoUrl = "https://www.douyu.com/betard"
liveEncUrl = "https://www.douyu.com/swf_api/homeH5Enc"
liveAPIUrl = "https://www.douyu.com/lapi/live/getH5Play"
)
func init() {
live.Register(domain, new(builder))
}
type builder struct{}
func (b *builder) Build(url *url.URL, opt ...live.Option) (live.Live, error) {
return &Live{
BaseLive: internal.NewBaseLive(url, opt...),
}, nil
}
var (
cryptoJS []byte
douyuRoomIDRegs = []string{
`\$ROOM\.room_id\s*=\s*(\d+)`,
`room_id\s*=\s*(\d+)`,
`"room_id.?":(\d+)`,
`data-onlineid=(\d+)`,
}
workflowReg = `function ub98484234\(.+?\Weval\((\w+)\);`
jsDomTmpl = template.Must(template.New("jsDom").Parse(`
{{.DebugMessages}} = { {{.DecryptedCodes}}: []};
if (!this.window) {window = {};}
if (!this.document) {document = {};}
`))
jsPatchTmpl = template.Must(template.New("jsPatch").Parse(`
{{.DebugMessages}}.{{.DecryptedCodes}}.push({{.Workflow}});
var patchCode = function(workflow) {
var testVari = /(\w+)=(\w+)\([\w\+]+\);.*?(\w+)="\w+";/.exec(workflow);
if (testVari && testVari[1] == testVari[2]) {
{{.Workflow}} += testVari[1] + "[" + testVari[3] + "] = function() {return true;};";
}
};
patchCode({{.Workflow}});
var subWorkflow = /(?:\w+=)?eval\((\w+)\)/.exec({{.Workflow}});
if (subWorkflow) {
var subPatch = (
"{{.DebugMessages}}.{{.DecryptedCodes}}.push('sub workflow: ' + subWorkflow);" +
"patchCode(subWorkflow);"
).replace(/subWorkflow/g, subWorkflow[1]) + subWorkflow[0];
{{.Workflow}} = {{.Workflow}}.replace(subWorkflow[0], subPatch);
}
eval({{.Workflow}});
`))
jsDebugTmpl = template.Must(template.New("jsDebug").Parse(`
var {{.Ub98484234}} = ub98484234;
ub98484234 = function(p1, p2, p3) {
try {
var resoult = {{.Ub98484234}}(p1, p2, p3);
{{.DebugMessages}}.{{.Resoult}} = resoult;
} catch(e) {
{{.DebugMessages}}.{{.Resoult}} = e.message;
}
return {{.DebugMessages}};
};
`))
)
func render(tmpl *template.Template, data interface{}) (string, error) {
buf := bytes.NewBuffer(nil)
if err := tmpl.Execute(buf, data); err != nil {
return "", err
}
return buf.String(), nil
}
func loadCryptoJS() {
var (
resp *requests.Response
body []byte
err error
)
cdnUrls := [...]string{"https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js",
"https://cdn.jsdelivr.net/npm/crypto-js@3.1.9-1/crypto-js.min.js",
"https://cdn.staticfile.org/crypto-js/3.1.9-1/crypto-js.min.js",
"https://cdn.bootcdn.net/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"}
for _, url := range cdnUrls {
resp, err = requests.Get(url)
if err != nil || resp.StatusCode != http.StatusOK {
continue
}
body, err = resp.Bytes()
if err != nil {
continue
}
cryptoJS = body
return
}
panic(fmt.Errorf("failed to load CryptoJS, please check network"))
}
func getEngineWithCryptoJS() (*otto.Otto, error) {
if cryptoJS == nil {
loadCryptoJS()
}
engine := otto.New()
if _, err := engine.Eval(cryptoJS); err != nil {
return nil, err
}
return engine, nil
}
type Live struct {
internal.BaseLive
roomID string
}
func (l *Live) fetchRoomID() error {
if l.roomID != "" {
return nil
}
var body []byte
resp, err := requests.Get(l.Url.String(), live.CommonUserAgent)
if err != nil {
goto ERROR
}
if resp.StatusCode != http.StatusOK {
goto ERROR
}
body, err = resp.Bytes()
if err != nil {
goto ERROR
}
for _, reg := range douyuRoomIDRegs {
if str := utils.Match1(reg, string(body)); str != "" {
l.roomID = str
return nil
}
}
goto ERROR
ERROR:
return errors.New("failed to fetch room id")
}
func (l *Live) GetInfo() (info *live.Info, err error) {
if err := l.fetchRoomID(); err != nil {
return nil, err
}
resp, err := requests.Get(fmt.Sprintf("%s/%s", liveInfoUrl, l.roomID), live.CommonUserAgent)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, live.ErrRoomNotExist
}
body, err := resp.Bytes()
if err != nil {
return nil, err
}
info = &live.Info{
Live: l,
HostName: gjson.GetBytes(body, "room.owner_name").String(),
RoomName: gjson.GetBytes(body, "room.room_name").String(),
Status: gjson.GetBytes(body, "room.show_status").Int() == 1 && gjson.GetBytes(body, "room.videoLoop").Int() == 0,
}
return info, nil
}
func (l *Live) getSignParams() (map[string]string, error) {
resp, err := requests.Get(liveEncUrl, live.CommonUserAgent, requests.Query("rids", l.roomID))
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, live.ErrRoomNotExist
}
body, err := resp.Bytes()
if err != nil {
return nil, err
}
jsEnc := gjson.GetBytes(body, "data.room"+l.roomID).String()
workflow := utils.Match1(workflowReg, jsEnc)
context := struct {
DebugMessages string
DecryptedCodes string
Resoult string
Ub98484234 string
Workflow string
}{
DebugMessages: utils.GenRandomName(8),
DecryptedCodes: utils.GenRandomName(8),
Resoult: utils.GenRandomName(8),
Ub98484234: utils.GenRandomName(8),
Workflow: workflow,
}
jsDom, err := render(jsDomTmpl, context)
if err != nil {
return nil, err
}
jsPatch, err := render(jsPatchTmpl, context)
if err != nil {
return nil, err
}
jsDebug, err := render(jsDebugTmpl, context)
if err != nil {
return nil, err
}
jsEnc = strings.ReplaceAll(jsEnc, fmt.Sprintf("eval(%s);", context.Workflow), jsPatch)
engine, err := getEngineWithCryptoJS()
if err != nil {
return nil, err
}
if _, err := engine.Eval(jsDom); err != nil {
return nil, err
}
if _, err := engine.Eval(jsEnc); err != nil {
return nil, err
}
if _, err := engine.Eval(jsDebug); err != nil {
return nil, err
}
did := strings.ReplaceAll(uuid.Must(uuid.NewV4()).String(), "-", "")
ts := time.Now()
res, err := engine.Call("ub98484234", nil, l.roomID, did, ts.Unix())
if err != nil {
return nil, err
}
values := map[string]string{
"cdn": "",
"iar": "0",
"ive": "0",
"rate": "0",
}
resoult, err := res.Object().Get(context.Resoult)
if err != nil {
return nil, err
}
for _, entry := range strings.Split(resoult.String(), "&") {
if entry == "" {
continue
}
strs := strings.SplitN(entry, "=", 2)
values[strs[0]] = strs[1]
}
return values, nil
}
func (l *Live) GetStreamUrls() (us []*url.URL, err error) {
if err := l.fetchRoomID(); err != nil {
return nil, err
}
params, err := l.getSignParams()
if err != nil {
return nil, err
}
resp, err := requests.Post(
fmt.Sprintf("%s/%s", liveAPIUrl, l.roomID),
requests.Form(params),
requests.Header("origin", "https://www.douyu.com"),
requests.Referer(l.GetRawUrl()),
live.CommonUserAgent,
)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, live.ErrInternalError
}
body, err := resp.Bytes()
if err != nil {
return nil, err
}
if gjson.GetBytes(body, "error").Int() != 0 {
return nil, live.ErrRoomNotExist
}
return utils.GenUrls(
fmt.Sprintf("%s/%s",
gjson.GetBytes(body, "data.rtmp_url").String(),
gjson.GetBytes(body, "data.rtmp_live").String(),
),
)
}
func (l *Live) GetPlatformCNName() string {
return cnName
}