-
Notifications
You must be signed in to change notification settings - Fork 0
/
bilibili.go
1847 lines (1768 loc) · 52.9 KB
/
bilibili.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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"NothinBot/Bilibili/Wbi"
"NothinBot/EasyBot"
"NothinBot/TimeLayout"
"encoding/json"
"fmt"
"math"
"os"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/PuerkitoBio/goquery"
"github.com/moxcomic/bcutasr"
"github.com/moxcomic/ihttp"
log "github.com/sirupsen/logrus"
"github.com/ysmood/gson"
)
type BiliApiResp struct {
Code int `json:"code"`
Message string `json:"message"`
Ttl int `json:"ttl"`
Data map[string]any `json:"data"`
}
type liveInfo struct {
live *danmaku
uid int
roomid int
state int
time int64
}
type push struct {
userID []int
groupID []int
}
type parseHistory struct {
parse string
time int64
}
var (
biliLinkRegexp = struct {
SHORT string
DYNAMIC string
ARCHIVEav string
ARCHIVEbv string
ARTICLE string
MUSIC string
SPACE string
LIVE string
}{
SHORT: `((让岁己)?(总结一下\s?)|我要看\s?)?.*(b23|acg)\.tv\\?/(BV[1-9A-HJ-NP-Za-km-z]{10}|av[0-9]{1,10}|[0-9A-Za-z]{7})`, //暂时应该只有7位 也有可能是av/bv号
DYNAMIC: `(让岁己)?(总结一下\s?)?.*(t.bilibili.com|dynamic|opus)\\?/([0-9]{18,19})`, //应该不会有17位的,可能要有19位
ARCHIVEav: `((让岁己)?(总结一下\s?)|我要看\s?)?.*video\\?/av([0-9]{1,10})`, //9位 预留10
ARCHIVEbv: `((让岁己)?(总结一下\s?)|我要看\s?)?.*video\\?/(BV[1-9A-HJ-NP-Za-km-z]{10})`, //恒定BV + 10位base58
ARTICLE: `(让岁己)?(总结一下\s?)?.*(read\\?/cv|read\\?/mobile\\?/)([0-9]{1,9})`, //8位 预留9
MUSIC: `(让岁己)?(总结一下\s?)?.*audio\\?/au([0-9]{1,10})`, //
SPACE: `(让岁己)?(总结一下\s?)?.*space\.bilibili\.com\\?/([0-9]{1,16})`, //新uid 16位
LIVE: `(让岁己)?(总结一下\s?)?.*live\.bilibili\.com\\?/([0-9]{1,9})`, //8位 预留9
}
liveState = struct {
UNKNOWN int
OFFLINE int
ONLINE int
ROTATE int
}{
UNKNOWN: -1,
OFFLINE: 0,
ONLINE: 1,
ROTATE: 2,
}
rmTitle = strings.NewReplacer(
"概述", "", "要点", "", "由", "", "总结:", "", "总结(原文长度超过1500字符,输入经过去尾):", "",
"ChatGLM2-6B", "", "ERNIE_Bot", "", "ERNIE_Bot_turbo", "", "BLOOMZ_7B", "", "Llama_2_7b", "", "Llama_2_13b", "",
"Llama_2_70b", "",
)
// cookie = ""
cookieUid = 0
cookieBuvid = "91F87C44-8B65-64C4-296C-B102F459941CF05635infoc" //扫码拿不到 先写着
cookieValidity = false
tempDir = "./bilibili_temp/"
summaryBackend = ""
dynamicCheckDuration time.Duration
dynamicHistrory = make(map[string]string)
pushWait sync.WaitGroup
liveList = make(map[int]liveInfo) // roomid : liveInfo
archiveVideoTable = make(map[int]*archiveVideo) //av:
archiveAudioTable = make(map[int]*archiveAudio) //av:
archiveSubtitleTable = make(map[int]*archiveSubtitle) //av:
articleTextTable = make(map[int]*articleText) //cv:
groupParseHistory = make(map[int]parseHistory) //group:
)
var everyBiliLinkRegexp = func() (everyBiliLinkRegexp string) {
structValue := reflect.ValueOf(biliLinkRegexp)
for i := 0; i < structValue.NumField(); i++ {
field := structValue.Field(i)
if everyBiliLinkRegexp != "" {
everyBiliLinkRegexp += "|"
}
everyBiliLinkRegexp += field.Interface().(string)
}
return
}()
const standardLength = len("BV1vh4y1U71j")
// bv转av
func bv2av(bv string) (av int) {
if length := len(bv); length != standardLength {
log.Warn("[bv2av] 输入了错误的bv号: ", bv, " (len: ", length, ")")
return 0
}
table := "fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF"
tr := make(map[byte]int)
for i := 0; i < 58; i++ {
tr[table[i]] = i
}
s := []int{11, 10, 3, 8, 4, 6}
xor := 177451812
add := 8728348608
r := 0
for i := 0; i < 6; i++ {
r += tr[bv[s[i]]] * int(math.Pow(58, float64(i)))
}
av = (r - add) ^ xor
log.Debug("[Bilibili] ", bv, " 转换到 av", av)
return
}
func CallBiliApi(url string, querys map[string]any) (resp *BiliApiResp, headers map[string]string, err error) {
resp = &BiliApiResp{}
i := ihttp.New().WithUrl(url).
WithHeaders(iheaders).WithAddQuerys(querys).Get()
body, err := i.ToBytes()
if err != nil {
log.Error("[Bilibili] CallBiliApi() ihttp ToBytes error: ", err)
return
}
header, err := i.ToHeader()
if err != nil {
log.Error("[Bilibili] CallBiliApi() ihttp ToHeader error: ", err)
return
}
err = json.Unmarshal(body, resp)
if err != nil {
log.Error(
"[Bilibili] CallBiliApi() unmarshal error: ", err,
"\n data: ", string(body),
"\n using gson: ", gson.New(body).JSON("", ""),
)
return
}
headers = make(map[string]string)
for k, v := range header {
headers[k] = strings.Join(v, "; ")
}
return
}
// 获取动态数据.Get("data.item")
func getDynamicJson(dynamicID string) gson.JSON {
dynamicJson, err := ihttp.New().WithUrl("https://api.bilibili.com/x/polymer/web-dynamic/v1/detail").
WithAddQuery("id", dynamicID).WithHeaders(iheaders).WithCookie(biliIdentity.Cookie).
Get().ToGson()
if err != nil {
log.Error("[bilibili] getDynamicJson().ihttp请求错误: ", err)
}
log.Trace("[bilibili] rawDynamicJson: ", dynamicJson.JSON("", ""))
if dynamicJson.Get("code").Int() != 0 {
log.Error("[parse] 动态 ", dynamicID, " 信息获取错误: ", dynamicJson.JSON("", ""))
}
return dynamicJson
}
// 获取投票数据.Get("data.info")
func getVoteJson(voteid int) gson.JSON {
voteJson, err := ihttp.New().WithUrl("https://api.vc.bilibili.com/vote_svr/v1/vote_svr/vote_info").
WithAddQuerys(map[string]any{"vote_id": voteid}).WithHeaders(iheaders).WithCookie(biliIdentity.Cookie).
Get().ToGson()
if err != nil {
log.Error("[bilibili] getVoteJson().ihttp请求错误: ", err)
}
log.Trace("[bilibili] rawVoteJson: ", voteJson.JSON("", ""))
if voteJson.Get("code").Int() != 0 {
log.Error("[parse] 投票 ", voteid, " 信息获取错误: ", voteJson.JSON("", ""))
}
return voteJson
}
// 格式化动态, 主动态.Get("data.item"), 转发原动态.Get("data.item.orig")
func formatDynamic(g gson.JSON) string {
dynamic := g.Get("modules.module_dynamic") //动态主体
id := g.Get("id_str").Str() //动态id
uid := g.Get("modules.module_author.mid").Int() //发布者uid
name := g.Get("modules.module_author.name").Str() //发布者用户名
action := g.Get("modules.module_author.pub_action").Str() //"投稿了视频"/"发布了动态视频"/"投稿了文章"/"直播了"
topic := func(exist bool) (topic string) { //话题
if exist {
topic = "\n#" + dynamic.Get("topic.name").Str() + "#"
}
return
}(!dynamic.Get("topic.name").Nil())
addition := func(additionalType string) (addtion string) { //子项内容
switch additionalType {
case "ADDITIONAL_TYPE_RESERVE": //预约
reserveJson := dynamic.Get("additional.reserve")
addtion = fmt.Sprintf(
"\n%s\n%s\n%s",
reserveJson.Get("title").Str(),
reserveJson.Get("desc1.text").Str(), //"预计xxx发布"
reserveJson.Get("desc2.text").Str(),
) //"xx人预约"/"xx观看"
case "ADDITIONAL_TYPE_VOTE": //投票
voteJson := getVoteJson(dynamic.Get("additional.vote.vote_id").Int()).Get("data.info")
name := voteJson.Get("name").Str() //发起者
title := voteJson.Get("title").Str() //标题
desc := descTrunc(voteJson.Get("desc").Str()) //简介
startTime, endTime := func(timeS1 int64, timeS2 int64) (string, string) {
time1 := time.Unix(timeS1, 0)
time2 := time.Unix(timeS2, 0)
timeNow := time.Unix(time.Now().Unix(), 0)
if time2.Format("2006") == timeNow.Format("2006") { //结束日期同年 不显示年份
if time2.Format("01") == timeNow.Format("01") { //结束日期同月 不显示月份
return time1.Format(TimeLayout.M24), time2.Format(TimeLayout.S24)
}
return time1.Format(TimeLayout.M24), time2.Format(TimeLayout.M24)
}
return time1.Format(TimeLayout.L24), time2.Format(TimeLayout.L24)
}(int64(voteJson.Get("starttime").Int()), int64(voteJson.Get("endtime").Int()))
c_cnt := voteJson.Get("choice_cnt").Int() //最大选择数
cnt := voteJson.Get("cnt").Int() //参与数
option := func(options []gson.JSON) (option string) { //选项
for _, j := range options {
if !j.Get("cnt").Nil() {
option += fmt.Sprintf(
"\n%d. %s %d人选择",
j.Get("idx").Int(), //序号
j.Get("desc").Str(), //描述
j.Get("cnt").Int(),
) //选择数
} else {
option += fmt.Sprintf(
"\n%d. %s",
j.Get("idx").Int(), //序号
j.Get("desc").Str(),
) //描述
//cookie失效时拿不到选择数
}
}
return
}(voteJson.Get("options").Arr())
addtion = fmt.Sprintf(
`
%s发起的投票:%s%s
%s - %s
最多选%d项 %d人参与%s`,
name, title, desc,
startTime, endTime,
c_cnt, cnt, option,
)
case "ADDITIONAL_TYPE_UGC": //评论同时转发
url := dynamic.Get("additional.ugc.jump_url").Str()
id, kind, _, _, _ := extractBiliLink(url)
addtion = "\n\n转发的视频:\n" + parseAndFormatBiliLink(nil, id, kind, false, false, false)
}
return
}(dynamic.Get("additional.type").Str())
dynamicType := g.Get("type").Str() //动态类型
log.Debug("[bilibili] 动态类型: ", dynamicType)
switch dynamicType {
case "DYNAMIC_TYPE_FORWARD": //转发
text := dynamic.Get("desc.text").Str() //正文
return fmt.Sprintf(
`t.bilibili.com/%s
%s:转发动态%s
%s
%s`,
id,
name, topic,
text,
formatDynamic(g.Get("orig")),
)
case "DYNAMIC_TYPE_NONE": //转发的动态已删除
return dynamic.Get("major.none.tips").Str() //错误提示: "源动态已被作者删除"
case "DYNAMIC_TYPE_WORD": //纯文字
text := dynamic.Get("desc.text").Str() //正文
return fmt.Sprintf(
`t.bilibili.com/%s
%s:%s
%s%s`,
id,
name, topic,
text, addition,
)
case "DYNAMIC_TYPE_DRAW": //图文
draw := dynamic.Get("major.draw")
images := func(items []gson.JSON) (images string) { //图片
for _, item := range items {
images += fmt.Sprint("[CQ:image,file=", item.Get("src").Str(), "]")
}
return
}(draw.Get("items").Arr())
text := dynamic.Get("desc.text").Str() //正文
return fmt.Sprintf(
`t.bilibili.com/%s
%s:%s
%s
%s%s`,
id,
name, topic,
text,
images, addition,
)
case "DYNAMIC_TYPE_AV": //视频
archive := dynamic.Get("major.archive")
text := func(exist bool, text string) string { //正文
if text == archive.Get("desc").Str() { //如果正文和简介相同, 不显示正文
return ""
}
if exist {
return "\n" + text
}
return ""
}(!dynamic.Get("desc.text").Nil(), dynamic.Get("desc.text").Str())
aid, _ := strconv.Atoi(archive.Get("aid").Str()) //av号数字
content := func() (content string) {
g, h := getArchiveJson(aid)
if g.Get("code").Int() != 0 {
return fmt.Sprintf("[NothingBot] [ERROR] [parse] 视频av%s信息获取错误: code%d", id, g.Get("code").Int())
}
content = formatArchive(g.Get("data"), h.Get("data"))
return
}()
return fmt.Sprintf(
`t.bilibili.com/%s
%s:%s%s%s
%s`,
id,
name, action, topic, text,
content,
)
case "DYNAMIC_TYPE_ARTICLE": //文章
article := dynamic.Get("major.article")
cvid := article.Get("id").Int() //cv号数字
content := func() (content string) {
g := getArticleJson(cvid)
if g.Get("code").Int() != 0 {
return fmt.Sprintf("[NothingBot] [ERROR] [parse] 专栏cv%s信息获取错误: code%d", id, g.Get("code").Int())
}
return formatArticle(g.Get("data"), cvid)
}()
return fmt.Sprintf(
`t.bilibili.com/%s
%s:%s%s
%s`,
id,
name, action, topic,
content,
)
case "DYNAMIC_TYPE_MUSIC":
music := dynamic.Get("major.music")
sid := music.Get("id").Int()
content := func() (content string) {
g, h, i := getMusicJson(sid)
if g.Get("code").Int() != 0 || h.Get("code").Int() != 0 || i.Get("code").Int() != 0 {
return fmt.Sprintf("[NothingBot] [ERROR] [parse] 专栏cv%s信息获取错误: code%d", id, g.Get("code").Int())
}
return formatMusic(g.Get("data"), h.Get("data"), i.Get("data"))
}()
return fmt.Sprintf(
`t.bilibili.com/%s
%s:%s%s
%s`,
id,
name, action, topic,
content,
)
case "DYNAMIC_TYPE_LIVE_RCMD": //直播(动态流拿不到更新)
return fmt.Sprintf(
`t.bilibili.com/%s
%s:%s
%s`,
id,
name, action,
formatLive(getRoomJsonUID(uid)),
)
case "DYNAMIC_TYPE_COMMON_SQUARE": //应用装扮同步动态
log.Info("[bilibili] 应用装扮同步动态: ", dynamic.JSON("", ""))
return fmt.Sprintf(
`t.bilibili.com/%s
%s:%s%s%s
这是一条应用装扮同步动态:%s`,
id,
name, action, topic, addition,
dynamicType,
)
default:
log.Error("[bilibili] 未知的动态类型: ", dynamicType, id)
bot.Log2SU.Error(fmt.Sprint("[bilibili] 未知的动态类型:", dynamicType, " (", id, ")"))
return fmt.Sprintf(
`t.bilibili.com/%s
%s:
未知的动态类型:%s`,
id,
name,
dynamicType,
)
}
}
// 获取官方AI总结
func getArchiveSummary(aid int) (summary string, err error) {
cid := getCid(aid)
signedUrl, _ := Wbi.Sign(
fmt.Sprintf(
"https://api.bilibili.com/x/web-interface/view/conclusion/get?aid=%d&cid=%d", aid, cid,
),
)
videoSummary, err := ihttp.New().WithUrl(signedUrl).WithHeaders(iheaders).Get().ToGson()
if err != nil {
return
}
// 大总结
summary = videoSummary.Get("data.model_result.summary").Str()
// 大纲
outlines := videoSummary.Get("data.model_result.outline").Arr()
if summary == "" && len(outlines) == 0 {
return "", nil
}
for _, outline := range outlines {
summary += "\n● " + outline.Get("title").Str()
// 小节
for _, partOutline := range outline.Get("part_outline").Arr() {
timestamp := partOutline.Get("timestamp").Int()
content := partOutline.Get("content").Str()
summary += fmt.Sprintf(
"\n[%s] %s",
formatTimeSimple(int64(timestamp)), content,
)
}
}
return
}
// av号获取视频数据.Get("data"))
func getArchiveJson[T int | string](aid T) (archiveJson gson.JSON, stateJson gson.JSON) {
archiveJson, err := ihttp.New().WithUrl("https://api.bilibili.com/x/web-interface/view").
WithAddQuerys(map[string]any{"aid": aid}).WithHeaders(iheaders).
Get().ToGson()
if err != nil {
log.Error("[bilibili] getArchiveJsonA().ihttp请求错误: ", err)
}
log.Trace("[bilibili] rawArchiveJsonA: ", archiveJson.JSON("", ""))
if archiveJson.Get("code").Int() != 0 {
log.Error("[parse] 视频 ", aid, " 信息获取错误: ", archiveJson.JSON("", ""))
}
cid := archiveJson.Get("data.cid").Int()
stateJson, err = ihttp.New().WithUrl("https://api.bilibili.com/x/player/online/total").
WithAddQuerys(map[string]any{"aid": aid, "cid": cid}).WithHeaders(iheaders).
Get().ToGson()
if err != nil {
log.Error("[bilibili] getArchiveJsonA().statJson.ihttp请求错误: ", err)
}
log.Trace("[bilibili] rawArchiveJsonA.state: ", archiveJson.JSON("", ""))
if stateJson.Get("code").Int() != 0 {
log.Error("[parse] 视频 ", aid, " 在线人数状态获取错误: ", stateJson.JSON("", ""))
}
return
}
// bv号获取视频数据.Get("data"))
func getArchiveJsonB(bvid string) (archiveJson gson.JSON, stateJson gson.JSON) {
archiveJson, err := ihttp.New().WithUrl("https://api.bilibili.com/x/web-interface/view").
WithAddQuery("bvid", bvid).WithHeaders(iheaders).
Get().ToGson()
if err != nil {
log.Error("[bilibili] getArchiveJsonB().ihttp请求错误: ", err)
}
log.Trace("[bilibili] rawVideoJsonB: ", archiveJson.JSON("", ""))
if archiveJson.Get("code").Int() != 0 {
log.Error("[parse] 视频 ", bvid, " 信息获取错误: ", archiveJson.JSON("", ""))
}
cid := archiveJson.Get("data.cid").Int()
stateJson, err = ihttp.New().WithUrl("https://api.bilibili.com/x/player/online/total").
WithAddQuerys(map[string]any{"bvid": bvid, "cid": cid}).WithHeaders(iheaders).
Get().ToGson()
if err != nil {
log.Error("[bilibili] getArchiveJsonB().statJson.ihttp请求错误: ", err)
}
log.Trace("[bilibili] getArchiveJsonB.statJson: ", archiveJson.JSON("", ""))
if stateJson.Get("code").Int() != 0 {
log.Error("[parse] 视频 ", bvid, " 在线人数状态获取错误: ", stateJson.JSON("", ""))
}
return
}
// 读取缓存
func initCache() {
_ = checkDir(tempDir)
err := filepath.Walk(
tempDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
log.Error("访问路径 ", path, " 时发生错误: ", err.Error())
return err
}
if info.IsDir() {
return nil
}
fileDataRaw, err := os.ReadFile(path)
if err != nil {
log.Error("[bilibili] read cache err: ", err.Error())
}
g := gson.New(fileDataRaw)
fileData := []byte(g.JSON("", ""))
switch info.Name()[:2] { //文件名前两个字母
case "av":
as := &archiveSubtitle{}
err = json.Unmarshal(fileData, as)
if err != nil {
log.Error(
"[NothingBot] 反序列化出错(json.Unmarshal(fileData, as)), err: ", err,
"\n respByte: ", string(fileData),
"\n Unmarshal by gson: ", gson.New(fileData).JSON("", ""),
)
break
}
as.marshal()
archiveSubtitleTable[as.Aid] = as
if !as.IsNative {
aacPath := fmt.Sprint("av", as.Aid, "_c", as.Cid, ".aac")
_, err := os.Stat(aacPath)
if err == nil { //存在已下载的音频文件
archiveAudioTable[as.Aid] = &archiveAudio{
aid: as.Aid,
cid: as.Cid,
localPath: aacPath,
}
}
}
case "cv":
at := &articleText{}
err = json.Unmarshal(fileData, at)
if err != nil {
log.Error(
"[NothingBot] 反序列化出错(json.Unmarshal(fileData, at)), err: ", err,
"\n respByte: ", string(fileData),
"\n Unmarshal by gson: ", gson.New(fileData).JSON("", ""),
)
break
}
at.marshal()
articleTextTable[at.Cvid] = at
}
return nil
},
)
if err != nil {
log.Error("遍历缓存时发生错误: ", err.Error())
}
}
var videoCodec = struct {
avc int
hevc int
av1 int
}{
avc: 7,
hevc: 12,
av1: 13,
}
var videoQual = struct {
js240 int
lc360 int
qx480 int
gq720 int
gzl720p60 int
gq1080 int
gml1080 int
gzl1080p60 int
cq4K int
zcsHDR int
dolby int
cgq8K int
}{
js240: 6,
lc360: 16,
qx480: 32,
gq720: 64,
gzl720p60: 74,
gq1080: 80,
gml1080: 112,
gzl1080p60: 116,
cq4K: 120,
zcsHDR: 125,
dolby: 126,
cgq8K: 127,
}
type archiveVideo struct {
aid int
cid int
hasAudio bool //是否带音频
path string
}
// 获取视频流(mp4)
func getVideoMp4(aid int, qual int) *archiveVideo {
if cacheVi, has := archiveVideoTable[aid]; has {
return cacheVi
}
checkDir(tempDir)
cid := getCid(aid)
url := getVideoUrlMp4(aid, cid, qual)
path := ""
if lor := gocqIsLocalOrRemote(); lor == "local" { //gocq在本地时通过bot下载
fileName := fmt.Sprint("av", aid, "_c", cid, "_qn", qual, ".mp4")
path := tempDir + fileName
videoByte, err := ihttp.New().WithUrl(url).
WithHeaders(iheaders).
Get().ToBytes()
if err != nil {
log.Error("[bilibili] 视频(mp4)下载失败 err: ", err)
return nil
}
err = os.WriteFile(path, videoByte, 0664)
if err != nil {
log.Error("[bilibili] 视频(mp4)写入本地失败 err: ", err)
}
log.Debug("[bilibili] local path: ", path, " len(videoByte): ", len(videoByte))
} else if lor == "remote" { //否则调用远程下载
p, err := bot.DownloadFile(url, 1, iheaders)
path = p
if err != nil {
log.Error("[bilibili] 远程视频(mp4)下载失败 err: ", err)
return nil
} else {
log.Debug("[bilibili] remote path: ", path)
}
}
return &archiveVideo{
aid: aid,
cid: cid,
hasAudio: true,
path: path,
}
}
type videoUrls map[int]map[int]string //qual:codec:
// 获取视频流(dash)链接
func getVideoUrlDash(aid int, cid int) (urls videoUrls) {
g, err := ihttp.New().WithUrl(`https://api.bilibili.com/x/player/playurl`).
WithHeaders(iheaders).WithCookie(biliIdentity.Cookie).
WithAddQuerys(
map[string]any{
"avid": aid,
"cid": cid,
"fnval": 16, //dash
},
).
Get().ToGson()
if err != nil {
log.Error("[bilibili] 获取视频流(dash)链接失败 err: ", err)
return
}
if g.Get("code").Int() != 0 {
log.Error("[bilibili] 获取视频流(dash)链接失败 g: ", g.JSON("", ""))
return
}
urls = make(videoUrls)
for _, h := range g.Get("data.dash.video").Arr() {
qualId := h.Get("id").Int()
urls[qualId] = make(map[int]string)
codecId := h.Get("codecid").Int()
baseUrl := h.Get("baseUrl").Str()
urls[qualId][codecId] = baseUrl
}
return
}
// 获取视频流(mp4)链接, avc only
func getVideoUrlMp4(aid int, cid int, qual int) (url string) {
g, err := ihttp.New().WithUrl(`https://api.bilibili.com/x/player/playurl`).
WithHeaders(iheaders).WithCookie(biliIdentity.Cookie).
WithAddQuerys(
map[string]any{
"avid": aid,
"cid": cid,
"qn": qual,
"fnval": 1, //mp4
},
).
Get().ToGson()
if err != nil {
log.Error("[bilibili] 获取视频流(mp4)链接失败 err: ", err)
return
}
if g.Get("code").Int() != 0 {
log.Error("[bilibili] 获取视频流(mp4)链接失败 g: ", g.JSON("", ""))
return
}
url = g.Get("data.durl").Arr()[0].Get("url").Str()
if len(url) < 16 {
log.Error("[bilibili] 获取视频流(mp4)链接失败 url: ", url, " g: ", g.JSON("", ""))
return ""
}
return
}
var audioQual = struct {
low int //64k
mid int //132k
high int //192k
dolby int
HiRes int
}{
low: 30216,
mid: 30232,
high: 30280,
dolby: 30250,
HiRes: 30251,
}
type archiveAudio struct {
aid int
cid int
localPath string
}
// 获取音频流
func getAudio(aid int, cid int) *archiveAudio {
if cacheAu, has := archiveAudioTable[aid]; has {
return cacheAu
}
checkDir(tempDir)
url := getAudioUrl(aid, cid).high()
fileName := fmt.Sprint("av", aid, "_c", cid, ".aac")
localPath := tempDir + fileName
audioByte, err := ihttp.New().WithUrl(url).
WithHeaders(iheaders).
Get().ToBytes()
if err != nil {
log.Error("[bilibili] 音频下载失败 err: ", err)
return nil
} else {
log.Debug("[bilibili] len(audioByte): ", len(audioByte))
}
os.WriteFile(localPath, audioByte, 0664)
return &archiveAudio{
aid: aid,
cid: cid,
localPath: localPath,
}
}
type audioUrls map[int]string
// 获取音频流链接
func getAudioUrl(aid int, cid int) (urls audioUrls) {
g, err := ihttp.New().WithUrl(`https://api.bilibili.com/x/player/playurl`).
WithHeaders(iheaders).WithCookie(biliIdentity.Cookie).
WithAddQuerys(
map[string]any{
"avid": aid,
"cid": cid,
"fnval": 16, //dash
},
).
Get().ToGson()
if err != nil {
log.Error("[bilibili] 获取音频流链接失败 err: ", err)
return
}
if g.Get("code").Int() != 0 {
log.Error("[bilibili] 获取音频流链接失败 g: ", g.JSON("", ""))
return
}
urls = make(audioUrls)
for _, h := range g.Get("data.dash.audio").Arr() {
qualId := h.Get("id").Int()
baseUrl := h.Get("baseUrl").Str()
urls[qualId] = baseUrl
}
return
}
// 尽量获取192k
func (a audioUrls) high() (bestUrl string) {
urlHigh, hasHigh := a[audioQual.high]
urlMid, hasMid := a[audioQual.mid]
urlLow, hasLow := a[audioQual.low]
switch {
case hasHigh:
bestUrl = urlHigh
case hasMid:
bestUrl = urlMid
case hasLow:
bestUrl = urlLow
default:
for _, j := range a {
bestUrl = j
break
}
}
log.Trace("[bilibili] bestUrl: ", bestUrl)
return
}
type archiveSubtitle struct {
Aid int `json:"aid"`
Cid int `json:"cid"`
Up string `json:"up"`
Title string `json:"title"`
Result string `json:"result"` //gson.JSON.JSON("","")
seq string //不存本地
IsNative bool `json:"is_native"` //真为原生字幕,假为转录字幕
}
// 获取视频原生字幕/缓存字幕, 传标题进来省得再请求一遍
func getSubtitle(aid int, up string, title string) *archiveSubtitle {
if cacheAS, has := archiveSubtitleTable[aid]; has && cacheAS != nil {
log.Info("[bilibili] 调用缓存: av", aid)
return cacheAS
}
cid := getCid(aid)
if cid == 0 {
log.Error("[bilibili] cid == 0")
return nil
}
subtitleUrl := getSubtitleUrl(aid, cid)
log.Trace("[bilibili] subtitleUrl: ", subtitleUrl)
if subtitleUrl == "" {
log.Error("[bilibili] subtitleUrl == \"\"")
return nil
}
result, err := ihttp.New().WithUrl("https:" + subtitleUrl).
WithHeaders(iheaders).
Get().ToString()
if err != nil {
log.Error("[bilibili] ihttp err: ", err)
return nil
}
as := &archiveSubtitle{
Aid: aid,
Cid: cid,
Up: up,
Title: title,
Result: result,
IsNative: true,
}
checkDir(tempDir)
asByte, err := json.Marshal(as)
if err != nil {
log.Error("[bilibili] Cache Marshal err: ", err.Error())
}
localPath := fmt.Sprint(tempDir, "av", aid, "_c", cid, ".json")
os.WriteFile(localPath, asByte, 0644) //缓存
as.nativeMarshal()
return as
}
// 调用必剪转录视频字幕
func bcutSubtitle(aid int, up string, title string) *archiveSubtitle {
checkDir(tempDir)
cid := getCid(aid)
if cid == 0 {
log.Error("[bilibili] cid == 0")
return nil
}
audio := getAudio(aid, cid)
resp, err := bcutasr.New().Parse(audio.localPath)
if err != nil {
panic(err)
}
log.Debug("[bilibili] bcutASR code: ", resp.GetInt("code"))
result := resp.GetString("data.result")
as := &archiveSubtitle{
Aid: aid,
Cid: cid,
Up: up,
Title: title,
Result: result,
IsNative: false,
}
checkDir(tempDir)
asByte, err := json.Marshal(as)
if err != nil {
log.Error("[bilibili] Cache Marshal err: ", err.Error())
}
localPath := fmt.Sprint(tempDir, "av", aid, "_c", cid, ".json")
os.WriteFile(localPath, asByte, 0644) //缓存
as.bcutMarshal()
return as
}
// 序列化
func (as *archiveSubtitle) marshal() *archiveSubtitle {
if as.IsNative {
as.nativeMarshal()
} else {
as.bcutMarshal()
}
return as
}
// 原生字幕序列化
func (as *archiveSubtitle) nativeMarshal() *archiveSubtitle {
as.seq = func() (seq string) {
resultJson := gson.NewFrom(as.Result)
for _, body := range resultJson.Get("body").Arr() {
if seq != "" {
seq += "\n"
}
seq += body.Get("content").Str()
}
return
}()
return as
}
// 必剪转录文本序列化
func (as *archiveSubtitle) bcutMarshal() *archiveSubtitle {
as.seq = func() (seq string) {
resultJson := gson.NewFrom(as.Result)
for _, sent := range resultJson.Get("utterances").Arr() {
if seq != "" {
seq += "\n"
}
seq += sent.Get("transcript").Str()
}
return
}()
return as
}
// 获取p1的cid
func getCid(aid int) (cid int) {
pagelist, err := ihttp.New().WithUrl("https://api.bilibili.com/x/player/pagelist").
WithAddQuerys(map[string]any{"aid": aid}).WithHeaders(iheaders).
Get().ToGson()
if err == nil && pagelist.Get("code").Int() == 0 {
cid = pagelist.Get("data.0.cid").Int()
} else {
log.Error("[bilibili] cid获取错误 err: ", err, " code: ", pagelist.Get("code").Int())
}
return
}
// 获取视频字幕链接
func getSubtitleUrl(aid int, cid int) (url string) {
player, err := ihttp.New().WithUrl("https://api.bilibili.com/x/player/v2").
WithAddQuerys(map[string]any{"aid": aid, "cid": cid}).WithHeaders(iheaders).WithCookie(biliIdentity.Cookie).
Get().ToGson()
if err == nil || player.Get("code").Int() == 0 {
subtitles := player.Get("data.subtitle.subtitles").Arr()
if len(subtitles) == 0 { //没有字幕
log.Trace("[bilibili] len(subtitles) == 0")
log.Trace("[bilibili] player: ", player.JSON("", ""))
return
}
subtitlesMap := make(map[string]string) // "lan":"subtitle_url"
for _, subtitle := range subtitles {
lan := subtitle.Get("lan").Str()
url := subtitle.Get("subtitle_url").Str()
subtitlesMap[lan] = url
}
urlZHCN, hasZHCN := subtitlesMap["zh-CN"]
urlAIZH, hasAIZH := subtitlesMap["ai-zh"]
if hasZHCN {
url = urlZHCN
} else if hasAIZH {
url = urlAIZH
} else { //都没有直接取第一个
url = subtitles[0].Get("subtitle_url").Str()
}