Debian Codegraph @

gallery_dl/extractor/weibo.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2019-2026 Mike Fährmann
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License version 2 as
7 # published by the Free Software Foundation.
8
9 """Extractors for https://www.weibo.com/"""
10
11 from .common import Extractor, Message, Dispatch
12 from .. import text, util
13 import random
14
15 BASE_PATTERN = r"(?:https?://)?(?:www\.|m\.)?weibo\.c(?:om|n)"
16 USER_PATTERN = BASE_PATTERN + r"/(?:(u|n|p(?:rofile)?)/)?([^/?#]+)(?:/home)?"
17
18
19 class WeiboExtractor(Extractor):
20 category = "weibo"
21 directory_fmt = ("{category}", "{user[screen_name]}")
22 filename_fmt = "{status[id]}_{num:>02}.{extension}"
23 archive_fmt = "{status[id]}_{num}"
24 cookies_domain = ".weibo.com"
25 cookies_names = ("SUB", "SUBP")
26 root = "https://weibo.com"
27 request_interval = (1.0, 2.0)
28
29 def __init__(self, match):
30 Extractor.__init__(self, match)
31 self._prefix = match[1]
32 self.user = match[2]
33
34 def _init(self):
35 self.livephoto = self.config("livephoto", True)
36 self.livephoto_video = (self.livephoto == "video")
37 self.retweets = self.config("retweets", False)
38 self.longtext = self.config("text", False)
39 self.videos = self.config("videos", True)
40 self.movies = self.config("movies", False)
41 self.likes = self.config("likes", False)
42 self.gifs = self.config("gifs", True)
43 self.gifs_video = (self.gifs == "video")
44
45 cookies = self.cache(
46 _cookie_cache, _key=None, _exp=365*86400, _mem=False)
47 if cookies is None:
48 self.logged_in = self.cookies_check(
49 self.cookies_names, self.cookies_domain)
50 return
51
52 domain = self.cookies_domain
53 cookies = {c.name: c for c in cookies if c.domain == domain}
54 for cookie in self.cookies:
55 if cookie.domain == domain and cookie.name in cookies:
56 del cookies[cookie.name]
57 if not cookies:
58 self.logged_in = True
59 return
60
61 self.logged_in = False
62 for cookie in cookies.values():
63 self.cookies.set_cookie(cookie)
64
65 def request(self, url, **kwargs):
66 response = Extractor.request(self, url, **kwargs)
67
68 if response.history:
69 if "login.sina.com" in response.url:
70 raise self.exc.AbortExtraction(
71 f"HTTP redirect to login page "
72 f"({response.url.partition('?')[0]})")
73 if "passport.weibo.com" in response.url:
74 self._sina_visitor_system(response)
75 response = Extractor.request(self, url, **kwargs)
76
77 return response
78
79 def items(self):
80 original_retweets = (self.retweets == "original")
81 is_like = text.re(r"\d-\d\d?赞过").search
82
83 for status in self.statuses():
84
85 if "ori_mid" in status and not self.retweets:
86 self.log.debug("Skipping %s (快转 retweet)", status["id"])
87 continue
88
89 if "retweeted_status" in status:
90 if not self.retweets:
91 self.log.debug("Skipping %s (retweet)", status["id"])
92 continue
93
94 # videos of the original post are in status
95 # images of the original post are in status["retweeted_status"]
96 files = []
97 self._extract_retweet(status, files)
98 self._extract_status(status["retweeted_status"], files)
99
100 if original_retweets:
101 status = status["retweeted_status"]
102 else:
103 files = []
104 self._extract_status(status, files)
105
106 if title := status.get("title"):
107 if is_like(title.get("text") or ""):
108 if not self.likes:
109 self.log.debug("Skipping %s (赞过 like)", status["id"])
110 continue
111 status["like"] = True
112 else:
113 status["like"] = False
114 else:
115 status["like"] = None
116
117 if self.longtext and status.get("isLongText") and \
118 status["text"].endswith('class="expand">展开</span>'):
119 status = self._status_by_id(status["id"])
120
121 status["date"] = self.parse_datetime(
122 status["created_at"], "%a %b %d %H:%M:%S %z %Y")
123 status["count"] = len(files)
124 yield Message.Directory, "", status
125
126 num = 0
127 for file in files:
128 url = file["url"]
129 if not url:
130 continue
131 if url.startswith("http:"):
132 url = "https:" + url[5:]
133 if "filename" not in file:
134 text.nameext_from_url(url, file)
135 if file["extension"] == "json":
136 file["extension"] = "mp4"
137 elif not file["extension"]:
138 params = text.parse_query(url[url.find("?")+1:])
139 if "livephoto" in params:
140 text.nameext_from_url(params["livephoto"], file)
141 else:
142 file["extension"] = "mp4"
143 if file["extension"] == "m3u8":
144 url = "ytdl:" + url
145 file["_ytdl_manifest"] = "hls"
146 file["extension"] = "mp4"
147 num += 1
148 file["status"] = status
149 file["num"] = num
150 yield Message.Url, url, file
151
152 def _extract_status(self, status, files):
153 if "mix_media_info" in status:
154 for item in status["mix_media_info"]["items"]:
155 type = item.get("type")
156 if type == "video":
157 if self.videos:
158 files.append(self._extract_video(
159 item["data"]["media_info"]))
160 elif type == "pic":
161 file = item["data"]["largest"].copy()
162 file["type"] = "pic"
163 files.append(file)
164 else:
165 self.log.warning("Unknown media type '%s'", type)
166 return
167
168 if pic_ids := status.get("pic_ids"):
169 pics = status["pic_infos"]
170 for pic_id in pic_ids:
171 pic = pics[pic_id]
172 pic_type = pic.get("type")
173
174 if pic_type == "gif" and self.gifs:
175 if self.gifs_video:
176 file = {"url": pic["video"]}
177 else:
178 file = pic["largest"].copy()
179
180 elif pic_type == "livephoto" and self.livephoto:
181 if not self.livephoto_video:
182 file = pic["largest"].copy()
183 file["type"] = "livephoto"
184 files.append(file)
185 file = {"url": pic["video"]}
186
187 else:
188 file = pic["largest"].copy()
189 file["type"] = pic_type
190 files.append(file)
191
192 if "page_info" in status:
193 info = status["page_info"]
194 if "media_info" in info and self.videos:
195 if info.get("type") != "5" or self.movies:
196 files.append(self._extract_video(info["media_info"]))
197 else:
198 self.log.debug("%s: Ignoring 'movie' video", status["id"])
199
200 def _extract_retweet(self, status, files):
201 self._extract_status(status, files)
202 if "url_struct" in status:
203 for item in status["url_struct"]:
204 if pics := item.get("pic_infos"):
205 for pic in pics.values():
206 file = pic.get("largest") or pic["large"]
207 file["type"] = "pic"
208 files.append(file)
209
210 def _extract_video(self, info):
211 if info.get("live_status") == 1:
212 self.log.debug("Skipping ongoing live stream")
213 return {"url": ""}
214
215 try:
216 media = max(info["playback_list"],
217 key=lambda m: m["meta"].get("quality_index", 0))
218 except Exception:
219 video = {"url": (info.get("replay_hd") or
220 info.get("stream_url_hd") or
221 info.get("stream_url") or "")}
222 else:
223 video = media["play_info"].copy()
224
225 if "//wblive-out." in video["url"] and \
226 not text.ext_from_url(video["url"]):
227 try:
228 video["url"] = self.request_location(video["url"])
229 except self.exc.HttpError as exc:
230 self.log.warning("%s: %s", exc.__class__.__name__, exc)
231 video["url"] = ""
232
233 video["type"] = "video"
234 return video
235
236 def _status_by_id(self, status_id):
237 url = (f"{self.root}/ajax/statuses/show"
238 f"?id={status_id}&isGetLongText=true")
239 return self.request_json(url)
240
241 def _user(self, user):
242 url = (f"{self.root}/ajax/profile/info?"
243 f"{'screen_name' if self._prefix == 'n' else 'custom'}={user}")
244 return self.request_json(url, interval=False)["data"]["user"]
245
246 def _user_id(self):
247 user = self.user
248 if len(user) >= 10 and user.isdecimal():
249 return user[-10:]
250 else:
251 return self._user(user)["idstr"]
252
253 def _pagination(self, endpoint, params,
254 since_key="sinceid", subalbums=None):
255 url = f"{self.root}/ajax{endpoint}"
256 headers = {
257 "Accept": "application/json, text/plain, */*",
258 "X-Requested-With": "XMLHttpRequest",
259 "X-XSRF-TOKEN": None,
260 "Referer": f"{self.root}/u/{params['uid']}",
261 }
262
263 while True:
264 response = self.request(url, params=params, headers=headers)
265 headers["X-XSRF-TOKEN"] = response.cookies.get("XSRF-TOKEN")
266
267 data = response.json()
268 if not (ok := data.get("ok", 0)):
269 self.log.debug(response.content)
270 if "since_id" not in params: # first iteration
271 raise self.exc.AbortExtraction(
272 f'"{data.get("msg") or "unknown error"}"')
273 elif ok < 0:
274 self.request(self.root + "/").content
275 continue
276
277 try:
278 data = data["data"]
279 statuses = data["list"]
280 except KeyError:
281 return
282
283 if subalbums is not None:
284 subalbums = None
285 yield data.get("album_list") or ()
286
287 yield from statuses
288
289 # videos, newvideo
290 if cursor := data.get("next_cursor"):
291 if cursor == -1:
292 return
293 params["cursor"] = cursor
294 continue
295
296 # album
297 if "since_id" in data:
298 params[since_key] = since_id = data["since_id"]
299 if not since_id:
300 return
301 if "page" in params:
302 params["page"] += 1
303 continue
304
305 # home, article
306 if "page" in params:
307 if not statuses:
308 return
309 params["page"] += 1
310 continue
311
312 # feed, last album page
313 try:
314 params["since_id"] = statuses[-1]["id"] - 1
315 except LookupError:
316 return
317
318 def _sina_visitor_system(self, response):
319 self.log.info("Sina Visitor System")
320
321 passport_url = "https://passport.weibo.com/visitor/genvisitor2"
322 headers = {"Referer": response.url}
323 data = {
324 "cb" : "visitor_gray_callback",
325 "ver" : "20250916",
326 "tid" : "",
327 "from": "weibo",
328 "webdriver" : "false",
329 "return_url": "https://weibo.com/",
330 }
331
332 page = Extractor.request(
333 self, passport_url, method="POST", headers=headers, data=data).text
334 data = util.json_loads(text.extr(page, "(", ");"))["data"]
335
336 passport_url = "https://passport.weibo.com/visitor/visitor"
337 params = {
338 "a" : "crossdomain",
339 "t" : data.get("tid"),
340 "sp" : data["subp"],
341 "s" : data["sub"],
342 "from" : "weibo",
343 "_rand": random.random(),
344 "url" : response.url
345 }
346 response = Extractor.request(
347 self, passport_url, params=params, allow_redirects=False)
348 self.cache_update(
349 _cookie_cache, ..., response.cookies, _exp=365*86400)
350
351
352 class WeiboUserExtractor(WeiboExtractor):
353 """Extractor for weibo user profiles"""
354 subcategory = "user"
355 pattern = USER_PATTERN + r"(?:$|#)"
356 example = "https://weibo.com/USER"
357
358 # do NOT override 'initialize()'
359 # it is needed for 'self._user_id()'
360 # def initialize(self):
361 # pass
362
363 def items(self):
364 base = f"{self.root}/u/{self._user_id()}?tabtype="
365 return Dispatch._dispatch_extractors(self, (
366 (WeiboHomeExtractor , base + "home"),
367 (WeiboFeedExtractor , base + "feed"),
368 (WeiboVideosExtractor , base + "video"),
369 (WeiboNewvideoExtractor, base + "newVideo"),
370 (WeiboArticleExtractor , base + "article"),
371 (WeiboAlbumExtractor , base + "album"),
372 ), ("feed",), {
373 ("album", "subalbums", base + "album-only"),
374 })
375
376
377 class WeiboHomeExtractor(WeiboExtractor):
378 """Extractor for weibo 'home' listings"""
379 subcategory = "home"
380 pattern = USER_PATTERN + r"\?tabtype=home"
381 example = "https://weibo.com/USER?tabtype=home"
382
383 def statuses(self):
384 endpoint = "/profile/myhot"
385 params = {"uid": self._user_id(), "page": 1, "feature": "2"}
386 return self._pagination(endpoint, params)
387
388
389 class WeiboFeedExtractor(WeiboExtractor):
390 """Extractor for weibo user feeds"""
391 subcategory = "feed"
392 pattern = USER_PATTERN + r"\?tabtype=feed"
393 example = "https://weibo.com/USER?tabtype=feed"
394
395 def statuses(self):
396 endpoint = "/statuses/mymblog"
397 params = {"uid": self._user_id(), "feature": "0"}
398 if self.logged_in:
399 params["page"] = 1
400 return self._pagination(endpoint, params)
401
402
403 class WeiboVideosExtractor(WeiboExtractor):
404 """Extractor for weibo 'video' listings"""
405 subcategory = "videos"
406 pattern = USER_PATTERN + r"\?tabtype=video"
407 example = "https://weibo.com/USER?tabtype=video"
408
409 def statuses(self):
410 endpoint = "/profile/getprofilevideolist"
411 params = {"uid": self._user_id()}
412
413 for status in self._pagination(endpoint, params):
414 yield status["video_detail_vo"]
415
416
417 class WeiboNewvideoExtractor(WeiboExtractor):
418 """Extractor for weibo 'newVideo' listings"""
419 subcategory = "newvideo"
420 pattern = USER_PATTERN + r"\?tabtype=newVideo"
421 example = "https://weibo.com/USER?tabtype=newVideo"
422
423 def statuses(self):
424 endpoint = "/profile/getWaterFallContent"
425 params = {"uid": self._user_id()}
426 return self._pagination(endpoint, params)
427
428
429 class WeiboArticleExtractor(WeiboExtractor):
430 """Extractor for weibo 'article' listings"""
431 subcategory = "article"
432 pattern = USER_PATTERN + r"\?tabtype=article"
433 example = "https://weibo.com/USER?tabtype=article"
434
435 def statuses(self):
436 endpoint = "/statuses/mymblog"
437 params = {"uid": self._user_id(), "page": 1, "feature": "10"}
438 return self._pagination(endpoint, params)
439
440
441 class WeiboAlbumExtractor(WeiboExtractor):
442 """Extractor for weibo 'album' listings"""
443 subcategory = "album"
444 pattern = USER_PATTERN + r"\?tabtype=album(?:[:_-]([^&#]+))?"
445 example = "https://weibo.com/USER?tabtype=album"
446
447 def items(self):
448 subalbum = self.groups[2]
449
450 if not subalbum and not self.config("subalbums", False):
451 return WeiboExtractor.items(self)
452
453 self.directory_fmt = ("{category}", "{user[screen_name]}",
454 "Album", "{subalbum[pic_title]|''}")
455 self.filename_fmt = "{filename}.{extension}"
456 self.archive_fmt = "{subalbum[pic_title]}_{pid}"
457 return self.items_subalbum(subalbum)
458
459 def items_subalbum(self, subalbum):
460 user = self.kwdict["user"] = self._user(self.user)
461 base = self.root + "/ajax/common/download?pid="
462
463 for data, files in self.albums(user["idstr"], subalbum):
464 self.kwdict["subalbum"] = data
465 yield Message.Directory, "", {}
466 for file in files:
467 if "pid" in file:
468 file["filename"] = file["pid"]
469 file["extension"] = "jpg"
470 yield Message.Url, base + file["pid"], file
471 elif "mid" in file:
472 mid = file["mid"]
473 status = self._status_by_id(mid)
474 if status.get("ok") != 1:
475 self.log.debug("Skipping status %s (%s)", mid, status)
476 else:
477 self.statuses = lambda: (status,)
478 yield from WeiboExtractor.items(self)
479 yield Message.Directory, "", {}
480
481 def statuses(self):
482 endpoint = "/profile/getImageWall"
483 params = {"uid": self._user_id()}
484
485 seen = set()
486 for image in self._pagination(endpoint, params):
487 mid = image["mid"]
488 if mid not in seen:
489 seen.add(mid)
490 status = self._status_by_id(mid)
491 if status.get("ok") != 1:
492 self.log.debug("Skipping status %s (%s)", mid, status)
493 else:
494 yield status
495
496 def albums(self, uid, subalbum):
497 endpoint = "/profile/getImageWall"
498 params = {
499 "uid" : uid,
500 "sinceid" : "0",
501 "has_album": "true",
502 }
503 album = self._pagination(endpoint, params, subalbums=True)
504 subalbums = next(album, ())
505
506 if not subalbum or subalbum == "0":
507 return (({}, album),)
508
509 if subalbum == "all":
510 results = [
511 (sub, self._pagination_subalbum(uid, sub))
512 for sub in subalbums
513 ]
514 results.append(({}, album))
515 return results
516
517 if subalbum == "only":
518 return [
519 (sub, self._pagination_subalbum(uid, sub))
520 for sub in subalbums
521 ]
522
523 if subalbum.isdecimal():
524 try:
525 sub = subalbums[int(subalbum)-1]
526 except Exception:
527 raise self.exc.NotFoundError("subalbum")
528 else:
529 subalbum = text.unquote(subalbum)
530 for sub in subalbums:
531 if sub["pic_title"] == subalbum:
532 break
533 else:
534 raise self.exc.NotFoundError("subalbum")
535 return ((sub, self._pagination_subalbum(uid, sub)),)
536
537 def _pagination_subalbum(self, uid, sub):
538 params = {"uid": uid, "containerid": text.unquote(sub["containerid"])}
539 return self._pagination("/profile/getAlbumDetail", params, "since_id")
540
541
542 class WeiboStatusExtractor(WeiboExtractor):
543 """Extractor for a weibo status"""
544 subcategory = "status"
545 pattern = BASE_PATTERN + r"/(detail|status|\d+)/(\w+)"
546 example = "https://weibo.com/detail/12345"
547
548 def statuses(self):
549 status = self._status_by_id(self.user)
550 if status.get("ok") != 1:
551 self.log.debug(status)
552 raise self.exc.NotFoundError("status")
553 return (status,)
554
555
556 def _cookie_cache():
557 return None