aboutsummaryrefslogtreecommitdiffstats
path: root/internal/api/biliapi.go
diff options
context:
space:
mode:
authoryingyu5658 <i@yingyu5658.me>2025-12-04 11:19:57 +0800
committeryingyu5658 <i@yingyu5658.me>2025-12-04 11:19:57 +0800
commitc52f41545df179b542f106d08e6dd013a70216e7 (patch)
treeda54d63c0ad311f77fd1ff7d3b3f53109ed99af7 /internal/api/biliapi.go
parent14a941b09749d63871016831b657f6de7a6337fc (diff)
downloadbvd-c52f41545df179b542f106d08e6dd013a70216e7.tar.gz
bvd-c52f41545df179b542f106d08e6dd013a70216e7.zip
refactor: 模块化重构并优化输出
- 将原本的 main.go 拆分为 命令 网络请求 下载三个单独职责的文件 - 优化输出, 添加用户友好的Emoji
Diffstat (limited to 'internal/api/biliapi.go')
-rw-r--r--internal/api/biliapi.go94
1 files changed, 94 insertions, 0 deletions
diff --git a/internal/api/biliapi.go b/internal/api/biliapi.go
new file mode 100644
index 0000000..efd2499
--- /dev/null
+++ b/internal/api/biliapi.go
@@ -0,0 +1,94 @@
+package api
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "time"
+)
+
+type VideoBaseInfo struct {
+ Data []struct {
+ Cid int `json:"cid"` // 每一个视频的 CID
+ Part string `json:"part"` // 分 P 标题
+ Page int `json:"page"` // 分 P 编号
+ FirstFrame string `json:"first_frame"` // 封面图
+ } `json:"data"`
+}
+
+type BiliAPI struct {
+ Client *http.Client
+}
+
+func NewBiliAPI() *BiliAPI {
+ return &BiliAPI{
+ Client: &http.Client{Timeout: 30 * time.Second},
+ }
+}
+
+// func getInfo(bvid string) (VideoBaseInfo, error) {
+// var APIUrl string = "https://api.bilibili.com/x/player/pagelist?bvid="
+// APIUrl += bvid
+// client := &http.Client{
+// Timeout: 30 * time.Second,
+// }
+
+// // 发送 GET 请求
+// resp, err := client.Get(APIUrl)
+// if err != nil {
+// return VideoBaseInfo{}, fmt.Errorf("发送请求失败: %w", err)
+// }
+// defer resp.Body.Close()
+
+// body, err := io.ReadAll(resp.Body)
+// if err != nil {
+// return VideoBaseInfo{}, fmt.Errorf("读取响应失败: %w", err)
+// }
+
+// var result VideoBaseInfo
+// if err := json.Unmarshal(body, &result); err != nil {
+// return VideoBaseInfo{}, fmt.Errorf("JSON 解析失败: %w", err)
+// }
+
+// return VideoBaseInfo{}, err
+// }
+
+func (a *BiliAPI) GetVideoInfo(bvid string) (*VideoBaseInfo, error) {
+ var APIUrl string = "https://api.bilibili.com/x/player/pagelist?bvid="
+ APIUrl += bvid
+ client := a.Client
+ if client == nil {
+ client = &http.Client{
+ Timeout: 30 * time.Second,
+ }
+ }
+
+ // 发送 GET 请求
+ resp, err := client.Get(APIUrl)
+ if err != nil {
+ return &VideoBaseInfo{}, fmt.Errorf("❌ 发送请求失败: %w", err)
+ }
+ defer resp.Body.Close()
+
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return &VideoBaseInfo{}, fmt.Errorf("❌ 读取响应失败: %w", err)
+ }
+
+ if len(body) > 0 && body[0] == '<' {
+ snippet := string(body)
+ if len(snippet) > 512 {
+ snippet = snippet[:512]
+ }
+ return nil, fmt.Errorf("❌ 服务器返回 HTML 而非 JSON: %s", snippet)
+ }
+
+ var result VideoBaseInfo
+ if err := json.Unmarshal(body, &result); err != nil {
+ return &VideoBaseInfo{}, fmt.Errorf("❌ JSON 解析失败: %w", err)
+ }
+
+ return &result, nil
+
+}