From ada2d7e5b00902dd8fdef2b398f9b7574ceb7e7f Mon Sep 17 00:00:00 2001 From: himawari <1156544355@qq.com> Date: Fri, 26 Aug 2022 10:39:50 +0800 Subject: [PATCH 1/4] =?UTF-8?q?=E2=9C=A8=20=E6=B7=BB=E5=8A=A0=E6=9F=A5?= =?UTF-8?q?=E5=BC=B9=E5=B9=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/bilibili/api.go | 20 ++- plugin/bilibili/bilibili.go | 297 +++++++++++++++++++++++++++++-- plugin/bilibili/bilibilimodel.go | 2 +- plugin/bilibili/types.go | 45 +++++ 4 files changed, 345 insertions(+), 19 deletions(-) diff --git a/plugin/bilibili/api.go b/plugin/bilibili/api.go index 2b6eb2a456..e7197af6b3 100644 --- a/plugin/bilibili/api.go +++ b/plugin/bilibili/api.go @@ -4,6 +4,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "net/http" "strconv" @@ -18,7 +19,24 @@ var ( // searchUser 查找b站用户 func searchUser(keyword string) (r []searchResult, err error) { - data, err := web.GetData(fmt.Sprintf(searchUserURL, keyword)) + client := &http.Client{} + req, err := http.NewRequest("GET", fmt.Sprintf(searchUserURL, keyword), nil) + if err != nil { + return + } + c := vdb.getBilibiliCookie() + req.Header.Add("cookie", c.Value) + res, err := client.Do(req) + if err != nil { + return + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + s := fmt.Sprintf("status code: %d", res.StatusCode) + err = errors.New(s) + return + } + data, err := io.ReadAll(res.Body) if err != nil { return } diff --git a/plugin/bilibili/bilibili.go b/plugin/bilibili/bilibili.go index 9316acf658..ddfb302d24 100644 --- a/plugin/bilibili/bilibili.go +++ b/plugin/bilibili/bilibili.go @@ -2,10 +2,13 @@ package bilibili import ( + "crypto/tls" "encoding/binary" + "encoding/json" "fmt" "image" "image/color" + "net/http" "os" "path" "regexp" @@ -14,7 +17,6 @@ import ( "time" "github.com/Coloured-glaze/gg" - fcext "github.com/FloatTech/floatbox/ctxext" "github.com/FloatTech/floatbox/file" "github.com/FloatTech/floatbox/img/writer" "github.com/FloatTech/floatbox/web" @@ -27,16 +29,27 @@ import ( "github.com/wdvxdr1123/ZeroBot/message" ) -var re = regexp.MustCompile(`^\d+$`) +var ( + re = regexp.MustCompile(`^\d+$`) + danmakuTypeMap = map[int64]string{ + 0: "普通消息", + 1: "礼物", + 2: "上舰", + 3: "Superchat", + 4: "进入直播间", + 5: "标题变动", + } +) // 查成分的 func init() { engine := control.Register("bilibili", &ctrl.Options[*zero.Ctx]{ DisableOnDefault: false, - Help: "bilibili\n" + + Help: "bilibili (412就是拦截的意思,建议私聊把cookie设全)\n" + "- >vup info [xxx]\n" + "- >user info [xxx]\n" + "- 查成分 [xxx]\n" + + "- 查弹幕 [xxx]\n" + "- 设置b站cookie SESSDATA=82da790d,1663822823,06ecf*31\n" + "- 更新vup", PublicDataFolder: "Bilibili", @@ -44,17 +57,12 @@ func init() { cachePath := engine.DataFolder() + "cache/" _ = os.RemoveAll(cachePath) _ = os.MkdirAll(cachePath, 0755) - var getdb = fcext.DoOnceOnSuccess(func(ctx *zero.Ctx) bool { - var err error - _, _ = engine.GetLazyData("bilibili.db", false) - vdb, err = initializeVup(engine.DataFolder() + "bilibili.db") - if err != nil { - ctx.SendChain(message.Text("ERROR: ", err)) - return false - } - return true - }) - + var err error + _, _ = engine.GetLazyData("bilibili.db", false) + vdb, err = initializeVup(engine.DataFolder() + "bilibili.db") + if err != nil { + panic(err) + } engine.OnRegex(`^>user info\s?(.{1,25})$`, getPara).SetBlock(true). Handle(func(ctx *zero.Ctx) { id := ctx.State["uid"].(string) @@ -96,7 +104,7 @@ func init() { )) }) - engine.OnRegex(`^查成分\s?(.{1,25})$`, getdb, getPara).SetBlock(true). + engine.OnRegex(`^查成分\s?(.{1,25})$`, getPara).SetBlock(true). Handle(func(ctx *zero.Ctx) { id := ctx.State["uid"].(string) today := time.Now().Format("20060102") @@ -254,7 +262,262 @@ func init() { ctx.SendChain(message.Image("file:///" + file.BOTPATH + "/" + drawedFile)) }) - engine.OnRegex(`^设置b站cookie?\s+(.{1,100})$`, zero.SuperUserPermission, getdb).SetBlock(true). + engine.OnRegex(`^查弹幕\s?(\S{1,25})\s?(\d*)$`, getPara).SetBlock(true).Handle(func(ctx *zero.Ctx) { + id := ctx.State["uid"].(string) + pagenum := ctx.State["regex_matched"].([]string)[2] + if pagenum == "" { + pagenum = "0" + } + u, err := getMemberCard(id) + if err != nil { + ctx.SendChain(message.Text("ERROR:", err)) + return + } + var danmaku danmakusuki + tr := &http.Transport{ + DisableKeepAlives: true, + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + } + + client := &http.Client{Transport: tr} + data, err := web.RequestDataWith(client, fmt.Sprintf(danmakuAPI, id, pagenum), "GET", "", web.RandUA()) + if err != nil { + ctx.SendChain(message.Text("Error:", err)) + return + } + err = json.Unmarshal(data, &danmaku) + if err != nil { + ctx.SendChain(message.Text("Error:", err)) + return + } + today := time.Now().Format("20060102150415") + drawedFile := cachePath + id + today + "vupLike.png" + facePath := cachePath + id + "vupFace" + path.Ext(u.Face) + backX := 500 + backY := 500 + var back image.Image + if path.Ext(u.Face) != ".webp" { + err = initFacePic(facePath, u.Face) + if err != nil { + ctx.SendChain(message.Text("ERROR:", err)) + return + } + back, err = gg.LoadImage(facePath) + if err != nil { + ctx.SendChain(message.Text("ERROR:", err)) + return + } + back = img.Size(back, backX, backY).Im + } + canvas := gg.NewContext(100, 100) + fontSize := 50.0 + _, err = file.GetLazyData(text.BoldFontFile, true) + if err != nil { + ctx.SendChain(message.Text("ERROR:", err)) + } + if err = canvas.LoadFontFace(text.BoldFontFile, fontSize); err != nil { + ctx.SendChain(message.Text("ERROR:", err)) + return + } + dz, h := canvas.MeasureString("好") + danmuH := h * 2 + faceH := float64(510) + + totalDanmuku := 0 + for i := 0; i < len(danmaku.Data.Data); i++ { + totalDanmuku += len(danmaku.Data.Data[i].Danmakus) + 1 + } + cw := 10000 + mcw := float64(2000) + ch := 550 + len(danmaku.Data.Data)*int(faceH) + totalDanmuku*int(danmuH) + canvas = gg.NewContext(cw, ch) + canvas.SetColor(color.White) + canvas.Clear() + canvas.SetColor(color.Black) + if err = canvas.LoadFontFace(text.BoldFontFile, fontSize); err != nil { + ctx.SendChain(message.Text("ERROR:", err)) + return + } + facestart := 100 + fontH := h * 1.6 + startWidth := float64(700) + startWidth2 := float64(20) + + if back != nil { + canvas.DrawImage(back, facestart, 0) + } + length, _ := canvas.MeasureString(u.Mid) + n, _ := canvas.MeasureString(u.Name) + canvas.DrawString(u.Name, startWidth, 122.5) + canvas.DrawRoundedRectangle(900+n-length*0.1, 66, length*1.2, 75, fontSize*0.2) + canvas.SetRGB255(221, 221, 221) + canvas.Fill() + canvas.SetColor(color.Black) + canvas.DrawString(u.Mid, 900+n, 122.5) + canvas.DrawString(fmt.Sprintf("粉丝:%d 关注:%d", u.Fans, u.Attention), startWidth, 222.5) + canvas.DrawString(fmt.Sprintf("页码:[%d/%d]", danmaku.Data.PageNum, (danmaku.Data.Total-1)/5), startWidth, 322.5) + canvas.DrawString("网页链接: "+fmt.Sprintf(danmakuURL, u.Mid), startWidth, 422.5) + var channelStart float64 + channelStart = float64(550) + for i := 0; i < len(danmaku.Data.Data); i++ { + item := danmaku.Data.Data[i] + facePath = cachePath + strconv.Itoa(int(item.Channel.UID)) + "vupFace" + path.Ext(item.Channel.FaceURL) + if path.Ext(item.Channel.FaceURL) != ".webp" { + err = initFacePic(facePath, item.Channel.FaceURL) + if err != nil { + ctx.SendChain(message.Text("ERROR:", err)) + return + } + back, err = gg.LoadImage(facePath) + if err != nil { + ctx.SendChain(message.Text("ERROR:", err)) + return + } + back = img.Size(back, backX, backY).Im + } + if back != nil { + canvas.DrawImage(back, facestart, int(channelStart)) + } + canvas.SetRGB255(24, 144, 255) + canvas.DrawString("标题: "+item.Live.Title, startWidth, channelStart+fontH) + canvas.DrawString("主播: "+item.Channel.Name, startWidth, channelStart+fontH*2) + canvas.SetColor(color.Black) + canvas.DrawString("开始时间: "+time.UnixMilli(item.Live.StartDate).Format("2006-01-02 15:04:05"), startWidth, channelStart+fontH*3) + if item.Live.IsFinish { + canvas.DrawString("结束时间: "+time.UnixMilli(item.Live.StopDate).Format("2006-01-02 15:04:05"), startWidth, channelStart+fontH*4) + canvas.DrawString("直播时长: "+strconv.FormatFloat(float64(item.Live.StopDate-item.Live.StartDate)/3600000.0, 'f', 1, 64)+"小时", startWidth, channelStart+fontH*5) + } else { + t := "结束时间:" + l, _ := canvas.MeasureString(t) + canvas.DrawString(t, startWidth, channelStart+fontH*4) + + canvas.SetRGB255(0, 128, 0) + t = "正在直播" + canvas.DrawString(t, startWidth+l*1.1, channelStart+fontH*4) + canvas.SetColor(color.Black) + + canvas.DrawString("直播时长: "+strconv.FormatFloat(float64(time.Now().UnixMilli()-item.Live.StartDate)/3600000.0, 'f', 1, 64)+"小时", startWidth, channelStart+fontH*5) + } + canvas.DrawString("弹幕数量: "+strconv.Itoa(int(item.Live.DanmakusCount)), startWidth, channelStart+fontH*6) + canvas.DrawString("观看次数: "+strconv.Itoa(int(item.Live.WatchCount)), startWidth, channelStart+fontH*7) + + t := "收益:" + l, _ := canvas.MeasureString(t) + canvas.DrawString(t, startWidth, channelStart+fontH*8) + + t = "¥" + strconv.Itoa(int(item.Live.TotalIncome)) + canvas.SetRGB255(255, 0, 0) + canvas.DrawString(t, startWidth+l*1.1, channelStart+fontH*8) + canvas.SetColor(color.Black) + + DanmakuStart := channelStart + faceH + for i := 0; i < len(item.Danmakus); i++ { + moveW := startWidth2 + danmuNow := DanmakuStart + danmuH*float64(i+1) + danItem := item.Danmakus[i] + + t := time.UnixMilli(danItem.SendDate).Format("15:04:05") + l, _ := canvas.MeasureString(t) + canvas.DrawString(t, moveW, danmuNow) + moveW += l + dz + + t = danItem.Name + l, _ = canvas.MeasureString(t) + canvas.SetRGB255(24, 144, 255) + canvas.DrawString(t, moveW, danmuNow) + canvas.SetColor(color.Black) + moveW += l + dz + + switch danItem.Type { + case 0: + t = danItem.Message + l, _ = canvas.MeasureString(t) + canvas.DrawString(t, moveW, danmuNow) + moveW += l + dz + case 1: + t = danmakuTypeMap[danItem.Type] + l, _ = canvas.MeasureString(t) + canvas.SetRGB255(255, 0, 0) + canvas.DrawString(t, moveW, danmuNow) + moveW += l + dz + + t = danItem.Message + l, _ = canvas.MeasureString(t) + canvas.DrawString(t, moveW, danmuNow) + canvas.SetColor(color.Black) + moveW += l + dz + case 2, 3: + t = danmakuTypeMap[danItem.Type] + l, _ = canvas.MeasureString(t) + if danItem.Type == 3 { + canvas.SetRGB255(0, 85, 255) + } else { + canvas.SetRGB255(128, 0, 128) + } + + canvas.DrawString(t, moveW, danmuNow) + moveW += l + dz + + t = danItem.Message + l, _ = canvas.MeasureString(t) + canvas.DrawString(t, moveW, danmuNow) + moveW += l + + t = "[" + l, _ = canvas.MeasureString(t) + canvas.DrawString(t, moveW, danmuNow) + moveW += l + + t = "¥" + strconv.FormatFloat(danItem.Price, 'f', 1, 64) + l, _ = canvas.MeasureString(t) + canvas.SetRGB255(255, 0, 0) + canvas.DrawString(t, moveW, danmuNow) + if danItem.Type == 3 { + canvas.SetRGB255(0, 85, 255) + } else { + canvas.SetRGB255(128, 0, 128) + } + moveW += l + + t = "]" + l, _ = canvas.MeasureString(t) + canvas.DrawString(t, moveW, danmuNow) + canvas.SetColor(color.Black) + moveW += l + dz + case 4, 5: + t = danmakuTypeMap[danItem.Type] + canvas.SetRGB255(0, 128, 0) + l, _ = canvas.MeasureString(t) + canvas.DrawString(t, moveW, danmuNow) + canvas.SetColor(color.Black) + moveW += l + dz + } + if moveW > mcw { + mcw = moveW + } + } + channelStart = DanmakuStart + float64(len(item.Danmakus)+1)*danmuH + } + im := canvas.Image().(*image.RGBA) + nim := im.SubImage(image.Rect(0, 0, int(mcw), ch)) + f, err := os.Create(drawedFile) + if err != nil { + log.Errorln("[bilibili]", err) + data, cl := writer.ToBytes(nim) + ctx.SendChain(message.ImageBytes(data)) + cl() + return + } + _, err = writer.WriteTo(nim, f) + _ = f.Close() + if err != nil { + ctx.SendChain(message.Text("ERROR:", err)) + return + } + ctx.SendChain(message.Image("file:///" + file.BOTPATH + "/" + drawedFile)) + }) + + engine.OnRegex(`^设置b站cookie?\s+(.*)$`, zero.SuperUserPermission).SetBlock(true). Handle(func(ctx *zero.Ctx) { cookie := ctx.State["regex_matched"].([]string)[1] err := vdb.setBilibiliCookie(cookie) @@ -265,7 +528,7 @@ func init() { ctx.SendChain(message.Text("成功设置b站cookie为" + cookie)) }) - engine.OnFullMatch("更新vup", zero.SuperUserPermission, getdb).SetBlock(true). + engine.OnFullMatch("更新vup", zero.SuperUserPermission).SetBlock(true). Handle(func(ctx *zero.Ctx) { ctx.SendChain(message.Text("少女祈祷中...")) err := updateVup() diff --git a/plugin/bilibili/bilibilimodel.go b/plugin/bilibili/bilibilimodel.go index 423e12b26c..5795d9ee4d 100644 --- a/plugin/bilibili/bilibilimodel.go +++ b/plugin/bilibili/bilibilimodel.go @@ -34,7 +34,7 @@ func (vup) TableName() string { type config struct { Key string `gorm:"column:key;primary_key"` - Value string `gorm:"column:value"` + Value string `gorm:"column:value;type:varchar(2048)"` } func (config) TableName() string { diff --git a/plugin/bilibili/types.go b/plugin/bilibili/types.go index 475dd0e68a..9eab22d1bf 100644 --- a/plugin/bilibili/types.go +++ b/plugin/bilibili/types.go @@ -31,6 +31,10 @@ const ( spaceHistoryURL = "https://api.vc.bilibili.com/dynamic_svr/v1/dynamic_svr/space_history?host_uid=%v&offset_dynamic_id=%v&need_top=0" // liveListURL 获得直播状态 liveListURL = "https://api.live.bilibili.com/room/v1/Room/get_status_info_by_uids" + // danmakuAPI 弹幕网获得用户弹幕api + danmakuAPI = "https://danmaku.suki.club/api/search/user/detail?uid=%v&pagenum=%v&pagesize=5" + // danmakuURL 弹幕网链接 + danmakuURL = "https://danmaku.suki.club/user/%v" ) // dynamicCard 总动态结构体,包括desc,card @@ -271,3 +275,44 @@ type vtbDetail struct { GuardNum int `json:"guardNum"` AreaRank int `json:"areaRank"` } + +// danmakusuki 弹幕网结构体 +type danmakusuki struct { + Code int64 `json:"code"` + Message string `json:"message"` + Data struct { + Data []struct { + Channel struct { + Name string `json:"name"` + IsLiving bool `json:"isLiving"` + UID int64 `json:"uId"` + RoomID int64 `json:"roomId"` + FaceURL string `json:"faceUrl"` + LiveCount int64 `json:"liveCount"` + } `json:"channel"` + Live struct { + LiveID string `json:"liveId"` + Title string `json:"title"` + IsFinish bool `json:"isFinish"` + CoverURL string `json:"coverUrl"` + StartDate int64 `json:"startDate"` + StopDate int64 `json:"stopDate"` + DanmakusCount int64 `json:"danmakusCount"` + TotalIncome float64 `json:"totalIncome"` + WatchCount int64 `json:"watchCount"` + } `json:"live"` + Danmakus []struct { + Name string `json:"name"` + Type int64 `json:"type"` + UID int64 `json:"uId"` + SendDate int64 `json:"sendDate"` + Price float64 `json:"price"` + Message string `json:"message"` + } `json:"danmakus"` + } `json:"data"` + Total int64 `json:"total"` + PageNum int64 `json:"pageNum"` + PageSize int64 `json:"pageSize"` + HasMore bool `json:"hasMore"` + } `json:"data"` +} From c0d9c5506544787a8da12a652f44e1db1cd4d245 Mon Sep 17 00:00:00 2001 From: himawari <1156544355@qq.com> Date: Fri, 26 Aug 2022 10:59:01 +0800 Subject: [PATCH 2/4] =?UTF-8?q?=F0=9F=8E=A8=20=E6=B7=BB=E5=8A=A0=E6=B3=A8?= =?UTF-8?q?=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.go | 1 + 1 file changed, 1 insertion(+) diff --git a/config.go b/config.go index 42984f9573..f6ca91f82c 100644 --- a/config.go +++ b/config.go @@ -1,3 +1,4 @@ +// package main 主函数 package main import ( From ca3a59984141693fdb321282fe9b30032d955312 Mon Sep 17 00:00:00 2001 From: himawari <1156544355@qq.com> Date: Fri, 26 Aug 2022 23:22:35 +0800 Subject: [PATCH 3/4] =?UTF-8?q?=F0=9F=8E=A8=20=E4=BC=98=E5=8C=96=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 ++- plugin/bilibili/api.go | 22 ++++-------- plugin/bilibili/bilibili.go | 23 ++++++++----- plugin/bilibili/bilibilimodel.go | 58 +++++++++++++++----------------- plugin/bilibili/types.go | 13 +++++++ 5 files changed, 66 insertions(+), 54 deletions(-) diff --git a/README.md b/README.md index e7586580ed..4677f66c7f 100644 --- a/README.md +++ b/README.md @@ -381,7 +381,9 @@ print("run[CQ:image,file="+j["img"]+"]") - [x] 查成分 [xxx] - - [x] 设置b站cookie SESSDATA=82da790d,1663822823,06ecf\*31 + - [x] 查弹幕 [xxx] 2 (最后一个参数是页码) + + - [x] 设置b站cookie SESSDATA=82da790d,1663822823,06ecf\*31 (最好把cookie设全) - [x] 更新vup diff --git a/plugin/bilibili/api.go b/plugin/bilibili/api.go index e7197af6b3..c94cbd3e0d 100644 --- a/plugin/bilibili/api.go +++ b/plugin/bilibili/api.go @@ -4,7 +4,6 @@ import ( "encoding/json" "errors" "fmt" - "io" "net/http" "strconv" @@ -24,8 +23,8 @@ func searchUser(keyword string) (r []searchResult, err error) { if err != nil { return } - c := vdb.getBilibiliCookie() - req.Header.Add("cookie", c.Value) + reflushBilibiliCookie() + req.Header.Add("cookie", cfg.BilibiliCookie) res, err := client.Do(req) if err != nil { return @@ -36,19 +35,12 @@ func searchUser(keyword string) (r []searchResult, err error) { err = errors.New(s) return } - data, err := io.ReadAll(res.Body) - if err != nil { - return - } - j := gjson.ParseBytes(data) - if j.Get("data.numResults").Int() == 0 { - err = errors.New("查无此人") - return - } - err = json.Unmarshal(binary.StringToBytes(j.Get("data.result").Raw), &r) + var sd searchData + err = json.NewDecoder(res.Body).Decode(&sd) if err != nil { return } + r = sd.Data.Result return } @@ -84,8 +76,8 @@ func getMedalwall(uid string) (result []medal, err error) { if err != nil { return } - c := vdb.getBilibiliCookie() - req.Header.Add("cookie", c.Value) + reflushBilibiliCookie() + req.Header.Add("cookie", cfg.BilibiliCookie) res, err := client.Do(req) if err != nil { return diff --git a/plugin/bilibili/bilibili.go b/plugin/bilibili/bilibili.go index ddfb302d24..b38034233e 100644 --- a/plugin/bilibili/bilibili.go +++ b/plugin/bilibili/bilibili.go @@ -17,6 +17,7 @@ import ( "time" "github.com/Coloured-glaze/gg" + fcext "github.com/FloatTech/floatbox/ctxext" "github.com/FloatTech/floatbox/file" "github.com/FloatTech/floatbox/img/writer" "github.com/FloatTech/floatbox/web" @@ -39,6 +40,8 @@ var ( 4: "进入直播间", 5: "标题变动", } + cfgFile = "data/Bilibili/config.json" + cfg config ) // 查成分的 @@ -57,12 +60,16 @@ func init() { cachePath := engine.DataFolder() + "cache/" _ = os.RemoveAll(cachePath) _ = os.MkdirAll(cachePath, 0755) - var err error - _, _ = engine.GetLazyData("bilibili.db", false) - vdb, err = initializeVup(engine.DataFolder() + "bilibili.db") - if err != nil { - panic(err) - } + var getdb = fcext.DoOnceOnSuccess(func(ctx *zero.Ctx) bool { + var err error + _, _ = engine.GetLazyData("bilibili.db", false) + vdb, err = initializeVup(engine.DataFolder() + "bilibili.db") + if err != nil { + ctx.SendChain(message.Text("ERROR:", err)) + return false + } + return true + }) engine.OnRegex(`^>user info\s?(.{1,25})$`, getPara).SetBlock(true). Handle(func(ctx *zero.Ctx) { id := ctx.State["uid"].(string) @@ -104,7 +111,7 @@ func init() { )) }) - engine.OnRegex(`^查成分\s?(.{1,25})$`, getPara).SetBlock(true). + engine.OnRegex(`^查成分\s?(.{1,25})$`, getPara, getdb).SetBlock(true). Handle(func(ctx *zero.Ctx) { id := ctx.State["uid"].(string) today := time.Now().Format("20060102") @@ -520,7 +527,7 @@ func init() { engine.OnRegex(`^设置b站cookie?\s+(.*)$`, zero.SuperUserPermission).SetBlock(true). Handle(func(ctx *zero.Ctx) { cookie := ctx.State["regex_matched"].([]string)[1] - err := vdb.setBilibiliCookie(cookie) + err := setBilibiliCookie(cookie) if err != nil { ctx.SendChain(message.Text("ERROR: ", err)) return diff --git a/plugin/bilibili/bilibilimodel.go b/plugin/bilibili/bilibilimodel.go index 5795d9ee4d..a6f4329af2 100644 --- a/plugin/bilibili/bilibilimodel.go +++ b/plugin/bilibili/bilibilimodel.go @@ -1,9 +1,12 @@ package bilibili import ( + "encoding/json" + "errors" "os" "github.com/FloatTech/floatbox/binary" + "github.com/FloatTech/floatbox/file" "github.com/FloatTech/floatbox/web" _ "github.com/fumiama/sqlite3" // use sql "github.com/jinzhu/gorm" @@ -32,15 +35,6 @@ func (vup) TableName() string { return "vup" } -type config struct { - Key string `gorm:"column:key;primary_key"` - Value string `gorm:"column:value;type:varchar(2048)"` -} - -func (config) TableName() string { - return "config" -} - // initializeVup 初始化vup数据库 func initializeVup(dbpath string) (*vupdb, error) { if _, err := os.Stat(dbpath); err != nil || os.IsNotExist(err) { @@ -55,7 +49,7 @@ func initializeVup(dbpath string) (*vupdb, error) { if err != nil { return nil, err } - gdb.AutoMigrate(&vup{}).AutoMigrate(&config{}) + gdb.AutoMigrate(&vup{}) return (*vupdb)(gdb), nil } @@ -103,28 +97,32 @@ func updateVup() error { return nil } -func (vdb *vupdb) setBilibiliCookie(cookie string) (err error) { - db := (*gorm.DB)(vdb) - c := config{ - Key: bilibiliCookie, - Value: cookie, - } - if err = db.Model(&config{}).First(&c, "key = ? ", bilibiliCookie).Error; err != nil { - // error handling... - if gorm.IsRecordNotFoundError(err) { - err = db.Model(&config{}).Create(&c).Error - } - } else { - err = db.Model(&config{}).Where("key = ? ", bilibiliCookie).Update( - map[string]interface{}{ - "value": cookie, - }).Error +func setBilibiliCookie(cookie string) (err error) { + cfg = config{ + BilibiliCookie: cookie, } + saveConfig(cfg) return } -func (vdb *vupdb) getBilibiliCookie() (c config) { - db := (*gorm.DB)(vdb) - db.Model(&config{}).First(&c, "key = ?", bilibiliCookie) - return +func reflushBilibiliCookie() (err error) { + if file.IsNotExist(cfgFile) { + err = errors.New("未初始化配置") + return + } + reader, err := os.Open(cfgFile) + if err != nil { + return + } + defer reader.Close() + return json.NewDecoder(reader).Decode(&cfg) +} + +func saveConfig(cfg config) (err error) { + reader, err := os.Create(cfgFile) + if err != nil { + return err + } + defer reader.Close() + return json.NewEncoder(reader).Encode(&cfg) } diff --git a/plugin/bilibili/types.go b/plugin/bilibili/types.go index 9eab22d1bf..c104cad526 100644 --- a/plugin/bilibili/types.go +++ b/plugin/bilibili/types.go @@ -219,6 +219,14 @@ type roomCard struct { } `json:"anchor_info"` } +// searchData 查找b站用户总结构体 +type searchData struct { + Data struct { + NumResults int `json:"numResults"` + Result []searchResult `json:"result"` + } `json:"data"` +} + // searchResult 查找b站用户结果 type searchResult struct { Mid int64 `json:"mid"` @@ -316,3 +324,8 @@ type danmakusuki struct { HasMore bool `json:"hasMore"` } `json:"data"` } + +// 配置结构体 +type config struct { + BilibiliCookie string `json:"bilibili_cookie"` +} From b0e8860dd2d4daa1c9d4bc0926edf2e174a74a08 Mon Sep 17 00:00:00 2001 From: himawari <1156544355@qq.com> Date: Fri, 26 Aug 2022 23:32:30 +0800 Subject: [PATCH 4/4] =?UTF-8?q?=F0=9F=8E=A8=20=E4=BF=AElint?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/bilibili/api.go | 10 ++++++++-- plugin/bilibili/bilibilimodel.go | 7 +------ 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/plugin/bilibili/api.go b/plugin/bilibili/api.go index c94cbd3e0d..371a743e24 100644 --- a/plugin/bilibili/api.go +++ b/plugin/bilibili/api.go @@ -23,7 +23,10 @@ func searchUser(keyword string) (r []searchResult, err error) { if err != nil { return } - reflushBilibiliCookie() + err = reflushBilibiliCookie() + if err != nil { + return + } req.Header.Add("cookie", cfg.BilibiliCookie) res, err := client.Do(req) if err != nil { @@ -76,7 +79,10 @@ func getMedalwall(uid string) (result []medal, err error) { if err != nil { return } - reflushBilibiliCookie() + err = reflushBilibiliCookie() + if err != nil { + return + } req.Header.Add("cookie", cfg.BilibiliCookie) res, err := client.Do(req) if err != nil { diff --git a/plugin/bilibili/bilibilimodel.go b/plugin/bilibili/bilibilimodel.go index a6f4329af2..54f7517ea4 100644 --- a/plugin/bilibili/bilibilimodel.go +++ b/plugin/bilibili/bilibilimodel.go @@ -13,10 +13,6 @@ import ( "github.com/tidwall/gjson" ) -const ( - bilibiliCookie = "bilbili_cookie" -) - var ( vtbURLs = [...]string{"https://api.vtbs.moe/v1/short", "https://api.tokyo.vtbs.moe/v1/short", "https://vtbs.musedash.moe/v1/short"} vdb *vupdb @@ -101,8 +97,7 @@ func setBilibiliCookie(cookie string) (err error) { cfg = config{ BilibiliCookie: cookie, } - saveConfig(cfg) - return + return saveConfig(cfg) } func reflushBilibiliCookie() (err error) {