-
Notifications
You must be signed in to change notification settings - Fork 14
/
live.go
476 lines (445 loc) · 11.6 KB
/
live.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
package dylive
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
"sync"
)
const userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0"
type (
Category struct {
Id string
Name string
Categories []Category
}
dyliveCategories struct {
CategoryData []struct {
Partition struct {
IDStr string `json:"id_str"`
Type int `json:"type"`
Title string `json:"title"`
} `json:"partition"`
} `json:"categoryData"`
}
)
// GetCategories gets all Douyin live stream categories.
func GetCategories(ctx context.Context) ([]Category, error) {
const first = "1_1"
var cats []Category
var subCats []Category
err := getCategories(ctx, first, &cats, &subCats)
if err != nil {
return nil, err
}
var wg sync.WaitGroup
for i := range cats {
if cats[i].Id == first {
cats[i].Categories = subCats
} else {
wg.Add(1)
go func(i int) {
defer wg.Done()
var subCats []Category
getCategories(ctx, cats[i].Id, nil, &subCats)
cats[i].Categories = subCats
}(i)
}
}
wg.Wait()
return cats, nil
}
func getCategories(ctx context.Context, id string, categories, subCategories *[]Category) error {
if categories == nil && subCategories == nil {
return nil
}
data, err := getCategoryPageData(ctx, id, "categoryData", "partitionData")
if err != nil {
return err
}
categoryData, partitionData := data[0], data[1]
var cats dyliveCategories
if err := getDataInArray(categoryData, &cats); err != nil {
return err
}
var cat dyliveCategory
if err := getDataInArray(partitionData, &cat); err != nil {
return err
}
if categories != nil {
for _, cat := range cats.CategoryData {
*categories = append(*categories, Category{
Id: fmt.Sprintf("%d_%s", cat.Partition.Type, cat.Partition.IDStr),
Name: cat.Partition.Title,
})
}
}
if subCategories != nil {
p := cat.PartitionData.Partition
for _, cat := range cat.PartitionData.SubPartition {
*subCategories = append(*subCategories, Category{
Id: fmt.Sprintf("%d_%s_%d_%s", p.Type, p.IDStr, cat.Type, cat.IDStr),
Name: cat.Title,
})
}
}
return nil
}
const (
RoomStatusLiveOn RoomStatus = 2 + iota
_
RoomStatusLiveOff
)
type (
RoomStatus = int
Room struct {
Id string
DouyinId string
StatusCode RoomStatus
Name string
CoverUrl string
WebUrl string
CurrentUsersCount string
TotalUsersCount string
Category *Category
User User
StreamUrl string
FlvStreamUrls map[string]string
HlsStreamUrls map[string]string
}
User struct {
Name string
Picture string
}
dyUser struct {
Nickname string `json:"nickname"`
AvatarThumb struct {
UrlList []string `json:"url_list"`
} `json:"avatar_thumb"`
}
dyliveRoom struct {
IdStr string `json:"id_str"`
Title string `json:"title"`
Status int `json:"status"`
Cover struct {
UrlList []string `json:"url_list"`
} `json:"cover"`
Stats struct {
TotalUserStr string `json:"total_user_str"`
UserCountStr string `json:"user_count_str"`
} `json:"stats"`
Owner dyUser `json:"owner"`
StreamUrl struct {
FlvPullUrl map[string]string `json:"flv_pull_url"`
HlsPullUrlMap map[string]string `json:"hls_pull_url_map"`
DefaultResolution string `json:"default_resolution"`
} `json:"stream_url"`
RoomViewStats struct {
DisplayValue int `json:"display_value"`
} `json:"room_view_stats"`
}
dyliveCategory struct {
RoomsData struct {
Data []struct {
Room dyliveRoom `json:"room"`
WebRid string `json:"web_rid"`
StreamSrc string `json:"streamSrc"`
Cover string `json:"cover"`
Avatar string `json:"avatar"`
} `json:"data"`
} `json:"roomsData"`
PartitionData struct {
Partition struct {
IDStr string `json:"id_str"`
Type int `json:"type"`
Title string `json:"title"`
} `json:"partition"`
SelectPartition struct {
IDStr string `json:"id_str"`
Type int `json:"type"`
Title string `json:"title"`
} `json:"select_partition"`
SubPartition []struct {
IDStr string `json:"id_str"`
Type int `json:"type"`
Title string `json:"title"`
} `json:"sub_partition"`
} `json:"partitionData"`
}
)
// FlvUrlForQuality returns the .flv stream URL for the given quality (uhd, hd, ld, sd).
// If no matching URL is found, it returns the room's default StreamUrl.
func (room Room) FlvUrlForQuality(quality string) string {
return room.urlForQuality(room.FlvStreamUrls, quality)
}
// HlsUrlForQuality returns the .m3u8 stream URL for the given quality (uhd, hd, ld, sd).
// If no matching URL is found, it returns the room's default StreamUrl.
func (room Room) HlsUrlForQuality(quality string) string {
return room.urlForQuality(room.HlsStreamUrls, quality)
}
func (room Room) urlForQuality(urls map[string]string, quality string) string {
quality = strings.ToLower(quality)
for key, value := range urls {
switch quality {
case "uhd":
if strings.Contains(key, "FULL_HD") || strings.Contains(value, "_uhd") {
return value
}
case "hd":
if strings.Contains(value, "_hd") {
return value
}
case "ld":
if strings.Contains(value, "_ld") {
return value
}
case "sd":
if strings.Contains(value, "_sd") {
return value
}
default:
return room.StreamUrl
}
}
return room.StreamUrl
}
// GetRoomsByCategory gets top 15 Douyin live stream rooms of a category.
func GetRoomsByCategory(ctx context.Context, categoryId string) ([]Room, error) {
data, err := getCategoryPageData(ctx, categoryId, "roomsData")
if err != nil {
return nil, err
}
roomsData := data[0]
var cat dyliveCategory
if err := getDataInArray(roomsData, &cat); err != nil {
return nil, err
}
var rooms []Room
for _, room := range cat.RoomsData.Data {
p := cat.PartitionData.Partition
c := cat.PartitionData.SelectPartition
var count string
if room.Room.RoomViewStats.DisplayValue > 0 {
count = strconv.Itoa(room.Room.RoomViewStats.DisplayValue)
} else {
count = room.Room.Stats.UserCountStr
}
rooms = append(rooms, Room{
Id: room.Room.IdStr,
DouyinId: room.WebRid,
StatusCode: RoomStatusLiveOn,
Name: room.Room.Title,
CoverUrl: room.Cover,
WebUrl: "https://live.douyin.com/" + room.WebRid,
StreamUrl: room.StreamSrc,
FlvStreamUrls: room.Room.StreamUrl.FlvPullUrl,
HlsStreamUrls: room.Room.StreamUrl.HlsPullUrlMap,
CurrentUsersCount: count,
TotalUsersCount: room.Room.Stats.TotalUserStr,
Category: &Category{
Id: fmt.Sprintf("%d_%s", p.Type, p.IDStr),
Name: p.Title,
Categories: []Category{
{
Id: fmt.Sprintf("%d_%s_%d_%s", p.Type, p.IDStr, c.Type, c.IDStr),
Name: c.Title,
},
},
},
User: User{
Name: room.Room.Owner.Nickname,
Picture: room.Avatar,
},
})
}
return rooms, nil
}
func getCategoryPageData(ctx context.Context, id string, filters ...string) ([]string, error) {
req, err := http.NewRequestWithContext(ctx, "GET", "https://live.douyin.com/category/"+id, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", userAgent)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
parts := getDataInHtml(string(b))
var output []string
for _, filter := range filters {
var ret string
for _, part := range parts {
if strings.Contains(part, filter) {
ret = part
break
}
}
output = append(output, ret)
}
return output, nil
}
type (
dyliveRoomDetails struct {
State struct {
RoomStore struct {
RoomInfo struct {
Room dyliveRoom `json:"room"`
WebRid string `json:"web_rid"`
Anchor dyUser `json:"anchor"`
} `json:"roomInfo"`
} `json:"roomStore"`
} `json:"state"`
}
)
// GetRoom get live stream room details by Douyin ID (抖音号)
func GetRoom(ctx context.Context, douyinId string) (*Room, error) {
data, err := getLivePageData(ctx, douyinId, "flv_pull_url")
if err != nil {
return nil, err
}
if len(data) == 0 || data[0] == "" {
return nil, fmt.Errorf("DouyinId %s does not exist", douyinId)
}
roomsData := data[0]
var page dyliveRoomDetails
if err := getDataInArray(roomsData, &page); err != nil {
return nil, err
}
info := page.State.RoomStore.RoomInfo
var cover string
if len(info.Room.Cover.UrlList) > 0 {
cover = info.Room.Cover.UrlList[0]
}
streamUrl := info.Room.StreamUrl.FlvPullUrl[info.Room.StreamUrl.DefaultResolution]
var count string
if info.Room.RoomViewStats.DisplayValue > 0 {
count = strconv.Itoa(info.Room.RoomViewStats.DisplayValue)
} else {
count = info.Room.Stats.UserCountStr
}
userName := info.Room.Owner.Nickname
if userName == "" {
userName = info.Anchor.Nickname
}
var userPicture string
if len(info.Room.Owner.AvatarThumb.UrlList) > 0 {
userPicture = info.Room.Owner.AvatarThumb.UrlList[0]
} else if len(info.Anchor.AvatarThumb.UrlList) > 0 {
userPicture = info.Anchor.AvatarThumb.UrlList[0]
}
return &Room{
Id: info.Room.IdStr,
DouyinId: info.WebRid,
StatusCode: info.Room.Status,
Name: info.Room.Title,
CoverUrl: cover,
WebUrl: "https://live.douyin.com/" + info.WebRid,
StreamUrl: streamUrl,
FlvStreamUrls: info.Room.StreamUrl.FlvPullUrl,
HlsStreamUrls: info.Room.StreamUrl.HlsPullUrlMap,
CurrentUsersCount: count,
TotalUsersCount: info.Room.Stats.TotalUserStr,
User: User{
Name: userName,
Picture: userPicture,
},
}, nil
}
func getLivePageData(ctx context.Context, douyinId string, filters ...string) ([]string, error) {
req, err := http.NewRequestWithContext(ctx, "GET", "https://live.douyin.com/"+douyinId, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Cookie", "__ac_nonce=064caded4009deafd8b89")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
parts := getDataInHtml(string(b))
var output []string
for _, filter := range filters {
var ret string
for _, part := range parts {
if strings.Contains(part, filter) {
ret = part
break
}
}
output = append(output, ret)
}
return output, nil
}
func getDataInHtml(input string) (output []string) {
const funcName = "__pace_f"
const endTag = "</script>"
var parts []string
for {
a := strings.Index(input, funcName)
if a == -1 {
break
}
input = input[a+len(funcName):]
b := strings.Index(input, `"`)
if b < 0 {
continue
}
input = input[b+1:]
b = strings.Index(input, endTag)
if b < 0 {
continue
}
b = strings.LastIndex(input[:b], `"`)
if b < 0 {
continue
}
var ret string
if json.Unmarshal([]byte(`"`+input[:b]+`"`), &ret) != nil {
continue
}
parts = append(parts, ret)
}
parts = strings.Split(strings.Join(parts, "\n"), "\n")
for _, part := range parts {
a := strings.IndexAny(part, "[{")
if a == -1 {
continue
}
b := strings.LastIndexAny(part, "}]")
if b == -1 {
continue
}
output = append(output, part[a:b+1])
}
return
}
func getDataInArray(input string, target interface{}) error {
var array []interface{}
if err := json.Unmarshal([]byte(input), &array); err != nil {
return err
}
for _, element := range array {
switch v := element.(type) {
case map[string]interface{}:
jsonStr, err := json.Marshal(v)
if err != nil {
continue
}
return json.Unmarshal(jsonStr, target)
}
}
return nil
}