Debian Codegraph @

gallery_dl/extractor/bilibili.py

raw
1 # -*- coding: utf-8 -*-
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License version 2 as
5 # published by the Free Software Foundation.
6
7 """Extractors for https://www.bilibili.com/"""
8
9 from .common import Extractor, Message
10 from .. import text, util
11
12
13 class BilibiliExtractor(Extractor):
14 """Base class for bilibili extractors"""
15 category = "bilibili"
16 root = "https://www.bilibili.com"
17 request_interval = (3.0, 6.0)
18
19 def _init(self):
20 self.api = BilibiliAPI(self)
21
22 def items(self):
23 for article in self.articles():
24 article["_extractor"] = BilibiliArticleExtractor
25 url = f"{self.root}/opus/{article['opus_id']}"
26 yield Message.Queue, url, article
27
28 def articles(self):
29 return ()
30
31
32 class BilibiliArticleExtractor(BilibiliExtractor):
33 """Extractor for a bilibili article"""
34 subcategory = "article"
35 pattern = (r"(?:https?://)?"
36 r"(?:t\.bilibili\.com|(?:www\.)?bilibili.com/opus)/(\d+)")
37 example = "https://www.bilibili.com/opus/12345"
38 directory_fmt = ("{category}", "{username}")
39 filename_fmt = "{id}_{num}{suffix}.{extension}"
40 archive_fmt = "{id}_{num}{suffix}"
41
42 def items(self):
43 article_id = self.groups[0]
44 article = self.api.article(article_id)
45
46 # Flatten modules list
47 pics = []
48 modules = {}
49 article["title"] = ""
50 article["content"] = txt = []
51 for module in article["detail"]["modules"]:
52 if m := module.get("module_author"):
53 article["username"] = m.get("name")
54 article["user_id"] = m.get("mid")
55 article["date"] = self.parse_timestamp(m.get("pub_ts"))
56 if m := module.get("module_title"):
57 article["title"] = m.get("text")
58 article["tags"] = m.get("tags")
59 if m := module.get("module_topic"):
60 article["topic"] = m.get("name")
61 article["topic_id"] = m.get("id")
62 article["topic_url"] = m.get("jump_url")
63 if m := module.get("module_blocked"):
64 self.log.warning("%s: Blocked Article\n%s", article_id,
65 m.get("hint_message"))
66 if m := module.get("module_top"):
67 try:
68 pics.extend(m["display"]["album"]["pics"])
69 except Exception:
70 pass
71 if m := module.get("module_content"):
72 for paragraph in m["paragraphs"]:
73 if "pic" in paragraph:
74 try:
75 pics.extend(paragraph["pic"]["pics"])
76 except Exception:
77 pass
78 if "text" in paragraph:
79 try:
80 for node in paragraph["text"]["nodes"]:
81 if n := node.get("word"):
82 txt.append(n["words"])
83 if n := node.get("rich"):
84 txt.append(n.get("orig_text") or n["text"])
85 except Exception:
86 pass
87 del module["module_type"]
88 modules.update(module)
89
90 article["detail"]["modules"] = modules
91 article["count"] = len(pics)
92 yield Message.Directory, "", article
93
94 livephoto = self.config("livephoto", True)
95 article["suffix"] = ""
96 for article["num"], pic in enumerate(pics, 1):
97 url = pic["url"]
98 article.update(pic)
99 yield Message.Url, url, text.nameext_from_url(url, article)
100
101 if livephoto and (url := pic.get("live_url")):
102 article["suffix"] = "l"
103 yield Message.Url, url, text.nameext_from_url(url, article)
104 article["suffix"] = ""
105
106
107 class BilibiliUserArticlesExtractor(BilibiliExtractor):
108 """Extractor for a bilibili user's articles"""
109 subcategory = "user-articles"
110 pattern = (r"(?:https?://)?space\.bilibili\.com/(\d+)"
111 r"/(?:article|upload/opus|dynamic)")
112 example = "https://space.bilibili.com/12345/article"
113
114 def articles(self):
115 return self.api.user_articles(self.groups[0])
116
117
118 class BilibiliUserArticlesFavoriteExtractor(BilibiliExtractor):
119 subcategory = "user-articles-favorite"
120 pattern = (r"(?:https?://)?space\.bilibili\.com"
121 r"/(\d+)/favlist\?fid=opus")
122 example = "https://space.bilibili.com/12345/favlist?fid=opus"
123 _warning = True
124
125 def articles(self):
126 if self._warning:
127 if not self.cookies_check(("SESSDATA",)):
128 self.log.error("'SESSDATA' cookie required")
129 BilibiliUserArticlesFavoriteExtractor._warning = False
130 return self.api.user_favlist()
131
132
133 class BilibiliAPI():
134 def __init__(self, extractor):
135 self.extractor = extractor
136 self.exc = extractor.exc
137
138 def _call(self, endpoint, params):
139 url = "https://api.bilibili.com/x/polymer/web-dynamic/v1" + endpoint
140 data = self.extractor.request_json(url, params=params)
141
142 if data["code"]:
143 self.extractor.log.debug("Server response: %s", data)
144 raise self.exc.AbortExtraction("API request failed")
145
146 return data
147
148 def user_articles(self, user_id):
149 endpoint = "/opus/feed/space"
150 params = {"host_mid": user_id}
151
152 while True:
153 data = self._call(endpoint, params)
154
155 for item in data["data"]["items"]:
156 params["offset"] = item["opus_id"]
157 yield item
158
159 if not data["data"]["has_more"]:
160 break
161
162 def article(self, article_id):
163 url = "https://www.bilibili.com/opus/" + article_id
164
165 while True:
166 page = self.extractor.request(url).text
167 try:
168 return util.json_loads(text.extr(
169 page, "window.__INITIAL_STATE__=", "};") + "}")
170 except Exception:
171 if "window._riskdata_" not in page:
172 raise self.exc.AbortExtraction(
173 article_id + ": Unable to extract INITIAL_STATE data")
174 self.extractor.wait(seconds=300)
175
176 def user_favlist(self):
177 endpoint = "/opus/feed/fav"
178 params = {"page": 1, "page_size": 20}
179
180 while True:
181 data = self._call(endpoint, params)["data"]
182
183 yield from data["items"]
184
185 if not data.get("has_more"):
186 break
187 params["page"] += 1
188
189 def login_user_id(self):
190 url = "https://api.bilibili.com/x/space/v2/myinfo"
191 data = self.extractor.request_json(url)
192
193 if data["code"] != 0:
194 self.extractor.log.debug("Server response: %s", data)
195 raise self.exc.AbortExtraction(
196 "API request failed. Are you logges in?")
197 try:
198 return data["data"]["profile"]["mid"]
199 except Exception:
200 raise self.exc.AbortExtraction("API request failed")