[ie/facebook] Support more groups URLs (#11576)
[yt-dlp3.git] / yt_dlp / extractor / dailymotion.py
blob423c11c5734da2a9aef1e70548102f36fffb4db1
1 import functools
2 import json
3 import re
4 import urllib.parse
6 from .common import InfoExtractor
7 from ..networking.exceptions import HTTPError
8 from ..utils import (
9 ExtractorError,
10 OnDemandPagedList,
11 age_restricted,
12 clean_html,
13 extract_attributes,
14 int_or_none,
15 traverse_obj,
16 try_get,
17 unescapeHTML,
18 unsmuggle_url,
19 update_url,
20 url_or_none,
21 urlencode_postdata,
25 class DailymotionBaseInfoExtractor(InfoExtractor):
26 _FAMILY_FILTER = None
27 _HEADERS = {
28 'Content-Type': 'application/json',
29 'Origin': 'https://www.dailymotion.com',
31 _NETRC_MACHINE = 'dailymotion'
33 def _get_dailymotion_cookies(self):
34 return self._get_cookies('https://www.dailymotion.com/')
36 @staticmethod
37 def _get_cookie_value(cookies, name):
38 cookie = cookies.get(name)
39 if cookie:
40 return cookie.value
42 def _set_dailymotion_cookie(self, name, value):
43 self._set_cookie('www.dailymotion.com', name, value)
45 def _real_initialize(self):
46 cookies = self._get_dailymotion_cookies()
47 ff = self._get_cookie_value(cookies, 'ff')
48 self._FAMILY_FILTER = ff == 'on' if ff else age_restricted(18, self.get_param('age_limit'))
49 self._set_dailymotion_cookie('ff', 'on' if self._FAMILY_FILTER else 'off')
51 def _get_token(self, xid):
52 cookies = self._get_dailymotion_cookies()
53 token = self._get_cookie_value(cookies, 'access_token') or self._get_cookie_value(cookies, 'client_token')
54 if token:
55 return token
57 data = {
58 'client_id': 'f1a362d288c1b98099c7',
59 'client_secret': 'eea605b96e01c796ff369935357eca920c5da4c5',
61 username, password = self._get_login_info()
62 if username:
63 data.update({
64 'grant_type': 'password',
65 'password': password,
66 'username': username,
68 else:
69 data['grant_type'] = 'client_credentials'
70 try:
71 token = self._download_json(
72 'https://graphql.api.dailymotion.com/oauth/token',
73 None, 'Downloading Access Token',
74 data=urlencode_postdata(data))['access_token']
75 except ExtractorError as e:
76 if isinstance(e.cause, HTTPError) and e.cause.status == 400:
77 raise ExtractorError(self._parse_json(
78 e.cause.response.read().decode(), xid)['error_description'], expected=True)
79 raise
80 self._set_dailymotion_cookie('access_token' if username else 'client_token', token)
81 return token
83 def _call_api(self, object_type, xid, object_fields, note, filter_extra=None):
84 if not self._HEADERS.get('Authorization'):
85 self._HEADERS['Authorization'] = f'Bearer {self._get_token(xid)}'
87 resp = self._download_json(
88 'https://graphql.api.dailymotion.com/', xid, note, data=json.dumps({
89 'query': '''{
90 %s(xid: "%s"%s) {
93 }''' % (object_type, xid, ', ' + filter_extra if filter_extra else '', object_fields), # noqa: UP031
94 }).encode(), headers=self._HEADERS)
95 obj = resp['data'][object_type]
96 if not obj:
97 raise ExtractorError(resp['errors'][0]['message'], expected=True)
98 return obj
101 class DailymotionIE(DailymotionBaseInfoExtractor):
102 _VALID_URL = r'''(?ix)
103 https?://
105 dai\.ly/|
107 (?:(?:www|touch|geo)\.)?dailymotion\.[a-z]{2,3}|
108 (?:www\.)?lequipe\.fr
111 swf/(?!video)|
112 (?:(?:crawler|embed|swf)/)?video/|
113 player(?:/[\da-z]+)?\.html\?(?:video|(?P<is_playlist>playlist))=
116 (?P<id>[^/?_&#]+)(?:[\w-]*\?playlist=(?P<playlist_id>x[0-9a-z]+))?
118 IE_NAME = 'dailymotion'
119 _EMBED_REGEX = [r'<(?:(?:embed|iframe)[^>]+?src=|input[^>]+id=[\'"]dmcloudUrlEmissionSelect[\'"][^>]+value=)(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/(?:embed|swf)/video/.+?)\1']
120 _TESTS = [{
121 'url': 'http://www.dailymotion.com/video/x5kesuj_office-christmas-party-review-jason-bateman-olivia-munn-t-j-miller_news',
122 'md5': '074b95bdee76b9e3654137aee9c79dfe',
123 'info_dict': {
124 'id': 'x5kesuj',
125 'ext': 'mp4',
126 'title': 'Office Christmas Party Review – Jason Bateman, Olivia Munn, T.J. Miller',
127 'description': 'Office Christmas Party Review - Jason Bateman, Olivia Munn, T.J. Miller',
128 'duration': 187,
129 'timestamp': 1493651285,
130 'upload_date': '20170501',
131 'uploader': 'Deadline',
132 'uploader_id': 'x1xm8ri',
133 'age_limit': 0,
134 'view_count': int,
135 'like_count': int,
136 'tags': ['hollywood', 'celeb', 'celebrity', 'movies', 'red carpet'],
137 'thumbnail': r're:https://(?:s[12]\.)dmcdn\.net/v/K456B1cmt4ZcZ9KiM/x1080',
139 }, {
140 'url': 'https://geo.dailymotion.com/player.html?video=x89eyek&mute=true',
141 'md5': 'e2f9717c6604773f963f069ca53a07f8',
142 'info_dict': {
143 'id': 'x89eyek',
144 'ext': 'mp4',
145 'title': "En quête d'esprit du 27/03/2022",
146 'description': 'md5:66542b9f4df2eb23f314fc097488e553',
147 'duration': 2756,
148 'timestamp': 1648383669,
149 'upload_date': '20220327',
150 'uploader': 'CNEWS',
151 'uploader_id': 'x24vth',
152 'age_limit': 0,
153 'view_count': int,
154 'like_count': int,
155 'tags': ['en_quete_d_esprit'],
156 'thumbnail': r're:https://(?:s[12]\.)dmcdn\.net/v/Tncwi1clTH6StrxMP/x1080',
158 }, {
159 'url': 'https://www.dailymotion.com/video/x2iuewm_steam-machine-models-pricing-listed-on-steam-store-ign-news_videogames',
160 'md5': '2137c41a8e78554bb09225b8eb322406',
161 'info_dict': {
162 'id': 'x2iuewm',
163 'ext': 'mp4',
164 'title': 'Steam Machine Models, Pricing Listed on Steam Store - IGN News',
165 'description': 'Several come bundled with the Steam Controller.',
166 'thumbnail': r're:^https?:.*\.(?:jpg|png)$',
167 'duration': 74,
168 'timestamp': 1425657362,
169 'upload_date': '20150306',
170 'uploader': 'IGN',
171 'uploader_id': 'xijv66',
172 'age_limit': 0,
173 'view_count': int,
175 'skip': 'video gone',
176 }, {
177 # Vevo video
178 'url': 'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi',
179 'info_dict': {
180 'title': 'Roar (Official)',
181 'id': 'USUV71301934',
182 'ext': 'mp4',
183 'uploader': 'Katy Perry',
184 'upload_date': '20130905',
186 'params': {
187 'skip_download': True,
189 'skip': 'VEVO is only available in some countries',
190 }, {
191 # age-restricted video
192 'url': 'http://www.dailymotion.com/video/xyh2zz_leanna-decker-cyber-girl-of-the-year-desires-nude-playboy-plus_redband',
193 'md5': '0d667a7b9cebecc3c89ee93099c4159d',
194 'info_dict': {
195 'id': 'xyh2zz',
196 'ext': 'mp4',
197 'title': 'Leanna Decker - Cyber Girl Of The Year Desires Nude [Playboy Plus]',
198 'uploader': 'HotWaves1012',
199 'age_limit': 18,
201 'skip': 'video gone',
202 }, {
203 # geo-restricted, player v5
204 'url': 'http://www.dailymotion.com/video/xhza0o',
205 'only_matching': True,
206 }, {
207 # with subtitles
208 'url': 'http://www.dailymotion.com/video/x20su5f_the-power-of-nightmares-1-the-rise-of-the-politics-of-fear-bbc-2004_news',
209 'only_matching': True,
210 }, {
211 'url': 'http://www.dailymotion.com/swf/video/x3n92nf',
212 'only_matching': True,
213 }, {
214 'url': 'http://www.dailymotion.com/swf/x3ss1m_funny-magic-trick-barry-and-stuart_fun',
215 'only_matching': True,
216 }, {
217 'url': 'https://www.lequipe.fr/video/x791mem',
218 'only_matching': True,
219 }, {
220 'url': 'https://www.lequipe.fr/video/k7MtHciueyTcrFtFKA2',
221 'only_matching': True,
222 }, {
223 'url': 'https://www.dailymotion.com/video/x3z49k?playlist=xv4bw',
224 'only_matching': True,
225 }, {
226 'url': 'https://geo.dailymotion.com/player/x86gw.html?video=k46oCapRs4iikoz9DWy',
227 'only_matching': True,
228 }, {
229 'url': 'https://geo.dailymotion.com/player/xakln.html?video=x8mjju4&customConfig%5BcustomParams%5D=%2Ffr-fr%2Ftennis%2Fwimbledon-mens-singles%2Farticles-video',
230 'only_matching': True,
231 }, { # playlist-only
232 'url': 'https://geo.dailymotion.com/player/xf7zn.html?playlist=x7wdsj',
233 'only_matching': True,
234 }, {
235 'url': 'https://geo.dailymotion.com/player/xmyye.html?video=x93blhi',
236 'only_matching': True,
237 }, {
238 'url': 'https://www.dailymotion.com/crawler/video/x8u4owg',
239 'only_matching': True,
240 }, {
241 'url': 'https://www.dailymotion.com/embed/video/x8u4owg',
242 'only_matching': True,
243 }, {
244 'url': 'https://dai.ly/x94cnnk',
245 'only_matching': True,
247 _WEBPAGE_TESTS = [{
248 # https://geo.dailymotion.com/player/xmyye.html?video=x93blhi
249 'url': 'https://www.financialounge.com/video/2024/08/01/borse-europee-in-rosso-dopo-la-fed-a-milano-volano-mediobanca-e-tim-edizione-del-1-agosto/',
250 'info_dict': {
251 'id': 'x93blhi',
252 'ext': 'mp4',
253 'title': 'OnAir - 01/08/24',
254 'description': '',
255 'duration': 217,
256 'timestamp': 1722505658,
257 'upload_date': '20240801',
258 'uploader': 'Financialounge',
259 'uploader_id': 'x2vtgmm',
260 'age_limit': 0,
261 'tags': [],
262 'view_count': int,
263 'like_count': int,
264 'thumbnail': r're:https://\w+.dmcdn.net/v/WnEY61cmvMxt2Fi6d/x1080',
266 }, {
267 # https://geo.dailymotion.com/player/xf7zn.html?playlist=x7wdsj
268 'url': 'https://www.cycleworld.com/blogs/ask-kevin/ducati-continues-to-evolve-with-v4/',
269 'info_dict': {
270 'id': 'x7wdsj',
272 'playlist_mincount': 50,
273 }, {
274 # https://www.dailymotion.com/crawler/video/x8u4owg
275 'url': 'https://www.leparisien.fr/environnement/video-le-veloto-la-voiture-a-pedales-qui-aimerait-se-faire-une-place-sur-les-routes-09-03-2024-KCYMCPM4WFHJXMSKBUI66UNFPU.php',
276 'info_dict': {
277 'id': 'x8u4owg',
278 'ext': 'mp4',
279 'like_count': int,
280 'uploader': 'Le Parisien',
281 'thumbnail': 'https://www.leparisien.fr/resizer/ho_GwveeYftNkLwg_cEta--5Bv4=/1200x675/cloudfront-eu-central-1.images.arcpublishing.com/leparisien/BFXJNEBN75EUNHGYJLORUC3TX4.jpg',
282 'upload_date': '20240309',
283 'view_count': int,
284 'timestamp': 1709997866,
285 'age_limit': 0,
286 'uploader_id': 'x32f7b',
287 'title': 'VIDÉO. Le «\xa0véloto\xa0», la voiture à pédales qui aimerait se faire une place sur les routes',
288 'duration': 428.0,
289 'description': 'À bord du « véloto », l’alternative à la voiture pour la campagne',
290 'tags': ['biclou', 'vélo', 'véloto', 'campagne', 'voiture', 'environnement', 'véhicules intermédiaires'],
292 }, {
293 # https://geo.dailymotion.com/player/xry80.html?video=x8vu47w
294 'url': 'https://www.metatube.com/en/videos/546765/This-frogs-decorates-Christmas-tree/',
295 'info_dict': {
296 'id': 'x8vu47w',
297 'ext': 'mp4',
298 'like_count': int,
299 'uploader': 'Metatube',
300 'thumbnail': r're:https://\w+.dmcdn.net/v/W1G_S1coGSFTfkTeR/x1080',
301 'upload_date': '20240326',
302 'view_count': int,
303 'timestamp': 1711496732,
304 'age_limit': 0,
305 'uploader_id': 'x2xpy74',
306 'title': 'Está lindas ranitas ponen su arbolito',
307 'duration': 28,
308 'description': 'Que lindura',
309 'tags': [],
312 _GEO_BYPASS = False
313 _COMMON_MEDIA_FIELDS = '''description
314 geoblockedCountries {
315 allowed
317 xid'''
319 @classmethod
320 def _extract_embed_urls(cls, url, webpage):
321 # https://developer.dailymotion.com/player#player-parameters
322 yield from super()._extract_embed_urls(url, webpage)
323 for mobj in re.finditer(
324 r'(?s)DM\.player\([^,]+,\s*{.*?video[\'"]?\s*:\s*["\']?(?P<id>[0-9a-zA-Z]+).+?}\s*\);', webpage):
325 yield 'https://www.dailymotion.com/embed/video/' + mobj.group('id')
326 for mobj in re.finditer(
327 r'(?s)<script [^>]*\bsrc=(["\'])(?:https?:)?//[\w-]+\.dailymotion\.com/player/(?:(?!\1).)+\1[^>]*>', webpage):
328 attrs = extract_attributes(mobj.group(0))
329 player_url = url_or_none(attrs.get('src'))
330 if not player_url:
331 continue
332 player_url = player_url.replace('.js', '.html')
333 if player_url.startswith('//'):
334 player_url = f'https:{player_url}'
335 if video_id := attrs.get('data-video'):
336 query_string = f'video={video_id}'
337 elif playlist_id := attrs.get('data-playlist'):
338 query_string = f'playlist={playlist_id}'
339 else:
340 continue
341 yield update_url(player_url, query=query_string)
343 def _real_extract(self, url):
344 url, smuggled_data = unsmuggle_url(url)
345 video_id, is_playlist, playlist_id = self._match_valid_url(url).group('id', 'is_playlist', 'playlist_id')
347 if is_playlist: # We matched the playlist query param as video_id
348 playlist_id = video_id
349 video_id = None
351 if self._yes_playlist(playlist_id, video_id):
352 return self.url_result(
353 f'http://www.dailymotion.com/playlist/{playlist_id}',
354 'DailymotionPlaylist', playlist_id)
356 password = self.get_param('videopassword')
357 media = self._call_api(
358 'media', video_id, '''... on Video {
360 stats {
361 likes {
362 total
364 views {
365 total
369 ... on Live {
371 audienceCount
372 isOnAir
373 }''' % (self._COMMON_MEDIA_FIELDS, self._COMMON_MEDIA_FIELDS), 'Downloading media JSON metadata', # noqa: UP031
374 'password: "{}"'.format(self.get_param('videopassword')) if password else None)
375 xid = media['xid']
377 metadata = self._download_json(
378 'https://www.dailymotion.com/player/metadata/video/' + xid,
379 xid, 'Downloading metadata JSON',
380 query=traverse_obj(smuggled_data, 'query') or {'app': 'com.dailymotion.neon'})
382 error = metadata.get('error')
383 if error:
384 title = error.get('title') or error['raw_message']
385 # See https://developer.dailymotion.com/api#access-error
386 if error.get('code') == 'DM007':
387 allowed_countries = try_get(media, lambda x: x['geoblockedCountries']['allowed'], list)
388 self.raise_geo_restricted(msg=title, countries=allowed_countries)
389 raise ExtractorError(
390 f'{self.IE_NAME} said: {title}', expected=True)
392 title = metadata['title']
393 is_live = media.get('isOnAir')
394 formats = []
395 subtitles = {}
397 for quality, media_list in metadata['qualities'].items():
398 for m in media_list:
399 media_url = m.get('url')
400 media_type = m.get('type')
401 if not media_url or media_type == 'application/vnd.lumberjack.manifest':
402 continue
403 if media_type == 'application/x-mpegURL':
404 fmt, subs = self._extract_m3u8_formats_and_subtitles(
405 media_url, video_id, 'mp4', live=is_live, m3u8_id='hls', fatal=False)
406 formats.extend(fmt)
407 self._merge_subtitles(subs, target=subtitles)
408 else:
409 f = {
410 'url': media_url,
411 'format_id': 'http-' + quality,
413 m = re.search(r'/H264-(\d+)x(\d+)(?:-(60)/)?', media_url)
414 if m:
415 width, height, fps = map(int_or_none, m.groups())
416 f.update({
417 'fps': fps,
418 'height': height,
419 'width': width,
421 formats.append(f)
422 for f in formats:
423 f['url'] = f['url'].split('#')[0]
424 if not f.get('fps') and f['format_id'].endswith('@60'):
425 f['fps'] = 60
427 subtitles_data = try_get(metadata, lambda x: x['subtitles']['data'], dict) or {}
428 for subtitle_lang, subtitle in subtitles_data.items():
429 subtitles[subtitle_lang] = [{
430 'url': subtitle_url,
431 } for subtitle_url in subtitle.get('urls', [])]
433 thumbnails = traverse_obj(metadata, (
434 ('posters', 'thumbnails'), {dict.items}, lambda _, v: url_or_none(v[1]), {
435 'height': (0, {int_or_none}),
436 'id': (0, {str}),
437 'url': 1,
440 owner = metadata.get('owner') or {}
441 stats = media.get('stats') or {}
442 get_count = lambda x: int_or_none(try_get(stats, lambda y: y[x + 's']['total']))
444 return {
445 'id': video_id,
446 'title': title,
447 'description': clean_html(media.get('description')),
448 'thumbnails': thumbnails,
449 'duration': int_or_none(metadata.get('duration')) or None,
450 'timestamp': int_or_none(metadata.get('created_time')),
451 'uploader': owner.get('screenname'),
452 'uploader_id': owner.get('id') or metadata.get('screenname'),
453 'age_limit': 18 if metadata.get('explicit') else 0,
454 'tags': metadata.get('tags'),
455 'view_count': get_count('view') or int_or_none(media.get('audienceCount')),
456 'like_count': get_count('like'),
457 'formats': formats,
458 'subtitles': subtitles,
459 'is_live': is_live,
463 class DailymotionPlaylistBaseIE(DailymotionBaseInfoExtractor):
464 _PAGE_SIZE = 100
466 def _fetch_page(self, playlist_id, page):
467 page += 1
468 videos = self._call_api(
469 self._OBJECT_TYPE, playlist_id,
470 '''videos(allowExplicit: %s, first: %d, page: %d) {
471 edges {
472 node {
477 }''' % ('false' if self._FAMILY_FILTER else 'true', self._PAGE_SIZE, page),
478 f'Downloading page {page}')['videos']
479 for edge in videos['edges']:
480 node = edge['node']
481 yield self.url_result(
482 node['url'], DailymotionIE.ie_key(), node['xid'])
484 def _real_extract(self, url):
485 playlist_id = self._match_id(url)
486 entries = OnDemandPagedList(functools.partial(
487 self._fetch_page, playlist_id), self._PAGE_SIZE)
488 return self.playlist_result(
489 entries, playlist_id)
492 class DailymotionPlaylistIE(DailymotionPlaylistBaseIE):
493 IE_NAME = 'dailymotion:playlist'
494 _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>x[0-9a-z]+)'
495 _TESTS = [{
496 'url': 'http://www.dailymotion.com/playlist/xv4bw_nqtv_sport/1#video=xl8v3q',
497 'info_dict': {
498 'id': 'xv4bw',
500 'playlist_mincount': 20,
502 _OBJECT_TYPE = 'collection'
504 @classmethod
505 def _extract_embed_urls(cls, url, webpage):
506 # Look for embedded Dailymotion playlist player (#3822)
507 for mobj in re.finditer(
508 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.[a-z]{2,3}/widget/jukebox\?.+?)\1',
509 webpage):
510 for p in re.findall(r'list\[\]=/playlist/([^/]+)/', unescapeHTML(mobj.group('url'))):
511 yield f'//dailymotion.com/playlist/{p}'
514 class DailymotionSearchIE(DailymotionPlaylistBaseIE):
515 IE_NAME = 'dailymotion:search'
516 _VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/search/(?P<id>[^/?#]+)/videos'
517 _PAGE_SIZE = 20
518 _TESTS = [{
519 'url': 'http://www.dailymotion.com/search/king of turtles/videos',
520 'info_dict': {
521 'id': 'king of turtles',
522 'title': 'king of turtles',
524 'playlist_mincount': 90,
526 _SEARCH_QUERY = 'query SEARCH_QUERY( $query: String! $page: Int $limit: Int ) { search { videos( query: $query first: $limit page: $page ) { edges { node { xid } } } } } '
528 def _call_search_api(self, term, page, note):
529 if not self._HEADERS.get('Authorization'):
530 self._HEADERS['Authorization'] = f'Bearer {self._get_token(term)}'
531 resp = self._download_json(
532 'https://graphql.api.dailymotion.com/', None, note, data=json.dumps({
533 'operationName': 'SEARCH_QUERY',
534 'query': self._SEARCH_QUERY,
535 'variables': {
536 'limit': 20,
537 'page': page,
538 'query': term,
540 }).encode(), headers=self._HEADERS)
541 obj = traverse_obj(resp, ('data', 'search', {dict}))
542 if not obj:
543 raise ExtractorError(
544 traverse_obj(resp, ('errors', 0, 'message', {str})) or 'Could not fetch search data')
546 return obj
548 def _fetch_page(self, term, page):
549 page += 1
550 response = self._call_search_api(term, page, f'Searching "{term}" page {page}')
551 for xid in traverse_obj(response, ('videos', 'edges', ..., 'node', 'xid')):
552 yield self.url_result(f'https://www.dailymotion.com/video/{xid}', DailymotionIE, xid)
554 def _real_extract(self, url):
555 term = urllib.parse.unquote_plus(self._match_id(url))
556 return self.playlist_result(
557 OnDemandPagedList(functools.partial(self._fetch_page, term), self._PAGE_SIZE), term, term)
560 class DailymotionUserIE(DailymotionPlaylistBaseIE):
561 IE_NAME = 'dailymotion:user'
562 _VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/(?!(?:embed|swf|#|video|playlist|search|crawler)/)(?:(?:old/)?user/)?(?P<id>[^/?#]+)'
563 _TESTS = [{
564 'url': 'https://www.dailymotion.com/user/nqtv',
565 'info_dict': {
566 'id': 'nqtv',
568 'playlist_mincount': 152,
569 }, {
570 'url': 'http://www.dailymotion.com/user/UnderProject',
571 'info_dict': {
572 'id': 'UnderProject',
574 'playlist_mincount': 1000,
575 'skip': 'Takes too long time',
576 }, {
577 'url': 'https://www.dailymotion.com/user/nqtv',
578 'info_dict': {
579 'id': 'nqtv',
581 'playlist_mincount': 148,
582 'params': {
583 'age_limit': 0,
586 _OBJECT_TYPE = 'channel'