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