]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/xhamster.py
[extractor] Deprecate `_sort_formats`
[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 (
85552042 7 clean_html,
fea92aa6 8 determine_ext,
065c4b27 9 dict_get,
df228355 10 extract_attributes,
103f8c8d 11 ExtractorError,
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):
6d1b3489 24 _DOMAINS = r'(?:xhamster\.(?:com|one|desi)|xhms\.pro|xhamster\d+\.com|xhday\.com)'
00e5c363
S
25 _VALID_URL = r'''(?x)
26 https?://
8945b10f 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,
6b43132c 123 }]
cb10cded 124
5f6a1245 125 def _real_extract(self, url):
5ad28e7f 126 mobj = self._match_valid_url(url)
00e5c363
S
127 video_id = mobj.group('id') or mobj.group('id_2')
128 display_id = mobj.group('display_id') or mobj.group('display_id_2')
129
b271e335 130 desktop_url = re.sub(r'^(https?://(?:.+?\.)?)m\.', r'\1', url)
b274e48d 131 webpage, urlh = self._download_webpage_handle(desktop_url, video_id)
cb10cded 132
103f8c8d
S
133 error = self._html_search_regex(
134 r'<div[^>]+id=["\']videoClosed["\'][^>]*>(.+?)</div>',
135 webpage, 'error', default=None)
136 if error:
137 raise ExtractorError(error, expected=True)
138
fea92aa6
S
139 age_limit = self._rta_search(webpage)
140
141 def get_height(s):
142 return int_or_none(self._search_regex(
143 r'^(\d+)[pP]', s, 'height', default=None))
144
145 initials = self._parse_json(
146 self._search_regex(
39e7107d
U
147 (r'window\.initials\s*=\s*({.+?})\s*;\s*</script>',
148 r'window\.initials\s*=\s*({.+?})\s*;'), webpage, 'initials',
fea92aa6
S
149 default='{}'),
150 video_id, fatal=False)
151 if initials:
152 video = initials['videoModel']
153 title = video['title']
154 formats = []
cc2db878 155 format_urls = set()
156 format_sizes = {}
157 sources = try_get(video, lambda x: x['sources'], dict) or {}
158 for format_id, formats_dict in sources.items():
fea92aa6
S
159 if not isinstance(formats_dict, dict):
160 continue
cc2db878 161 download_sources = try_get(sources, lambda x: x['download'], dict) or {}
162 for quality, format_dict in download_sources.items():
163 if not isinstance(format_dict, dict):
164 continue
165 format_sizes[quality] = float_or_none(format_dict.get('size'))
fea92aa6
S
166 for quality, format_item in formats_dict.items():
167 if format_id == 'download':
168 # Download link takes some time to be generated,
169 # skipping for now
170 continue
cc2db878 171 format_url = format_item
3052a30d 172 format_url = url_or_none(format_url)
cc2db878 173 if not format_url or format_url in format_urls:
fea92aa6 174 continue
cc2db878 175 format_urls.add(format_url)
fea92aa6
S
176 formats.append({
177 'format_id': '%s-%s' % (format_id, quality),
178 'url': format_url,
179 'ext': determine_ext(format_url, 'mp4'),
180 'height': get_height(quality),
cc2db878 181 'filesize': format_sizes.get(quality),
b274e48d
S
182 'http_headers': {
183 'Referer': urlh.geturl(),
184 },
fea92aa6 185 })
cc2db878 186 xplayer_sources = try_get(
187 initials, lambda x: x['xplayerSettings']['sources'], dict)
188 if xplayer_sources:
189 hls_sources = xplayer_sources.get('hls')
190 if isinstance(hls_sources, dict):
191 for hls_format_key in ('url', 'fallback'):
192 hls_url = hls_sources.get(hls_format_key)
193 if not hls_url:
194 continue
195 hls_url = urljoin(url, hls_url)
196 if not hls_url or hls_url in format_urls:
197 continue
198 format_urls.add(hls_url)
199 formats.extend(self._extract_m3u8_formats(
200 hls_url, video_id, 'mp4', entry_protocol='m3u8_native',
201 m3u8_id='hls', fatal=False))
202 standard_sources = xplayer_sources.get('standard')
203 if isinstance(standard_sources, dict):
204 for format_id, formats_list in standard_sources.items():
205 if not isinstance(formats_list, list):
206 continue
207 for standard_format in formats_list:
208 if not isinstance(standard_format, dict):
209 continue
210 for standard_format_key in ('url', 'fallback'):
211 standard_url = standard_format.get(standard_format_key)
212 if not standard_url:
213 continue
214 standard_url = urljoin(url, standard_url)
215 if not standard_url or standard_url in format_urls:
216 continue
217 format_urls.add(standard_url)
218 ext = determine_ext(standard_url, 'mp4')
219 if ext == 'm3u8':
220 formats.extend(self._extract_m3u8_formats(
221 standard_url, video_id, 'mp4', entry_protocol='m3u8_native',
222 m3u8_id='hls', fatal=False))
223 continue
224 quality = (str_or_none(standard_format.get('quality'))
225 or str_or_none(standard_format.get('label'))
226 or '')
227 formats.append({
228 'format_id': '%s-%s' % (format_id, quality),
229 'url': standard_url,
230 'ext': ext,
231 'height': get_height(quality),
232 'filesize': format_sizes.get(quality),
233 'http_headers': {
234 'Referer': standard_url,
235 },
236 })
fea92aa6
S
237
238 categories_list = video.get('categories')
239 if isinstance(categories_list, list):
240 categories = []
241 for c in categories_list:
242 if not isinstance(c, dict):
243 continue
244 c_name = c.get('name')
245 if isinstance(c_name, compat_str):
246 categories.append(c_name)
247 else:
248 categories = None
249
908b56ea 250 uploader_url = url_or_none(try_get(video, lambda x: x['author']['pageURL']))
fea92aa6
S
251 return {
252 'id': video_id,
253 'display_id': display_id,
254 'title': title,
255 'description': video.get('description'),
256 'timestamp': int_or_none(video.get('created')),
257 'uploader': try_get(
258 video, lambda x: x['author']['name'], compat_str),
908b56ea 259 'uploader_url': uploader_url,
260 'uploader_id': uploader_url.split('/')[-1] if uploader_url else None,
fea92aa6
S
261 'thumbnail': video.get('thumbURL'),
262 'duration': int_or_none(video.get('duration')),
263 'view_count': int_or_none(video.get('views')),
264 'like_count': int_or_none(try_get(
265 video, lambda x: x['rating']['likes'], int)),
266 'dislike_count': int_or_none(try_get(
267 video, lambda x: x['rating']['dislikes'], int)),
268 'comment_count': int_or_none(video.get('views')),
6d1b3489 269 'age_limit': age_limit if age_limit is not None else 18,
fea92aa6
S
270 'categories': categories,
271 'formats': formats,
272 }
273
274 # Old layout fallback
275
4395ca2e 276 title = self._html_search_regex(
1a6d9284
S
277 [r'<h1[^>]*>([^<]+)</h1>',
278 r'<meta[^>]+itemprop=".*?caption.*?"[^>]+content="(.+?)"',
279 r'<title[^>]*>(.+?)(?:,\s*[^,]*?\s*Porn\s*[^,]*?:\s*xHamster[^<]*| - xHamster\.com)</title>'],
280 webpage, 'title')
cb10cded 281
d852c6bc
S
282 formats = []
283 format_urls = set()
284
285 sources = self._parse_json(
286 self._search_regex(
287 r'sources\s*:\s*({.+?})\s*,?\s*\n', webpage, 'sources',
288 default='{}'),
289 video_id, fatal=False)
290 for format_id, format_url in sources.items():
3052a30d
S
291 format_url = url_or_none(format_url)
292 if not format_url:
d852c6bc
S
293 continue
294 if format_url in format_urls:
295 continue
296 format_urls.add(format_url)
297 formats.append({
298 'format_id': format_id,
299 'url': format_url,
fea92aa6 300 'height': get_height(format_id),
d852c6bc
S
301 })
302
303 video_url = self._search_regex(
304 [r'''file\s*:\s*(?P<q>["'])(?P<mp4>.+?)(?P=q)''',
305 r'''<a\s+href=(?P<q>["'])(?P<mp4>.+?)(?P=q)\s+class=["']mp4Thumb''',
306 r'''<video[^>]+file=(?P<q>["'])(?P<mp4>.+?)(?P=q)[^>]*>'''],
307 webpage, 'video url', group='mp4', default=None)
308 if video_url and video_url not in format_urls:
309 formats.append({
310 'url': video_url,
311 })
312
4353cf51 313 # Only a few videos have an description
22ff1c4a 314 mobj = re.search(r'<span>Description: </span>([^<]+)', webpage)
ccb079ee 315 description = mobj.group(1) if mobj else None
cb10cded 316
4763b624
S
317 upload_date = unified_strdate(self._search_regex(
318 r'hint=["\'](\d{4}-\d{2}-\d{2}) \d{2}:\d{2}:\d{2} [A-Z]{3,4}',
319 webpage, 'upload date', fatal=False))
cb10cded 320
3e485224 321 uploader = self._html_search_regex(
a846173d 322 r'<span[^>]+itemprop=["\']author[^>]+><a[^>]+><span[^>]+>([^<]+)',
3e485224 323 webpage, 'uploader', default='anonymous')
cb10cded 324
251a44b7 325 thumbnail = self._search_regex(
b271e335
W
326 [r'''["']thumbUrl["']\s*:\s*(?P<q>["'])(?P<thumbnail>.+?)(?P=q)''',
327 r'''<video[^>]+"poster"=(?P<q>["'])(?P<thumbnail>.+?)(?P=q)[^>]*>'''],
c73cdd80 328 webpage, 'thumbnail', fatal=False, group='thumbnail')
ccb079ee 329
51378d35 330 duration = parse_duration(self._search_regex(
d852c6bc
S
331 [r'<[^<]+\bitemprop=["\']duration["\'][^<]+\bcontent=["\'](.+?)["\']',
332 r'Runtime:\s*</span>\s*([\d:]+)'], webpage,
51378d35 333 'duration', fatal=False))
ccb079ee 334
6a16fd4a
S
335 view_count = int_or_none(self._search_regex(
336 r'content=["\']User(?:View|Play)s:(\d+)',
337 webpage, 'view count', fatal=False))
ccb079ee 338
a846173d 339 mobj = re.search(r'hint=[\'"](?P<likecount>\d+) Likes / (?P<dislikecount>\d+) Dislikes', webpage)
ccb079ee
S
340 (like_count, dislike_count) = (mobj.group('likecount'), mobj.group('dislikecount')) if mobj else (None, None)
341
342 mobj = re.search(r'</label>Comments \((?P<commentcount>\d+)\)</div>', webpage)
343 comment_count = mobj.group('commentcount') if mobj else 0
cb10cded 344
85552042
S
345 categories_html = self._search_regex(
346 r'(?s)<table.+?(<span>Categories:.+?)</table>', webpage,
347 'categories', default=None)
348 categories = [clean_html(category) for category in re.findall(
349 r'<a[^>]+>(.+?)</a>', categories_html)] if categories_html else None
350
5d0c9754 351 return {
352 'id': video_id,
d852c6bc 353 'display_id': display_id,
ccb079ee
S
354 'title': title,
355 'description': description,
356 'upload_date': upload_date,
3e485224 357 'uploader': uploader,
908b56ea 358 'uploader_id': uploader.lower() if uploader else None,
ccb079ee
S
359 'thumbnail': thumbnail,
360 'duration': duration,
361 'view_count': view_count,
362 'like_count': int_or_none(like_count),
363 'dislike_count': int_or_none(dislike_count),
364 'comment_count': int_or_none(comment_count),
9d92015d 365 'age_limit': age_limit,
85552042 366 'categories': categories,
ccb079ee 367 'formats': formats,
5d0c9754 368 }
0bbba43e
S
369
370
371class XHamsterEmbedIE(InfoExtractor):
8945b10f 372 _VALID_URL = r'https?://(?:.+?\.)?%s/xembed\.php\?video=(?P<id>\d+)' % XHamsterIE._DOMAINS
bfd973ec 373 _EMBED_REGEX = [r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?xhamster\.com/xembed\.php\?video=\d+)\1']
0bbba43e
S
374 _TEST = {
375 'url': 'http://xhamster.com/xembed.php?video=3328539',
376 'info_dict': {
377 'id': '3328539',
378 'ext': 'mp4',
379 'title': 'Pen Masturbation',
b271e335 380 'timestamp': 1406581861,
0bbba43e 381 'upload_date': '20140728',
b271e335 382 'uploader': 'ManyakisArt',
0bbba43e
S
383 'duration': 5,
384 'age_limit': 18,
385 }
386 }
387
388 def _real_extract(self, url):
389 video_id = self._match_id(url)
390
391 webpage = self._download_webpage(url, video_id)
392
393 video_url = self._search_regex(
db962528 394 r'href="(https?://xhamster\.com/(?:movies/{0}/[^"]*\.html|videos/[^/]*-{0})[^"]*)"'.format(video_id),
065c4b27
S
395 webpage, 'xhamster url', default=None)
396
397 if not video_url:
398 vars = self._parse_json(
399 self._search_regex(r'vars\s*:\s*({.+?})\s*,\s*\n', webpage, 'vars'),
400 video_id)
401 video_url = dict_get(vars, ('downloadLink', 'homepageLink', 'commentsLink', 'shareUrl'))
0bbba43e 402
25701d5a 403 return self.url_result(video_url, 'XHamster')
df228355
S
404
405
406class XHamsterUserIE(InfoExtractor):
407 _VALID_URL = r'https?://(?:.+?\.)?%s/users/(?P<id>[^/?#&]+)' % XHamsterIE._DOMAINS
408 _TESTS = [{
409 # Paginated user profile
410 'url': 'https://xhamster.com/users/netvideogirls/videos',
411 'info_dict': {
412 'id': 'netvideogirls',
413 },
414 'playlist_mincount': 267,
415 }, {
416 # Non-paginated user profile
417 'url': 'https://xhamster.com/users/firatkaan/videos',
418 'info_dict': {
419 'id': 'firatkaan',
420 },
421 'playlist_mincount': 1,
6d1b3489 422 }, {
423 'url': 'https://xhday.com/users/mobhunter',
424 'only_matching': True,
df228355
S
425 }]
426
427 def _entries(self, user_id):
428 next_page_url = 'https://xhamster.com/users/%s/videos/1' % user_id
429 for pagenum in itertools.count(1):
430 page = self._download_webpage(
431 next_page_url, user_id, 'Downloading page %s' % pagenum)
432 for video_tag in re.findall(
433 r'(<a[^>]+class=["\'].*?\bvideo-thumb__image-container[^>]+>)',
434 page):
435 video = extract_attributes(video_tag)
436 video_url = url_or_none(video.get('href'))
437 if not video_url or not XHamsterIE.suitable(video_url):
438 continue
439 video_id = XHamsterIE._match_id(video_url)
440 yield self.url_result(
441 video_url, ie=XHamsterIE.ie_key(), video_id=video_id)
442 mobj = re.search(r'<a[^>]+data-page=["\']next[^>]+>', page)
443 if not mobj:
444 break
445 next_page = extract_attributes(mobj.group(0))
446 next_page_url = url_or_none(next_page.get('href'))
447 if not next_page_url:
448 break
449
450 def _real_extract(self, url):
451 user_id = self._match_id(url)
452 return self.playlist_result(self._entries(user_id), user_id)