Debian Codegraph @

gallery_dl/extractor/subscribestar.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2020-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.subscribestar.com/"""
10
11 from .common import Extractor, Message
12 from .. import text, util
13
14 BASE_PATTERN = r"(?:https?://)?(?:www\.)?subscribestar\.(com|art|adult)"
15
16
17 class SubscribestarExtractor(Extractor):
18 """Base class for subscribestar extractors"""
19 category = "subscribestar"
20 root = "https://www.subscribestar.com"
21 directory_fmt = ("{category}", "{author_name}")
22 filename_fmt = "{post_id}_{id}.{extension}"
23 archive_fmt = "{id}"
24 cookies_domain = ".subscribestar.com"
25 cookies_names = ("_personalization_id",)
26 _warning = True
27
28 def __init__(self, match):
29 tld = match[1]
30 if tld != "com":
31 self.root = "https://subscribestar." + tld
32 self.cookies_domain = ".subscribestar." + tld
33 self.subcategory += "-adult"
34 Extractor.__init__(self, match)
35 self.item = match[2]
36
37 def items(self):
38 self.login()
39 for post_html in self.posts():
40 media = self._media_from_post(post_html)
41 data = self._data_from_post(post_html)
42
43 content = data["content"]
44 if "<html><body>" in content:
45 data["content"] = content = text.extr(
46 content, "<body>", "</body>")
47 data["title"] = text.unescape(text.rextr(content, "<h1>", "</h1>"))
48
49 yield Message.Directory, "", data
50 for num, item in enumerate(media, 1):
51 item.update(data)
52 item["num"] = num
53
54 url = item["url"]
55 if name := (item.get("name") or item.get("original_filename")):
56 text.nameext_from_name(name, item)
57 else:
58 text.nameext_from_url(url, item)
59
60 if url[0] == "/":
61 url = self.root + url
62 yield Message.Url, url, item
63
64 def posts(self):
65 """Yield HTML content of all relevant posts"""
66
67 def request(self, url, **kwargs):
68 while True:
69 response = Extractor.request(self, url, **kwargs)
70
71 if response.history and (
72 "/verify_subscriber" in response.url or
73 "/age_confirmation_warning" in response.url):
74 raise self.exc.AbortExtraction(
75 "HTTP redirect to " + response.url)
76
77 content = response.content
78 if len(content) < 250 and b">redirected<" in content:
79 url = text.unescape(text.extr(
80 content, b'href="', b'"').decode())
81 self.log.debug("HTML redirect message for %s", url)
82 continue
83
84 return response
85
86 def login(self):
87 if self.cookies_check(self.cookies_names):
88 return
89
90 username, password = self._get_auth_info()
91 if username:
92 self.cookies_update(self.cache(
93 self._login_impl, (username, self.cookies_domain), password,
94 _exp=28*86400, _mem=False))
95
96 if self._warning:
97 if not username or not self.cookies_check(self.cookies_names):
98 self.log.warning("no '_personalization_id' cookie set")
99 SubscribestarExtractor._warning = False
100
101 def _login_impl(self, username, password):
102 username = username[0]
103 self.log.info("Logging in as %s", username)
104
105 if not self.root.endswith(".com"):
106 self.cookies.set("18_plus_agreement_generic", "true",
107 domain=self.cookies_domain)
108
109 # load login page
110 url = self.root + "/login"
111 page = self.request(url).text
112
113 headers = {
114 "Accept": "*/*;q=0.5, text/javascript, application/javascript, "
115 "application/ecmascript, application/x-ecmascript",
116 "Referer": self.root + "/login",
117 "X-CSRF-Token": text.unescape(text.extr(
118 page, '<meta name="csrf-token" content="', '"')),
119 "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
120 "X-Requested-With": "XMLHttpRequest",
121 }
122
123 def check_errors(response):
124 if errors := response.json().get("errors"):
125 self.log.debug(errors)
126 try:
127 msg = f'"{errors.popitem()[1]}"'
128 except Exception:
129 msg = None
130 raise self.exc.AuthenticationError(msg)
131 return response
132
133 # submit username / email
134 url = self.root + "/session.json"
135 data = {"email": username}
136 response = check_errors(self.request(
137 url, method="POST", headers=headers, data=data, fatal=False))
138
139 # submit password
140 url = self.root + "/session/password.json"
141 data = {"password": password}
142 response = check_errors(self.request(
143 url, method="POST", headers=headers, data=data, fatal=False))
144
145 # return cookies
146 return {
147 cookie.name: cookie.value
148 for cookie in response.cookies
149 }
150
151 def _pagination(self, url, params=None):
152 needle_next_page = 'data-role="infinite_scroll-next_page" href="'
153 page = self.request(url, params=params).text
154
155 while True:
156 posts = page.split('<div class="post ')[1:]
157 if not posts:
158 return
159 yield from posts
160
161 url = text.extr(posts[-1], needle_next_page, '"')
162 if not url:
163 return
164 page = self.request_json(self.root + text.unescape(url))["html"]
165
166 def _media_from_post(self, html):
167 media = []
168
169 if gallery := text.extr(html, 'data-gallery="', '"'):
170 for item in util.json_loads(text.unescape(gallery)):
171 if "/previews" in item["url"]:
172 self._warn_preview()
173 else:
174 media.append(item)
175
176 attachments = text.extr(
177 html, 'class="uploads-docs"', 'class="post-edit_form"')
178 if attachments:
179 for att in text.re(r'class="doc_preview[" ]').split(
180 attachments)[1:]:
181 media.append({
182 "id" : text.parse_int(text.extr(
183 att, 'data-upload-id="', '"')),
184 "name": text.unescape(text.extr(
185 att, 'doc_preview-title">', '<')),
186 "url" : text.unescape(text.extr(att, 'href="', '"')),
187 "type": "attachment",
188 })
189
190 audios = text.extr(
191 html, 'class="uploads-audios"', 'class="post-edit_form"')
192 if audios:
193 for audio in text.re(r'class="audio_preview-data[" ]').split(
194 audios)[1:]:
195 media.append({
196 "id" : text.parse_int(text.extr(
197 audio, 'data-upload-id="', '"')),
198 "name": text.unescape(text.extr(
199 audio, 'audio_preview-title">', '<')),
200 "url" : text.unescape(text.extr(audio, 'src="', '"')),
201 "type": "audio",
202 })
203
204 return media
205
206 def _data_from_post(self, html):
207 extr = text.extract_from(html)
208 return {
209 "post_id" : text.parse_int(extr('data-id="', '"')),
210 "author_id" : text.parse_int(extr('data-user-id="', '"')),
211 "author_name": text.unescape(extr('href="/', '"')),
212 "author_nick": text.unescape(extr('>', '<')),
213 "date" : self._parse_datetime(extr(
214 'class="post-date">', '</').rpartition(">")[2]),
215 "content" : extr(
216 '<div class="post-content" data-role="post_content-text">',
217 '</div><div class="post-uploads for-youtube"').strip(),
218 "tags" : list(text.extract_iter(extr(
219 '<div class="post_tags for-post">',
220 '<div class="post-actions">'), '?tag=', '"')),
221 }
222
223 def _parse_datetime(self, dt):
224 if dt.startswith("Updated on "):
225 dt = dt[11:]
226 date = self.parse_datetime(dt, "%b %d, %Y %I:%M %p")
227 if date is dt:
228 date = self.parse_datetime(dt, "%B %d, %Y %I:%M %p")
229 return date
230
231 def _warn_preview(self):
232 self.log.warning("Preview image detected")
233 self._warn_preview = util.noop
234
235
236 class SubscribestarUserExtractor(SubscribestarExtractor):
237 """Extractor for media from a subscribestar user"""
238 subcategory = "user"
239 pattern = BASE_PATTERN + r"/(?!posts/)([^/?#]+)(?:\?([^#]+))?"
240 example = "https://www.subscribestar.com/USER"
241
242 def posts(self):
243 _, user, qs = self.groups
244 url = f"{self.root}/{user}"
245
246 if qs is None:
247 params = None
248 else:
249 params = text.parse_query(qs)
250 if "tag" in params:
251 self.kwdict["search_tags"] = params["tag"]
252
253 return self._pagination(url, params)
254
255
256 class SubscribestarPostExtractor(SubscribestarExtractor):
257 """Extractor for media from a single subscribestar post"""
258 subcategory = "post"
259 pattern = BASE_PATTERN + r"/posts/(\d+)"
260 example = "https://www.subscribestar.com/posts/12345"
261
262 def posts(self):
263 url = f"{self.root}/posts/{self.item}"
264 return (self.request(url).text,)
265
266 def _data_from_post(self, html):
267 extr = text.extract_from(html)
268 return {
269 "post_id" : text.parse_int(extr('data-id="', '"')),
270 "date" : self._parse_datetime(extr(
271 '<div class="section-title_date">', '<')),
272 "content" : extr(
273 '<div class="post-content" data-role="post_content-text">',
274 '</div><div class="post-uploads for-youtube"').strip(),
275 "tags" : list(text.extract_iter(extr(
276 '<div class="post_tags for-post">',
277 '<div class="post-actions">'), '?tag=', '"')),
278 "author_name": text.unescape(extr(
279 'class="star_link" href="/', '"')),
280 "author_id" : text.parse_int(extr('data-user-id="', '"')),
281 "author_nick": text.unescape(extr('alt="', '"')),
282 }