2 from __future__ import unicode_literals
13 from .common import InfoExtractor
14 from ..compat import compat_struct_pack
33 class DailymotionBaseInfoExtractor(InfoExtractor):
35 def _build_request(url):
36 """Build a request with the family filter disabled"""
37 request = sanitized_Request(url)
38 request.add_header('Cookie', 'family_filter=off; ff=off')
41 def _download_webpage_handle_no_ff(self, url, *args, **kwargs):
42 request = self._build_request(url)
43 return self._download_webpage_handle(request, *args, **kwargs)
45 def _download_webpage_no_ff(self, url, *args, **kwargs):
46 request = self._build_request(url)
47 return self._download_webpage(request, *args, **kwargs)
50 class DailymotionIE(DailymotionBaseInfoExtractor):
51 _VALID_URL = r'(?i)https?://(?:(www|touch)\.)?dailymotion\.[a-z]{2,3}/(?:(?:(?:embed|swf|#)/)?video|swf)/(?P<id>[^/?_]+)'
52 IE_NAME = 'dailymotion'
55 ('stream_h264_ld_url', 'ld'),
56 ('stream_h264_url', 'standard'),
57 ('stream_h264_hq_url', 'hq'),
58 ('stream_h264_hd_url', 'hd'),
59 ('stream_h264_hd1080_url', 'hd180'),
63 'url': 'http://www.dailymotion.com/video/x5kesuj_office-christmas-party-review-jason-bateman-olivia-munn-t-j-miller_news',
64 'md5': '074b95bdee76b9e3654137aee9c79dfe',
68 'title': 'Office Christmas Party Review – Jason Bateman, Olivia Munn, T.J. Miller',
69 'description': 'Office Christmas Party Review - Jason Bateman, Olivia Munn, T.J. Miller',
70 'thumbnail': r're:^https?:.*\.(?:jpg|png)$',
72 'timestamp': 1493651285,
73 'upload_date': '20170501',
74 'uploader': 'Deadline',
75 'uploader_id': 'x1xm8ri',
79 'url': 'https://www.dailymotion.com/video/x2iuewm_steam-machine-models-pricing-listed-on-steam-store-ign-news_videogames',
80 'md5': '2137c41a8e78554bb09225b8eb322406',
84 'title': 'Steam Machine Models, Pricing Listed on Steam Store - IGN News',
85 'description': 'Several come bundled with the Steam Controller.',
86 'thumbnail': r're:^https?:.*\.(?:jpg|png)$',
88 'timestamp': 1425657362,
89 'upload_date': '20150306',
91 'uploader_id': 'xijv66',
98 'url': 'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi',
100 'title': 'Roar (Official)',
101 'id': 'USUV71301934',
103 'uploader': 'Katy Perry',
104 'upload_date': '20130905',
107 'skip_download': True,
109 'skip': 'VEVO is only available in some countries',
111 # age-restricted video
112 'url': 'http://www.dailymotion.com/video/xyh2zz_leanna-decker-cyber-girl-of-the-year-desires-nude-playboy-plus_redband',
113 'md5': '0d667a7b9cebecc3c89ee93099c4159d',
117 'title': 'Leanna Decker - Cyber Girl Of The Year Desires Nude [Playboy Plus]',
118 'uploader': 'HotWaves1012',
121 'skip': 'video gone',
123 # geo-restricted, player v5
124 'url': 'http://www.dailymotion.com/video/xhza0o',
125 'only_matching': True,
128 'url': 'http://www.dailymotion.com/video/x20su5f_the-power-of-nightmares-1-the-rise-of-the-politics-of-fear-bbc-2004_news',
129 'only_matching': True,
131 'url': 'http://www.dailymotion.com/swf/video/x3n92nf',
132 'only_matching': True,
134 'url': 'http://www.dailymotion.com/swf/x3ss1m_funny-magic-trick-barry-and-stuart_fun',
135 'only_matching': True,
139 def _extract_urls(webpage):
141 # Look for embedded Dailymotion player
142 # https://developer.dailymotion.com/player#player-parameters
143 for mobj in re.finditer(
144 r'<(?:(?:embed|iframe)[^>]+?src=|input[^>]+id=[\'"]dmcloudUrlEmissionSelect[\'"][^>]+value=)(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/(?:embed|swf)/video/.+?)\1', webpage):
145 urls.append(unescapeHTML(mobj.group('url')))
146 for mobj in re.finditer(
147 r'(?s)DM\.player\([^,]+,\s*{.*?video[\'"]?\s*:\s*["\']?(?P<id>[0-9a-zA-Z]+).+?}\s*\);', webpage):
148 urls.append('https://www.dailymotion.com/embed/video/' + mobj.group('id'))
151 def _real_extract(self, url):
152 video_id = self._match_id(url)
154 webpage = self._download_webpage_no_ff(
155 'https://www.dailymotion.com/video/%s' % video_id, video_id)
157 age_limit = self._rta_search(webpage)
159 description = self._og_search_description(
160 webpage, default=None) or self._html_search_meta(
161 'description', webpage, 'description')
163 view_count_str = self._search_regex(
164 (r'<meta[^>]+itemprop="interactionCount"[^>]+content="UserPlays:([\s\d,.]+)"',
165 r'video_views_count[^>]+>\s+([\s\d\,.]+)'),
166 webpage, 'view count', default=None)
168 view_count_str = re.sub(r'\s', '', view_count_str)
169 view_count = str_to_int(view_count_str)
170 comment_count = int_or_none(self._search_regex(
171 r'<meta[^>]+itemprop="interactionCount"[^>]+content="UserComments:(\d+)"',
172 webpage, 'comment count', default=None))
174 player_v5 = self._search_regex(
175 [r'buildPlayer\(({.+?})\);\n', # See https://github.com/ytdl-org/youtube-dl/issues/7826
176 r'playerV5\s*=\s*dmp\.create\([^,]+?,\s*({.+?})\);',
177 r'buildPlayer\(({.+?})\);',
178 r'var\s+config\s*=\s*({.+?});',
179 # New layout regex (see https://github.com/ytdl-org/youtube-dl/issues/13580)
180 r'__PLAYER_CONFIG__\s*=\s*({.+?});'],
181 webpage, 'player v5', default=None)
183 player = self._parse_json(player_v5, video_id, fatal=False) or {}
184 metadata = try_get(player, lambda x: x['metadata'], dict)
186 metadata_url = url_or_none(try_get(
187 player, lambda x: x['context']['metadata_template_url1']))
189 metadata_url = metadata_url.replace(':videoId', video_id)
191 metadata_url = update_url_query(
192 'https://www.dailymotion.com/player/metadata/video/%s'
195 'integration': 'inline',
198 metadata = self._download_json(
199 metadata_url, video_id, 'Downloading metadata JSON')
201 if try_get(metadata, lambda x: x['error']['type']) == 'password_protected':
202 password = self._downloader.params.get('videopassword')
204 r = int(metadata['id'][1:], 36)
205 us64e = lambda x: base64.urlsafe_b64encode(x).decode().strip('=')
206 t = ''.join(random.choice(string.ascii_letters) for i in range(10))
207 n = us64e(compat_struct_pack('I', r))
208 i = us64e(hashlib.md5(('%s%d%s' % (password, r, t)).encode()).digest())
209 metadata = self._download_json(
210 'http://www.dailymotion.com/player/metadata/video/p' + i + t + n, video_id)
212 self._check_error(metadata)
215 for quality, media_list in metadata['qualities'].items():
216 for media in media_list:
217 media_url = media.get('url')
220 type_ = media.get('type')
221 if type_ == 'application/vnd.lumberjack.manifest':
223 ext = mimetype2ext(type_) or determine_ext(media_url)
225 m3u8_formats = self._extract_m3u8_formats(
226 media_url, video_id, 'mp4', preference=-1,
227 m3u8_id='hls', fatal=False)
228 for f in m3u8_formats:
229 f['url'] = f['url'].split('#')[0]
232 formats.extend(self._extract_f4m_formats(
233 media_url, video_id, preference=-1, f4m_id='hds', fatal=False))
237 'format_id': 'http-%s' % quality,
240 m = re.search(r'H264-(?P<width>\d+)x(?P<height>\d+)', media_url)
243 'width': int(m.group('width')),
244 'height': int(m.group('height')),
247 self._sort_formats(formats)
249 title = metadata['title']
250 duration = int_or_none(metadata.get('duration'))
251 timestamp = int_or_none(metadata.get('created_time'))
252 thumbnail = metadata.get('poster_url')
253 uploader = metadata.get('owner', {}).get('screenname')
254 uploader_id = metadata.get('owner', {}).get('id')
257 subtitles_data = metadata.get('subtitles', {}).get('data', {})
258 if subtitles_data and isinstance(subtitles_data, dict):
259 for subtitle_lang, subtitle in subtitles_data.items():
260 subtitles[subtitle_lang] = [{
261 'ext': determine_ext(subtitle_url),
263 } for subtitle_url in subtitle.get('urls', [])]
268 'description': description,
269 'thumbnail': thumbnail,
270 'duration': duration,
271 'timestamp': timestamp,
272 'uploader': uploader,
273 'uploader_id': uploader_id,
274 'age_limit': age_limit,
275 'view_count': view_count,
276 'comment_count': comment_count,
278 'subtitles': subtitles,
282 vevo_id = self._search_regex(
283 r'<link rel="video_src" href="[^"]*?vevo\.com[^"]*?video=(?P<id>[\w]*)',
284 webpage, 'vevo embed', default=None)
286 return self.url_result('vevo:%s' % vevo_id, 'Vevo')
288 # fallback old player
289 embed_page = self._download_webpage_no_ff(
290 'https://www.dailymotion.com/embed/video/%s' % video_id,
291 video_id, 'Downloading embed page')
293 timestamp = parse_iso8601(self._html_search_meta(
294 'video:release_date', webpage, 'upload date'))
296 info = self._parse_json(
298 r'var info = ({.*?}),$', embed_page,
299 'video info', flags=re.MULTILINE),
302 self._check_error(info)
305 for (key, format_id) in self._FORMATS:
306 video_url = info.get(key)
307 if video_url is not None:
308 m_size = re.search(r'H264-(\d+)x(\d+)', video_url)
309 if m_size is not None:
310 width, height = map(int_or_none, (m_size.group(1), m_size.group(2)))
312 width, height = None, None
316 'format_id': format_id,
320 self._sort_formats(formats)
323 video_subtitles = self.extract_subtitles(video_id, webpage)
325 title = self._og_search_title(webpage, default=None)
327 title = self._html_search_regex(
328 r'(?s)<span\s+id="video_title"[^>]*>(.*?)</span>', webpage,
334 'uploader': info['owner.screenname'],
335 'timestamp': timestamp,
337 'description': description,
338 'subtitles': video_subtitles,
339 'thumbnail': info['thumbnail_url'],
340 'age_limit': age_limit,
341 'view_count': view_count,
342 'duration': info['duration']
345 def _check_error(self, info):
346 error = info.get('error')
348 title = error.get('title') or error['message']
349 # See https://developer.dailymotion.com/api#access-error
350 if error.get('code') == 'DM007':
351 self.raise_geo_restricted(msg=title)
352 raise ExtractorError(
353 '%s said: %s' % (self.IE_NAME, title), expected=True)
355 def _get_subtitles(self, video_id, webpage):
357 sub_list = self._download_webpage(
358 'https://api.dailymotion.com/video/%s/subtitles?fields=id,language,url' % video_id,
359 video_id, note=False)
360 except ExtractorError as err:
361 self._downloader.report_warning('unable to download video subtitles: %s' % error_to_compat_str(err))
363 info = json.loads(sub_list)
364 if (info['total'] > 0):
365 sub_lang_list = dict((l['language'], [{'url': l['url'], 'ext': 'srt'}]) for l in info['list'])
367 self._downloader.report_warning('video doesn\'t have subtitles')
371 class DailymotionPlaylistIE(DailymotionBaseInfoExtractor):
372 IE_NAME = 'dailymotion:playlist'
373 _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>x[0-9a-z]+)'
375 'url': 'http://www.dailymotion.com/playlist/xv4bw_nqtv_sport/1#video=xl8v3q',
380 'playlist_mincount': 20,
384 def _fetch_page(self, playlist_id, authorizaion, page):
386 videos = self._download_json(
387 'https://graphql.api.dailymotion.com',
388 playlist_id, 'Downloading page %d' % page,
391 collection(xid: "%s") {
392 videos(first: %d, page: %d) {
405 }''' % (playlist_id, self._PAGE_SIZE, page)
406 }).encode(), headers={
407 'Authorization': authorizaion,
408 'Origin': 'https://www.dailymotion.com',
409 })['data']['collection']['videos']
410 for edge in videos['edges']:
412 yield self.url_result(
413 node['url'], DailymotionIE.ie_key(), node['xid'])
415 def _real_extract(self, url):
416 playlist_id = self._match_id(url)
417 webpage = self._download_webpage(url, playlist_id)
418 api = self._parse_json(self._search_regex(
419 r'__PLAYER_CONFIG__\s*=\s*({.+?});',
420 webpage, 'player config'), playlist_id)['context']['api']
421 auth = self._download_json(
422 api.get('auth_url', 'https://graphql.api.dailymotion.com/oauth/token'),
423 playlist_id, data=urlencode_postdata({
424 'client_id': api.get('client_id', 'f1a362d288c1b98099c7'),
425 'client_secret': api.get('client_secret', 'eea605b96e01c796ff369935357eca920c5da4c5'),
426 'grant_type': 'client_credentials',
428 authorizaion = '%s %s' % (auth.get('token_type', 'Bearer'), auth['access_token'])
429 entries = OnDemandPagedList(functools.partial(
430 self._fetch_page, playlist_id, authorizaion), self._PAGE_SIZE)
431 return self.playlist_result(
432 entries, playlist_id,
433 self._og_search_title(webpage))
436 class DailymotionUserIE(DailymotionBaseInfoExtractor):
437 IE_NAME = 'dailymotion:user'
438 _VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/(?!(?:embed|swf|#|video|playlist)/)(?:(?:old/)?user/)?(?P<user>[^/]+)'
439 _MORE_PAGES_INDICATOR = r'(?s)<div class="pages[^"]*">.*?<a\s+class="[^"]*?icon-arrow_right[^"]*?"'
440 _PAGE_TEMPLATE = 'http://www.dailymotion.com/user/%s/%s'
442 'url': 'https://www.dailymotion.com/user/nqtv',
445 'title': 'Rémi Gaillard',
447 'playlist_mincount': 100,
449 'url': 'http://www.dailymotion.com/user/UnderProject',
451 'id': 'UnderProject',
452 'title': 'UnderProject',
454 'playlist_mincount': 1800,
455 'expected_warnings': [
456 'Stopped at duplicated page',
458 'skip': 'Takes too long time',
461 def _extract_entries(self, id):
463 processed_urls = set()
464 for pagenum in itertools.count(1):
465 page_url = self._PAGE_TEMPLATE % (id, pagenum)
466 webpage, urlh = self._download_webpage_handle_no_ff(
467 page_url, id, 'Downloading page %s' % pagenum)
468 if urlh.geturl() in processed_urls:
469 self.report_warning('Stopped at duplicated page %s, which is the same as %s' % (
470 page_url, urlh.geturl()), id)
473 processed_urls.add(urlh.geturl())
475 for video_id in re.findall(r'data-xid="(.+?)"', webpage):
476 if video_id not in video_ids:
477 yield self.url_result(
478 'http://www.dailymotion.com/video/%s' % video_id,
479 DailymotionIE.ie_key(), video_id)
480 video_ids.add(video_id)
482 if re.search(self._MORE_PAGES_INDICATOR, webpage) is None:
485 def _real_extract(self, url):
486 mobj = re.match(self._VALID_URL, url)
487 user = mobj.group('user')
488 webpage = self._download_webpage(
489 'https://www.dailymotion.com/user/%s' % user, user)
490 full_user = unescapeHTML(self._html_search_regex(
491 r'<a class="nav-image" title="([^"]+)" href="/%s">' % re.escape(user),
498 'entries': self._extract_entries(user),