Debian Codegraph @

gallery_dl/extractor/sexcom.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2019-2025 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.sex.com/"""
10
11 from .common import Extractor, Message
12 from .. import text, dt
13
14 BASE_PATTERN = r"(?:https?://)?(?:www\.)?sex\.com(?:/[a-z]{2})?"
15
16
17 class SexcomExtractor(Extractor):
18 """Base class for sexcom extractors"""
19 category = "sexcom"
20 directory_fmt = ("{category}")
21 filename_fmt = "{pin_id}{title:? //}.{extension}"
22 archive_fmt = "{pin_id}"
23 root = "https://www.sex.com"
24
25 def items(self):
26 self.gifs = self.config("gifs", True)
27
28 yield Message.Directory, "", self.metadata()
29 for pin in map(self._parse_pin, self.pins()):
30 if not pin:
31 continue
32
33 url = pin["url"]
34 parts = url.rsplit("/", 4)
35 try:
36 pin["date_url"] = d = dt.datetime(
37 int(parts[1]), int(parts[2]), int(parts[3]))
38 if "date" not in pin:
39 pin["date"] = d
40 except Exception:
41 pass
42 pin["tags"] = [t[1:] if t[0] == "@" else t for t in pin["tags"]]
43
44 yield Message.Url, url, pin
45
46 def metadata(self):
47 return {}
48
49 def pins(self):
50 return ()
51
52 def _pagination(self, url):
53 while True:
54 extr = text.extract_from(self.request(url).text)
55 url = extr('<link rel="next" href="', '"')
56
57 while True:
58 href = extr('<a class="image_wrapper" href="', '"')
59 if not href:
60 break
61 yield self.root + href
62
63 if not url:
64 return
65 url = text.urljoin(self.root, text.unescape(url))
66
67 def _parse_pin(self, url):
68 if "/pin/" in url:
69 if url[-1] != "/":
70 url += "/"
71 elif url[-1] == "/":
72 url = url[:-1]
73
74 response = self.request(url, fatal=False, allow_redirects=False)
75 location = response.headers.get("location")
76
77 if location:
78 if location[0] == "/":
79 location = self.root + location
80 if len(location) <= 25:
81 return self.log.warning(
82 'Unable to fetch %s: Redirect to homepage', url)
83 response = self.request(location, fatal=False)
84
85 if response.status_code >= 400:
86 return self.log.warning('Unable to fetch %s: %s %s',
87 url, response.status_code, response.reason)
88
89 if "/pin/" in response.url:
90 return self._parse_pin_legacy(response)
91 if "/videos/" in response.url:
92 return self._parse_pin_video(response)
93 return self._parse_pin_image(response)
94
95 def _parse_pin_legacy(self, response):
96 extr = text.extract_from(response.text)
97 data = {}
98
99 data["_http_headers"] = {"Referer": response.url}
100 data["thumbnail"] = extr('itemprop="thumbnail" content="', '"')
101 data["type"] = extr('<h1>' , '<').rstrip(" -").strip().lower()
102 data["title"] = text.unescape(extr('itemprop="name">' , '<'))
103 data["repins"] = text.parse_int(text.extract(
104 extr('"btn-group"', '</div>'), '"btn btn-primary">' , '<')[0])
105 data["likes"] = text.parse_int(text.extract(
106 extr('"btn-group"', '</div>'), '"btn btn-default">' , '<')[0])
107 data["pin_id"] = text.parse_int(extr('data-id="', '"'))
108
109 if data["type"] == "video":
110 info = extr("player.updateSrc(", ");")
111
112 if info:
113 try:
114 path = text.rextr(
115 info, "src: '", "'", info.index("label: 'HD'"))
116 except ValueError:
117 path = text.extr(info, "src: '", "'")
118 text.nameext_from_url(path, data)
119 data["url"] = path
120 else:
121 iframe = extr('<iframe', '>')
122 src = (text.extr(iframe, ' src="', '"') or
123 text.extr(iframe, " src='", "'"))
124 if not src:
125 self.log.warning(
126 "Unable to fetch media from %s", response.url)
127 return None
128 data["extension"] = None
129 data["url"] = "ytdl:" + src
130 else:
131 data["_http_validate"] = _check_empty
132 url = text.unescape(extr(' src="', '"'))
133 data["url"] = url.partition("?")[0]
134 data["_fallback"] = (url,)
135 text.nameext_from_url(data["url"], data)
136
137 data["uploader"] = extr('itemprop="author">', '<')
138 data["date"] = dt.parse_iso(extr('datetime="', '"'))
139 data["tags"] = text.split_html(extr('class="tags"> Tags', '</div>'))
140 data["comments"] = text.parse_int(extr('Comments (', ')'))
141
142 return data
143
144 def _parse_pin_image(self, response):
145 extr = text.extract_from(response.text)
146 href = extr(' href="', '"').partition("?")[0]
147 title, _, type = extr("<title>", " | ").rpartition(" ")
148
149 data = {
150 "_http_headers": {"Referer": response.url},
151 "url": href,
152 "title": text.unescape(title),
153 "pin_id": text.parse_int(extr(
154 'rel="canonical" href="', '"').rpartition("/")[2]),
155 "tags": text.split_html(extr("</h1>", "</section>")),
156 }
157
158 text.nameext_from_url(href, data)
159 if type.lower() == "pic":
160 data["type"] = "picture"
161 else:
162 data["type"] = "gif"
163 if self.gifs and data["extension"] == "webp":
164 data["extension"] = "gif"
165 data["_fallback"] = (href,)
166 data["url"] = href[:-4] + "gif"
167
168 return data
169
170 def _parse_pin_video(self, response):
171 extr = text.extract_from(response.text)
172
173 if not self.cookies.get("CloudFront-Key-Pair-Id", domain=".sex.com"):
174 self.log.warning("CloudFront cookies required for video downloads")
175
176 data = {
177 "_ytdl_manifest": "hls",
178 "_ytdl_manifest_headers": {"Referer": response.url},
179 "extension": "mp4",
180 "type": "video",
181 "title": text.unescape(extr("<title>", " | Sex.com<")),
182 "pin_id": text.parse_int(extr(
183 'rel="canonical" href="', '"').rpartition("/")[2]),
184 "tags": text.split_html(extr(
185 'event_name="video_tags_click"', "<div data-testid=")
186 .partition(">")[2]),
187 "url": "ytdl:" + extr('<source src="', '"'),
188 }
189
190 return data
191
192
193 class SexcomPinExtractor(SexcomExtractor):
194 """Extractor for a pinned image or video on www.sex.com"""
195 subcategory = "pin"
196 directory_fmt = ("{category}",)
197 pattern = (BASE_PATTERN +
198 r"(/(?:\w\w/(?:pic|gif|video)s|pin)/\d+/?)(?!.*#related$)")
199 example = "https://www.sex.com/pin/12345-TITLE/"
200
201 def pins(self):
202 return (self.root + self.groups[0],)
203
204
205 class SexcomRelatedPinExtractor(SexcomPinExtractor):
206 """Extractor for related pins on www.sex.com"""
207 subcategory = "related-pin"
208 directory_fmt = ("{category}", "related {original_pin[pin_id]}")
209 pattern = BASE_PATTERN + r"(/pin/(\d+)/?).*#related$"
210 example = "https://www.sex.com/pin/12345#related"
211
212 def metadata(self):
213 pin = self._parse_pin(SexcomPinExtractor.pins(self)[0])
214 return {"original_pin": pin}
215
216 def pins(self):
217 url = (f"{self.root}/pin/related?pinId={self.groups[1]}"
218 f"&limit=24&offset=0")
219 return self._pagination(url)
220
221
222 class SexcomPinsExtractor(SexcomExtractor):
223 """Extractor for a user's pins on www.sex.com"""
224 subcategory = "pins"
225 directory_fmt = ("{category}", "{user}")
226 pattern = BASE_PATTERN + r"/user/([^/?#]+)/pins/"
227 example = "https://www.sex.com/user/USER/pins/"
228
229 def metadata(self):
230 return {"user": text.unquote(self.groups[0])}
231
232 def pins(self):
233 url = f"{self.root}/user/{self.groups[0]}/pins/"
234 return self._pagination(url)
235
236
237 class SexcomLikesExtractor(SexcomExtractor):
238 """Extractor for a user's liked pins on www.sex.com"""
239 subcategory = "likes"
240 directory_fmt = ("{category}", "{user}", "Likes")
241 pattern = BASE_PATTERN + r"/user/([^/?#]+)/likes/"
242 example = "https://www.sex.com/user/USER/likes/"
243
244 def metadata(self):
245 return {"user": text.unquote(self.groups[0])}
246
247 def pins(self):
248 url = f"{self.root}/user/{self.groups[0]}/likes/"
249 return self._pagination(url)
250
251
252 class SexcomBoardExtractor(SexcomExtractor):
253 """Extractor for pins from a board on www.sex.com"""
254 subcategory = "board"
255 directory_fmt = ("{category}", "{user}", "{board}")
256 pattern = (BASE_PATTERN + r"/user"
257 r"/([^/?#]+)/(?!(?:following|pins|repins|likes)/)([^/?#]+)")
258 example = "https://www.sex.com/user/USER/BOARD/"
259
260 def metadata(self):
261 self.user, self.board = self.groups
262 return {
263 "user" : text.unquote(self.user),
264 "board": text.unquote(self.board),
265 }
266
267 def pins(self):
268 url = f"{self.root}/user/{self.user}/{self.board}/"
269 return self._pagination(url)
270
271
272 class SexcomFeedExtractor(SexcomExtractor):
273 """Extractor for pins from your account's main feed on www.sex.com"""
274 subcategory = "feed"
275 directory_fmt = ("{category}", "feed")
276 pattern = BASE_PATTERN + r"/feed"
277 example = "https://www.sex.com/feed/"
278
279 def metadata(self):
280 return {"feed": True}
281
282 def pins(self):
283 if not self.cookies_check(("sess_sex",)):
284 self.log.warning("no 'sess_sex' cookie set")
285 url = self.root + "/feed/"
286 return self._pagination(url)
287
288
289 class SexcomSearchExtractor(SexcomExtractor):
290 """Extractor for search results on www.sex.com"""
291 subcategory = "search"
292 directory_fmt = ("{category}", "search", "{search[search]}")
293 pattern = (BASE_PATTERN + r"/(?:"
294 r"(pic|gif|video)s(?:\?(search=[^#]+)$|/([^/?#]*))"
295 r"|search/(pic|gif|video)s"
296 r")/?(?:\?([^#]+))?")
297 example = "https://www.sex.com/search/pics?query=QUERY"
298
299 def _init(self):
300 t1, qs1, search_alt, t2, qs2 = self.groups
301
302 self.params = params = text.parse_query(qs1 or qs2)
303 if "query" in params:
304 params["search"] = params.pop("query")
305 params.setdefault("sexual-orientation", "straight")
306 params.setdefault("order", "likeCount")
307 params.setdefault("search", search_alt or "")
308
309 self.kwdict["search"] = search = params.copy()
310 search["type"] = self.type = t1 or t2
311
312 def items(self):
313 root = "https://imagex1.sx.cdn.live"
314 type = self.type
315 gifs = self.config("gifs", True)
316
317 url = (f"{self.root}/portal/api/"
318 f"{'picture' if type == 'pic' else type}s/search")
319 params = self.params
320 params["page"] = text.parse_int(params.get("page"), 1)
321 params["limit"] = 40
322
323 while True:
324 data = self.request_json(url, params=params)
325
326 for pin in data["data"]:
327 path = pin["uri"]
328 pin["pin_id"] = pin.pop("id")
329 text.nameext_from_url(path, pin)
330
331 parts = path.rsplit("/", 4)
332 try:
333 pin["date_url"] = pin["date"] = dt.datetime(
334 int(parts[1]), int(parts[2]), int(parts[3]))
335 except Exception:
336 pass
337
338 if type == "pic":
339 pin["type"] = "picture"
340 else:
341 pin["type"] = "gif"
342 if gifs and pin["extension"] == "webp":
343 pin["extension"] = "gif"
344 pin["_fallback"] = (root + path,)
345 path = path[:-4] + "gif"
346
347 pin["url"] = root + path
348 yield Message.Directory, "", pin
349 yield Message.Url, pin["url"], pin
350
351 if params["page"] >= data["paging"]["numberOfPages"]:
352 break
353 params["page"] += 1
354
355
356 def _check_empty(response):
357 return response.headers.get("content-length") != "0"