Debian Codegraph @

gallery_dl/extractor/plurk.py

raw symbols SCIP
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.plurk.com/"""
10
11 from .common import Extractor, Message
12 from .. import text, util, dt
13
14 BASE_PATTERN = r"(?:https?://)?(?:www\.)?plurk\.com"
15
16
17 class PlurkExtractor(Extractor):
18 """Base class for plurk extractors"""
19 category = "plurk"
20 root = "https://www.plurk.com"
21 directory_fmt = ("{category}", "{user_id}")
22 filename_fmt = "{plurk_id}_{num}.{extension}"
23 archive_fmt = "{plurk_id}_{num}"
24 request_interval = (0.5, 1.5)
25
26 def items(self):
27 urls = self._urls_ex if self.config("comments", False) else self._urls
28 replurk = self.config("replurk", False)
29 external = self.config("external", False)
30 internal = (
31 "https://images.plurk.com/",
32 "https://imgs.plurk.com/",
33 "http://images.plurk.com/",
34 "http://imgs.plurk.com/",
35 )
36
37 for plurk in self.plurks():
38 if not replurk and plurk.get("replurked"):
39 continue
40 plurk["plurk_id_base36"] = util.b36encode(plurk.get("plurk_id"))
41 plurk["date"] = self.parse_datetime(
42 plurk.get("posted"), "%a, %d %b %Y %H:%M:%S %Z")
43 if plurk.get("last_edited"):
44 plurk["date_edited"] = self.parse_datetime(
45 plurk.get("last_edited"), "%a, %d %b %Y %H:%M:%S %Z")
46 plurk.pop("favorers", None)
47 plurk.pop("replurkers", None)
48
49 num = 1
50 yield Message.Directory, "", plurk
51 for url in urls(plurk):
52 data = plurk.copy()
53 data["num"] = num
54 if url.startswith(internal):
55 yield Message.Url, url, text.nameext_from_url(url, data)
56 num += 1
57 elif external:
58 text.nameext_from_url(url, data)
59 yield Message.Queue, url, data
60 num += 1
61
62 def _urls(self, obj):
63 """Extract URLs from a 'plurk' object"""
64 return text.extract_iter(obj["content"], ' href="', '"')
65
66 def _urls_ex(self, plurk):
67 """Extract URLs from a 'plurk' and its comments"""
68 yield from self._urls(plurk)
69 for comment in self._comments(plurk):
70 yield from self._urls(comment)
71
72 def _comments(self, plurk):
73 """Return an iterable with a 'plurk's comments"""
74 url = "https://www.plurk.com/Responses/get"
75 data = {"plurk_id": plurk["id"], "count": "200"}
76 headers = {"X-Requested-With": "XMLHttpRequest"}
77
78 while True:
79 info = self.request_json(
80 url, method="POST", headers=headers, data=data)
81 yield from info["responses"]
82 if not info["has_newer"]:
83 return
84 elif info["has_newer"] < 200:
85 del data["count"]
86 data["from_response_id"] = info["responses"][-1]["id"] + 1
87
88 def _load(self, data):
89 if not data:
90 raise self.exc.NotFoundError("user")
91 return util.json_loads(
92 text.re(r"new Date\(([^)]+)\)").sub(r"\1", data))
93
94
95 class PlurkTimelineExtractor(PlurkExtractor):
96 """Extractor for a plurk timeline"""
97 subcategory = "timeline"
98 pattern = BASE_PATTERN + r"/(?!p/)([^/?#]+)"
99 example = "https://www.plurk.com/USER"
100
101 def plurks(self):
102 url = f"{self.root}/{self.groups[0]}"
103 page = self.request(url).text
104 user_id, pos = text.extract(page, '"page_user": {"id":', ',')
105 plurks = self._load(text.extract(page, "_PLURKS = ", ";\n", pos)[0])
106
107 headers = {"Referer": url, "X-Requested-With": "XMLHttpRequest"}
108 data = {"user_id": user_id.strip()}
109 url = "https://www.plurk.com/TimeLine/getPlurks"
110
111 while plurks:
112 yield from plurks
113
114 offset = dt.parse(plurks[-1]["posted"], "%a, %d %b %Y %H:%M:%S %Z")
115 data["offset"] = offset.strftime("%Y-%m-%dT%H:%M:%S.000Z")
116 plurks = self.request_json(
117 url, method="POST", headers=headers, data=data)["plurks"]
118
119
120 class PlurkPostExtractor(PlurkExtractor):
121 """Extractor for a plurk post"""
122 subcategory = "post"
123 pattern = BASE_PATTERN + r"/p/([^/?#]+)"
124 example = "https://www.plurk.com/p/12345"
125
126 def plurks(self):
127 url = f"{self.root}/p/{self.groups[0]}"
128 page = self.request(url).text
129 user, pos = text.extract(page, " GLOBAL=", "\n")
130 data, pos = text.extract(page, "plurk =", ";\n", pos)
131
132 data = self._load(data)
133 try:
134 data["user"] = self._load(user)["page_user"]
135 except Exception:
136 self.log.warning("%s: Failed to extract 'user' data",
137 self.groups[0])
138 return (data,)