]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/xhamster.py
[misc] Add `hatch`, `ruff`, `pre-commit` and improve dev docs (#7409)
[yt-dlp.git] / yt_dlp / extractor / xhamster.py
CommitLineData
df228355 1import itertools
cb10cded
PH
2import re
3
4from .common import InfoExtractor
d852c6bc 5from ..compat import compat_str
cb10cded 6from ..utils import (
e897bd82 7 ExtractorError,
85552042 8 clean_html,
fea92aa6 9 determine_ext,
065c4b27 10 dict_get,
df228355 11 extract_attributes,
cc2db878 12 float_or_none,
ccb079ee 13 int_or_none,
51378d35 14 parse_duration,
cc2db878 15 str_or_none,
fea92aa6 16 try_get,
44731e30 17 unified_strdate,
3052a30d 18 url_or_none,
cc2db878 19 urljoin,
cb10cded
PH
20)
21
22
23class XHamsterIE(InfoExtractor):
45b2ee6f 24 _DOMAINS = r'(?:xhamster\.(?:com|one|desi)|xhms\.pro|xhamster\d+\.com|xhday\.com|xhvid\.com)'
00e5c363
S
25 _VALID_URL = r'''(?x)
26 https?://
b634ba74 27 (?:[^/?#]+\.)?%s/
00e5c363 28 (?:
6cb30ea5
J
29 movies/(?P<id>[\dA-Za-z]+)/(?P<display_id>[^/]*)\.html|
30 videos/(?P<display_id_2>[^/]*)-(?P<id_2>[\dA-Za-z]+)
00e5c363 31 )
8945b10f 32 ''' % _DOMAINS
6b43132c 33 _TESTS = [{
8945b10f 34 'url': 'https://xhamster.com/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
6d1b3489 35 'md5': '34e1ab926db5dc2750fed9e1f34304bb',
6b43132c
S
36 'info_dict': {
37 'id': '1509445',
8945b10f 38 'display_id': 'femaleagent-shy-beauty-takes-the-bait',
6b43132c
S
39 'ext': 'mp4',
40 'title': 'FemaleAgent Shy beauty takes the bait',
fea92aa6 41 'timestamp': 1350194821,
6b43132c
S
42 'upload_date': '20121014',
43 'uploader': 'Ruseful2011',
6d1b3489 44 'uploader_id': 'ruseful2011',
51378d35 45 'duration': 893,
6b43132c 46 'age_limit': 18,
ccb079ee 47 },
6b43132c 48 }, {
8945b10f 49 'url': 'https://xhamster.com/videos/britney-spears-sexy-booty-2221348?hd=',
6b43132c
S
50 'info_dict': {
51 'id': '2221348',
8945b10f 52 'display_id': 'britney-spears-sexy-booty',
6b43132c
S
53 'ext': 'mp4',
54 'title': 'Britney Spears Sexy Booty',
fea92aa6 55 'timestamp': 1379123460,
6b43132c
S
56 'upload_date': '20130914',
57 'uploader': 'jojo747400',
51378d35 58 'duration': 200,
6b43132c 59 'age_limit': 18,
5b9aefef 60 },
6b43132c
S
61 'params': {
62 'skip_download': True,
a4690b32 63 },
6b43132c 64 }, {
8945b10f 65 # empty seo, unavailable via new URL schema
6b43132c
S
66 'url': 'http://xhamster.com/movies/5667973/.html',
67 'info_dict': {
68 'id': '5667973',
69 'ext': 'mp4',
70 'title': '....',
fea92aa6 71 'timestamp': 1454948101,
6b43132c
S
72 'upload_date': '20160208',
73 'uploader': 'parejafree',
6d1b3489 74 'uploader_id': 'parejafree',
51378d35 75 'duration': 72,
6b43132c 76 'age_limit': 18,
5b9aefef 77 },
6b43132c
S
78 'params': {
79 'skip_download': True,
80 },
b271e335
W
81 }, {
82 # mobile site
83 'url': 'https://m.xhamster.com/videos/cute-teen-jacqueline-solo-masturbation-8559111',
84 'only_matching': True,
6b43132c
S
85 }, {
86 'url': 'https://xhamster.com/movies/2272726/amber_slayed_by_the_knight.html',
87 'only_matching': True,
103f8c8d
S
88 }, {
89 # This video is visible for marcoalfa123456's friends only
90 'url': 'https://it.xhamster.com/movies/7263980/la_mia_vicina.html',
91 'only_matching': True,
00e5c363
S
92 }, {
93 # new URL schema
94 'url': 'https://pt.xhamster.com/videos/euro-pedal-pumping-7937821',
95 'only_matching': True,
b43c5f47
S
96 }, {
97 'url': 'https://xhamster.one/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
98 'only_matching': True,
8945b10f
S
99 }, {
100 'url': 'https://xhamster.desi/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
101 'only_matching': True,
102 }, {
103 'url': 'https://xhamster2.com/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
104 'only_matching': True,
10709fc7
S
105 }, {
106 'url': 'https://xhamster11.com/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
107 'only_matching': True,
108 }, {
109 'url': 'https://xhamster26.com/videos/femaleagent-shy-beauty-takes-the-bait-1509445',
110 'only_matching': True,
8945b10f
S
111 }, {
112 'url': 'http://xhamster.com/movies/1509445/femaleagent_shy_beauty_takes_the_bait.html',
113 'only_matching': True,
114 }, {
115 'url': 'http://xhamster.com/movies/2221348/britney_spears_sexy_booty.html?hd',
116 'only_matching': True,
6cb30ea5
J
117 }, {
118 'url': 'http://de.xhamster.com/videos/skinny-girl-fucks-herself-hard-in-the-forest-xhnBJZx',
119 'only_matching': True,
6d1b3489 120 }, {
121 'url': 'https://xhday.com/videos/strapless-threesome-xhh7yVf',
122 'only_matching': True,
45b2ee6f 123 }, {
124 'url': 'https://xhvid.com/videos/lk-mm-xhc6wn6',
125 'only_matching': True,
6b43132c 126 }]
cb10cded 127
5f6a1245 128 def _real_extract(self, url):
5ad28e7f 129 mobj = self._match_valid_url(url)
00e5c363
S
130 video_id = mobj.group('id') or mobj.group('id_2')
131 display_id = mobj.group('display_id') or mobj.group('display_id_2')
132
b271e335 133 desktop_url = re.sub(r'^(https?://(?:.+?\.)?)m\.', r'\1', url)
b274e48d 134 webpage, urlh = self._download_webpage_handle(desktop_url, video_id)
cb10cded 135
103f8c8d
S
136 error = self._html_search_regex(
137 r'<div[^>]+id=["\']videoClosed["\'][^>]*>(.+?)</div>',
138 webpage, 'error', default=None)
139 if error:
140 raise ExtractorError(error, expected=True)
141
fea92aa6
S
142 age_limit = self._rta_search(webpage)
143
144 def get_height(s):
145 return int_or_none(self._search_regex(
146 r'^(\d+)[pP]', s, 'height', default=None))
147
148 initials = self._parse_json(
149 self._search_regex(
39e7107d
U
150 (r'window\.initials\s*=\s*({.+?})\s*;\s*</script>',
151 r'window\.initials\s*=\s*({.+?})\s*;'), webpage, 'initials',
fea92aa6
S
152 default='{}'),
153 video_id, fatal=False)
154 if initials:
155 video = initials['videoModel']
156 title = video['title']
157 formats = []
cc2db878 158 format_urls = set()
159 format_sizes = {}
160 sources = try_get(video, lambda x: x['sources'], dict) or {}
161 for format_id, formats_dict in sources.items():
fea92aa6
S
162 if not isinstance(formats_dict, dict):
163 continue
cc2db878 164 download_sources = try_get(sources, lambda x: x['download'], dict) or {}
165 for quality, format_dict in download_sources.items():
166 if not isinstance(format_dict, dict):
167 continue
168 format_sizes[quality] = float_or_none(format_dict.get('size'))
fea92aa6
S
169 for quality, format_item in formats_dict.items():
170 if format_id == 'download':
171 # Download link takes some time to be generated,
172 # skipping for now
173 continue
cc2db878 174 format_url = format_item
3052a30d 175 format_url = url_or_none(format_url)
cc2db878 176 if not format_url or format_url in format_urls:
fea92aa6 177 continue
cc2db878 178 format_urls.add(format_url)
fea92aa6
S
179 formats.append({
180 'format_id': '%s-%s' % (format_id, quality),
181 'url': format_url,
182 'ext': determine_ext(format_url, 'mp4'),
183 'height': get_height(quality),
cc2db878 184 'filesize': format_sizes.get(quality),
b274e48d 185 'http_headers': {
3d2623a8 186 'Referer': urlh.url,
b274e48d 187 },
fea92aa6 188 })
cc2db878 189 xplayer_sources = try_get(
190 initials, lambda x: x['xplayerSettings']['sources'], dict)
191 if xplayer_sources:
192 hls_sources = xplayer_sources.get('hls')
193 if isinstance(hls_sources, dict):
194 for hls_format_key in ('url', 'fallback'):
195 hls_url = hls_sources.get(hls_format_key)
196 if not hls_url:
197 continue
198 hls_url = urljoin(url, hls_url)
199 if not hls_url or hls_url in format_urls:
200 continue
201 format_urls.add(hls_url)
202 formats.extend(self._extract_m3u8_formats(
203 hls_url, video_id, 'mp4', entry_protocol='m3u8_native',
204 m3u8_id='hls', fatal=False))
205 standard_sources = xplayer_sources.get('standard')
206 if isinstance(standard_sources, dict):
207 for format_id, formats_list in standard_sources.items():
208 if not isinstance(formats_list, list):
209 continue
210 for standard_format in formats_list:
211 if not isinstance(standard_format, dict):
212 continue
213 for standard_format_key in ('url', 'fallback'):
214 standard_url = standard_format.get(standard_format_key)
215 if not standard_url:
216 continue
217 standard_url = urljoin(url, standard_url)
218 if not standard_url or standard_url in format_urls:
219 continue
220 format_urls.add(standard_url)
221 ext = determine_ext(standard_url, 'mp4')
222 if ext == 'm3u8':
223 formats.extend(self._extract_m3u8_formats(
224 standard_url, video_id, 'mp4', entry_protocol='m3u8_native',
225 m3u8_id='hls', fatal=False))
226 continue
227 quality = (str_or_none(standard_format.get('quality'))
228 or str_or_none(standard_format.get('label'))
229 or '')
230 formats.append({
231 'format_id': '%s-%s' % (format_id, quality),
232 'url': standard_url,
233 'ext': ext,
234 'height': get_height(quality),
235 'filesize': format_sizes.get(quality),
236 'http_headers': {
237 'Referer': standard_url,
238 },
239 })
fea92aa6
S
240
241 categories_list = video.get('categories')
242 if isinstance(categories_list, list):
243 categories = []
244 for c in categories_list:
245 if not isinstance(c, dict):
246 continue
247 c_name = c.get('name')
248 if isinstance(c_name, compat_str):
249 categories.append(c_name)
250 else:
251 categories = None
252
908b56ea 253 uploader_url = url_or_none(try_get(video, lambda x: x['author']['pageURL']))
fea92aa6
S
254 return {
255 'id': video_id,
256 'display_id': display_id,
257 'title': title,
258 'description': video.get('description'),
259 'timestamp': int_or_none(video.get('created')),
260 'uploader': try_get(
261 video, lambda x: x['author']['name'], compat_str),
908b56ea 262 'uploader_url': uploader_url,
263 'uploader_id': uploader_url.split('/')[-1] if uploader_url else None,
fea92aa6
S
264 'thumbnail': video.get('thumbURL'),
265 'duration': int_or_none(video.get('duration')),
266 'view_count': int_or_none(video.get('views')),
267 'like_count': int_or_none(try_get(
268 video, lambda x: x['rating']['likes'], int)),
269 'dislike_count': int_or_none(try_get(
270 video, lambda x: x['rating']['dislikes'], int)),
271 'comment_count': int_or_none(video.get('views')),
6d1b3489 272 'age_limit': age_limit if age_limit is not None else 18,
fea92aa6
S
273 'categories': categories,
274 'formats': formats,
275 }
276
277 # Old layout fallback
278
4395ca2e 279 title = self._html_search_regex(
1a6d9284
S
280 [r'<h1[^>]*>([^<]+)</h1>',
281 r'<meta[^>]+itemprop=".*?caption.*?"[^>]+content="(.+?)"',
282 r'<title[^>]*>(.+?)(?:,\s*[^,]*?\s*Porn\s*[^,]*?:\s*xHamster[^<]*| - xHamster\.com)</title>'],
283 webpage, 'title')
cb10cded 284
d852c6bc
S
285 formats = []
286 format_urls = set()
287
288 sources = self._parse_json(
289 self._search_regex(
290 r'sources\s*:\s*({.+?})\s*,?\s*\n', webpage, 'sources',
291 default='{}'),
292 video_id, fatal=False)
293 for format_id, format_url in sources.items():
3052a30d
S
294 format_url = url_or_none(format_url)
295 if not format_url:
d852c6bc
S
296 continue
297 if format_url in format_urls:
298 continue
299 format_urls.add(format_url)
300 formats.append({
301 'format_id': format_id,
302 'url': format_url,
fea92aa6 303 'height': get_height(format_id),
d852c6bc
S
304 })
305
306 video_url = self._search_regex(
307 [r'''file\s*:\s*(?P<q>["'])(?P<mp4>.+?)(?P=q)''',
308 r'''<a\s+href=(?P<q>["'])(?P<mp4>.+?)(?P=q)\s+class=["']mp4Thumb''',
309 r'''<video[^>]+file=(?P<q>["'])(?P<mp4>.+?)(?P=q)[^>]*>'''],
310 webpage, 'video url', group='mp4', default=None)
311 if video_url and video_url not in format_urls:
312 formats.append({
313 'url': video_url,
314 })
315
4353cf51 316 # Only a few videos have an description
22ff1c4a 317 mobj = re.search(r'<span>Description: </span>([^<]+)', webpage)
ccb079ee 318 description = mobj.group(1) if mobj else None
cb10cded 319
4763b624
S
320 upload_date = unified_strdate(self._search_regex(
321 r'hint=["\'](\d{4}-\d{2}-\d{2}) \d{2}:\d{2}:\d{2} [A-Z]{3,4}',
322 webpage, 'upload date', fatal=False))
cb10cded 323
3e485224 324 uploader = self._html_search_regex(
a846173d 325 r'<span[^>]+itemprop=["\']author[^>]+><a[^>]+><span[^>]+>([^<]+)',
3e485224 326 webpage, 'uploader', default='anonymous')
cb10cded 327
251a44b7 328 thumbnail = self._search_regex(
b271e335
W
329 [r'''["']thumbUrl["']\s*:\s*(?P<q>["'])(?P<thumbnail>.+?)(?P=q)''',
330 r'''<video[^>]+"poster"=(?P<q>["'])(?P<thumbnail>.+?)(?P=q)[^>]*>'''],
c73cdd80 331 webpage, 'thumbnail', fatal=False, group='thumbnail')
ccb079ee 332
51378d35 333 duration = parse_duration(self._search_regex(
d852c6bc
S
334 [r'<[^<]+\bitemprop=["\']duration["\'][^<]+\bcontent=["\'](.+?)["\']',
335 r'Runtime:\s*</span>\s*([\d:]+)'], webpage,
51378d35 336 'duration', fatal=False))
ccb079ee 337
6a16fd4a
S
338 view_count = int_or_none(self._search_regex(
339 r'content=["\']User(?:View|Play)s:(\d+)',
340 webpage, 'view count', fatal=False))
ccb079ee 341
a846173d 342 mobj = re.search(r'hint=[\'"](?P<likecount>\d+) Likes / (?P<dislikecount>\d+) Dislikes', webpage)
ccb079ee
S
343 (like_count, dislike_count) = (mobj.group('likecount'), mobj.group('dislikecount')) if mobj else (None, None)
344
345 mobj = re.search(r'</label>Comments \((?P<commentcount>\d+)\)</div>', webpage)
346 comment_count = mobj.group('commentcount') if mobj else 0
cb10cded 347
85552042
S
348 categories_html = self._search_regex(
349 r'(?s)<table.+?(<span>Categories:.+?)</table>', webpage,
350 'categories', default=None)
351 categories = [clean_html(category) for category in re.findall(
352 r'<a[^>]+>(.+?)</a>', categories_html)] if categories_html else None
353
5d0c9754 354 return {
355 'id': video_id,
d852c6bc 356 'display_id': display_id,
ccb079ee
S
357 'title': title,
358 'description': description,
359 'upload_date': upload_date,
3e485224 360 'uploader': uploader,
908b56ea 361 'uploader_id': uploader.lower() if uploader else None,
ccb079ee
S
362 'thumbnail': thumbnail,
363 'duration': duration,
364 'view_count': view_count,
365 'like_count': int_or_none(like_count),
366 'dislike_count': int_or_none(dislike_count),
367 'comment_count': int_or_none(comment_count),
9d92015d 368 'age_limit': age_limit,
85552042 369 'categories': categories,
ccb079ee 370 'formats': formats,
5d0c9754 371 }
0bbba43e
S
372
373
374class XHamsterEmbedIE(InfoExtractor):
b634ba74 375 _VALID_URL = r'https?://(?:[^/?#]+\.)?%s/xembed\.php\?video=(?P<id>\d+)' % XHamsterIE._DOMAINS
bfd973ec 376 _EMBED_REGEX = [r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?xhamster\.com/xembed\.php\?video=\d+)\1']
0bbba43e
S
377 _TEST = {
378 'url': 'http://xhamster.com/xembed.php?video=3328539',
379 'info_dict': {
380 'id': '3328539',
381 'ext': 'mp4',
382 'title': 'Pen Masturbation',
b271e335 383 'timestamp': 1406581861,
0bbba43e 384 'upload_date': '20140728',
b271e335 385 'uploader': 'ManyakisArt',
0bbba43e
S
386 'duration': 5,
387 'age_limit': 18,
388 }
389 }
390
391 def _real_extract(self, url):
392 video_id = self._match_id(url)
393
394 webpage = self._download_webpage(url, video_id)
395
396 video_url = self._search_regex(
db962528 397 r'href="(https?://xhamster\.com/(?:movies/{0}/[^"]*\.html|videos/[^/]*-{0})[^"]*)"'.format(video_id),
065c4b27
S
398 webpage, 'xhamster url', default=None)
399
400 if not video_url:
401 vars = self._parse_json(
402 self._search_regex(r'vars\s*:\s*({.+?})\s*,\s*\n', webpage, 'vars'),
403 video_id)
404 video_url = dict_get(vars, ('downloadLink', 'homepageLink', 'commentsLink', 'shareUrl'))
0bbba43e 405
25701d5a 406 return self.url_result(video_url, 'XHamster')
df228355
S
407
408
409class XHamsterUserIE(InfoExtractor):
cc8d8441 410 _VALID_URL = rf'https?://(?:[^/?#]+\.)?{XHamsterIE._DOMAINS}/(?:(?P<user>users)|creators)/(?P<id>[^/?#&]+)'
df228355
S
411 _TESTS = [{
412 # Paginated user profile
413 'url': 'https://xhamster.com/users/netvideogirls/videos',
414 'info_dict': {
415 'id': 'netvideogirls',
416 },
417 'playlist_mincount': 267,
418 }, {
419 # Non-paginated user profile
420 'url': 'https://xhamster.com/users/firatkaan/videos',
421 'info_dict': {
422 'id': 'firatkaan',
423 },
424 'playlist_mincount': 1,
cc8d8441
SS
425 }, {
426 'url': 'https://xhamster.com/creators/squirt-orgasm-69',
427 'info_dict': {
428 'id': 'squirt-orgasm-69',
429 },
430 'playlist_mincount': 150,
6d1b3489 431 }, {
432 'url': 'https://xhday.com/users/mobhunter',
433 'only_matching': True,
45b2ee6f 434 }, {
435 'url': 'https://xhvid.com/users/pelushe21',
436 'only_matching': True,
df228355
S
437 }]
438
cc8d8441
SS
439 def _entries(self, user_id, is_user):
440 prefix, suffix = ('users', 'videos') if is_user else ('creators', 'exclusive')
441 next_page_url = f'https://xhamster.com/{prefix}/{user_id}/{suffix}/1'
df228355
S
442 for pagenum in itertools.count(1):
443 page = self._download_webpage(
444 next_page_url, user_id, 'Downloading page %s' % pagenum)
445 for video_tag in re.findall(
446 r'(<a[^>]+class=["\'].*?\bvideo-thumb__image-container[^>]+>)',
447 page):
448 video = extract_attributes(video_tag)
449 video_url = url_or_none(video.get('href'))
450 if not video_url or not XHamsterIE.suitable(video_url):
451 continue
452 video_id = XHamsterIE._match_id(video_url)
453 yield self.url_result(
454 video_url, ie=XHamsterIE.ie_key(), video_id=video_id)
455 mobj = re.search(r'<a[^>]+data-page=["\']next[^>]+>', page)
456 if not mobj:
457 break
458 next_page = extract_attributes(mobj.group(0))
459 next_page_url = url_or_none(next_page.get('href'))
460 if not next_page_url:
461 break
462
463 def _real_extract(self, url):
cc8d8441
SS
464 user, user_id = self._match_valid_url(url).group('user', 'id')
465 return self.playlist_result(self._entries(user_id, bool(user)), user_id)