bilifeed.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // ============================================================================
  2. // bilifeed.go — B站关注动态抓取
  3. //
  4. // 需要登录态(cookie 含 SESSDATA),抓取「关注的人的最新动态」。
  5. // 接口:GET https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/all?type=all&page=1
  6. // 该接口本身不需 WBI 签名,但需带登录 cookie 与 buvid3,否则返回 code=-101 账号未登录。
  7. // ============================================================================
  8. package main
  9. import (
  10. "encoding/json"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "net/http"
  15. "strings"
  16. "time"
  17. )
  18. const (
  19. biliDynamicURL = "https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/all"
  20. biliHomeURL = "https://www.bilibili.com/"
  21. )
  22. // B站 cookie 相关错误:供上层区分「未配置」与「已过期」,向用户给出明确提示
  23. var (
  24. errBiliCookieEmpty = errors.New("未配置 B站登录 cookie(设置 → 新闻 → B站 cookie)")
  25. errBiliCookieExpired = errors.New("B站 cookie 已过期或无效,请到「设置 → 新闻」更新 cookie")
  26. )
  27. // BiliDynamicItem 一条 B站动态,供「新闻」页展示
  28. type BiliDynamicItem struct {
  29. Source string `json:"source"` // 来源:B站动态
  30. Title string `json:"title"` // 标题(动态文案或视频标题)
  31. URL string `json:"url"` // 详情页地址
  32. Matched bool `json:"matched"` // 是否命中关注关键词
  33. }
  34. // BiliFeedResult B站动态抓取结果:列表 + 需要提示用户的说明(如 cookie 过期后回退热门)
  35. type BiliFeedResult struct {
  36. Items []BiliDynamicItem `json:"items"`
  37. Notice string `json:"notice"`
  38. }
  39. // biliFeedPayload 动态 feed 接口响应结构(只取需要的字段)
  40. type biliFeedPayload struct {
  41. Code int `json:"code"`
  42. Message string `json:"message"`
  43. Data struct {
  44. HasMore bool `json:"has_more"`
  45. Items []struct {
  46. IDStr string `json:"id_str"`
  47. Modules struct {
  48. ModuleAuthor struct {
  49. Name string `json:"name"` // 发布者昵称
  50. } `json:"module_author"`
  51. ModuleDynamic struct {
  52. Desc struct {
  53. Text string `json:"text"` // 动态文案
  54. } `json:"desc"`
  55. } `json:"module_dynamic"`
  56. ModuleArchival struct {
  57. Archival struct {
  58. Title string `json:"title"` // 视频标题
  59. Bvid string `json:"bvid"` // 视频 bvid,用于拼详情地址
  60. Desc string `json:"desc"` // 视频简介
  61. History struct {
  62. Text string `json:"text"` // 时长/进度
  63. } `json:"history"`
  64. } `json:"archival"`
  65. } `json:"module_archival"`
  66. } `json:"modules"`
  67. } `json:"items"`
  68. } `json:"data"`
  69. }
  70. // fetchBiliDynamic 抓取 B站关注动态(需登录 cookie)。cookie 为空返回明确错误。
  71. func fetchBiliDynamic(cookie string) ([]BiliDynamicItem, error) {
  72. cookie = strings.TrimSpace(cookie)
  73. if cookie == "" {
  74. return nil, errBiliCookieEmpty
  75. }
  76. // 先访问主页拿 buvid3/buvid4(动态接口可能要求),再把 cookie 一起带上
  77. _, buvids := fetchBuvid3()
  78. client := &http.Client{Timeout: 12 * time.Second}
  79. req, err := http.NewRequest(http.MethodGet, biliDynamicURL+"?type=all&page=1", nil)
  80. if err != nil {
  81. return nil, err
  82. }
  83. req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36")
  84. req.Header.Set("Referer", biliHomeURL)
  85. req.Header.Set("Accept", "application/json")
  86. // cookie 拼接:登录 cookie + buvid3/buvid4(若有)
  87. allCookie := cookie
  88. if buvids != "" {
  89. allCookie = strings.TrimSpace(allCookie + "; " + buvids)
  90. }
  91. req.Header.Set("Cookie", allCookie)
  92. resp, err := client.Do(req)
  93. if err != nil {
  94. return nil, err
  95. }
  96. defer resp.Body.Close()
  97. body, err := io.ReadAll(resp.Body)
  98. if err != nil {
  99. return nil, err
  100. }
  101. var payload biliFeedPayload
  102. if err := json.Unmarshal(body, &payload); err != nil {
  103. return nil, fmt.Errorf("解析 B站动态失败: %w", err)
  104. }
  105. if payload.Code == -101 {
  106. return nil, errBiliCookieExpired
  107. }
  108. if payload.Code != 0 {
  109. return nil, fmt.Errorf("B站动态接口错误 code=%d message=%s", payload.Code, payload.Message)
  110. }
  111. items := make([]BiliDynamicItem, 0, len(payload.Data.Items))
  112. for _, it := range payload.Data.Items {
  113. author := strings.TrimSpace(it.Modules.ModuleAuthor.Name)
  114. // 优先取视频标题(module_archival),否则取动态文案(module_dynamic.desc)
  115. archTitle := strings.TrimSpace(it.Modules.ModuleArchival.Archival.Title)
  116. bvid := strings.TrimSpace(it.Modules.ModuleArchival.Archival.Bvid)
  117. dynText := strings.TrimSpace(it.Modules.ModuleDynamic.Desc.Text)
  118. var title, link string
  119. if archTitle != "" {
  120. title = archTitle
  121. if bvid != "" {
  122. link = "https://www.bilibili.com/video/" + bvid
  123. }
  124. } else if dynText != "" {
  125. title = dynText
  126. link = "https://t.bilibili.com/" + it.IDStr
  127. } else {
  128. continue // 无标题无视频:跳过
  129. }
  130. title = truncateText(title, 120) // 长文案截断,避免卡片撑爆
  131. if link == "" {
  132. link = "https://t.bilibili.com/" + it.IDStr
  133. }
  134. if author != "" {
  135. title = author + ":" + title
  136. }
  137. items = append(items, BiliDynamicItem{Source: "B站动态", Title: title, URL: link})
  138. if len(items) >= 30 {
  139. break
  140. }
  141. }
  142. if len(items) == 0 {
  143. return nil, fmt.Errorf("B站动态为空(可能没有关注动态)")
  144. }
  145. return items, nil
  146. }
  147. // fetchBuvid3 访问 B站主页获取 buvid3 / buvid4 cookie(动态接口可能要求校验)
  148. func fetchBuvid3() (buvid string, extra string) {
  149. client := &http.Client{Timeout: 8 * time.Second}
  150. req, err := http.NewRequest(http.MethodGet, biliHomeURL, nil)
  151. if err != nil {
  152. return "", ""
  153. }
  154. req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36")
  155. resp, err := client.Do(req)
  156. if err != nil {
  157. return "", ""
  158. }
  159. defer resp.Body.Close()
  160. io.Copy(io.Discard, resp.Body) // 读走 body 以便复用连接
  161. var parts []string
  162. for _, c := range resp.Cookies() {
  163. if c.Name == "buvid3" || c.Name == "buvid4" {
  164. parts = append(parts, c.Name+"="+c.Value)
  165. }
  166. }
  167. if len(parts) == 0 {
  168. return "", ""
  169. }
  170. return "", strings.Join(parts, "; ")
  171. }
  172. // truncateText 截断长文本到 maxRunes 个字符(按 rune 计,避免切断多字节)
  173. func truncateText(s string, maxRunes int) string {
  174. r := []rune(s)
  175. if len(r) <= maxRunes {
  176. return s
  177. }
  178. return string(r[:maxRunes]) + "…"
  179. }
  180. // ------------------------------------------------------------------------
  181. // 备用:B站热门 / 排行榜(无需登录),可作为 cookie 失效时的兜底。
  182. // ------------------------------------------------------------------------
  183. const (
  184. biliPopularURL = "https://api.bilibili.com/x/web-interface/popular"
  185. biliRankURL = "https://api.bilibili.com/x/web-interface/ranking/v2"
  186. )
  187. // biliVideoListPayload 热门 / 排行接口响应结构
  188. type biliVideoListPayload struct {
  189. Code int `json:"code"`
  190. Message string `json:"message"`
  191. Data struct {
  192. List []struct {
  193. Title string `json:"title"` // 视频标题
  194. Bvid string `json:"bvid"` // 视频 bvid
  195. } `json:"list"`
  196. } `json:"data"`
  197. }
  198. // fetchBiliPopular 抓取 B站热门视频(取前 20 条,无需登录)
  199. func fetchBiliPopular() ([]BiliDynamicItem, error) {
  200. return fetchBiliVideoList(biliPopularURL + "?ps=20&pn=1")
  201. }
  202. // fetchBiliRank 抓取 B站排行榜(取前 20 条,无需登录)
  203. func fetchBiliRank() ([]BiliDynamicItem, error) {
  204. return fetchBiliVideoList(biliRankURL + "?rid=0&type=all")
  205. }
  206. func fetchBiliVideoList(apiURL string) ([]BiliDynamicItem, error) {
  207. client := &http.Client{Timeout: 10 * time.Second}
  208. req, err := http.NewRequest(http.MethodGet, apiURL, nil)
  209. if err != nil {
  210. return nil, err
  211. }
  212. req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36")
  213. req.Header.Set("Referer", biliHomeURL)
  214. req.Header.Set("Accept", "application/json")
  215. resp, err := client.Do(req)
  216. if err != nil {
  217. return nil, err
  218. }
  219. defer resp.Body.Close()
  220. body, err := io.ReadAll(resp.Body)
  221. if err != nil {
  222. return nil, err
  223. }
  224. var payload biliVideoListPayload
  225. if err := json.Unmarshal(body, &payload); err != nil {
  226. return nil, fmt.Errorf("解析 B站列表失败: %w", err)
  227. }
  228. if payload.Code != 0 {
  229. return nil, fmt.Errorf("B站列表接口错误 code=%d message=%s", payload.Code, payload.Message)
  230. }
  231. items := make([]BiliDynamicItem, 0, len(payload.Data.List))
  232. for _, v := range payload.Data.List {
  233. title := strings.TrimSpace(v.Title)
  234. if title == "" || v.Bvid == "" {
  235. continue
  236. }
  237. items = append(items, BiliDynamicItem{
  238. Source: "B站",
  239. Title: truncateText(title, 120),
  240. URL: "https://www.bilibili.com/video/" + v.Bvid,
  241. })
  242. if len(items) >= 20 {
  243. break
  244. }
  245. }
  246. if len(items) == 0 {
  247. return nil, fmt.Errorf("列表为空")
  248. }
  249. return items, nil
  250. }
  251. // ------------------------------------------------------------------------
  252. // 组合抓取:B站动态(需 cookie)+ 热门兜底。
  253. // ------------------------------------------------------------------------
  254. // fetchBiliFeed 优先抓关注动态,cookie 未配置或失效时回退热门视频。
  255. // 返回 (列表, 需要提示用户的说明, 错误);说明仅在回退到热门视频时非空,
  256. // 用于让前端明确告知「cookie 已过期」而不是误以为看到的是关注动态。
  257. func fetchBiliFeed(cookie string) ([]BiliDynamicItem, string, error) {
  258. dyn, err := fetchBiliDynamic(cookie)
  259. if err == nil {
  260. return dyn, "", nil // 正常拿到关注动态
  261. }
  262. notice := ""
  263. switch {
  264. case errors.Is(err, errBiliCookieEmpty):
  265. notice = "未配置 B站 cookie,当前显示热门视频(可在「设置 → 新闻」填写)"
  266. case errors.Is(err, errBiliCookieExpired):
  267. notice = "B站 cookie 已过期或无效,当前显示热门视频,请到「设置 → 新闻」更新 cookie"
  268. }
  269. // 兜底:热门视频
  270. pop, popErr := fetchBiliPopular()
  271. if popErr == nil {
  272. return pop, notice, nil // 用热门兜底(动态失败但热门成功)
  273. }
  274. return nil, notice, fmt.Errorf("B站动态失败:%v;热门兜底也失败:%v", err, popErr)
  275. }