2 from __future__ import unicode_literals
13 from .common import InfoExtractor
14 from ..compat import compat_struct_pack
31 class DailymotionBaseInfoExtractor(InfoExtractor):
33 def _build_request(url):
34 """Build a request with the family filter disabled"""
35 request = sanitized_Request(url)
36 request.add_header('Cookie', 'family_filter=off; ff=off')
39 def _download_webpage_handle_no_ff(self, url, *args, **kwargs):
40 request = self._build_request(url)
41 return self._download_webpage_handle(request, *args, **kwargs)
43 def _download_webpage_no_ff(self, url, *args, **kwargs):
44 request = self._build_request(url)
45 return self._download_webpage(request, *args, **kwargs)
48 class DailymotionIE(DailymotionBaseInfoExtractor):
49 _VALID_URL = r'(?i)https?://(?:(www|touch)\.)?dailymotion\.[a-z]{2,3}/(?:(?:(?:embed|swf|#)/)?video|swf)/(?P<id>[^/?_]+)'
50 IE_NAME = 'dailymotion'
53 ('stream_h264_ld_url', 'ld'),
54 ('stream_h264_url', 'standard'),
55 ('stream_h264_hq_url', 'hq'),
56 ('stream_h264_hd_url', 'hd'),
57 ('stream_h264_hd1080_url', 'hd180'),
61 'url': 'http://www.dailymotion.com/video/x5kesuj_office-christmas-party-review-jason-bateman-olivia-munn-t-j-miller_news',
62 'md5': '074b95bdee76b9e3654137aee9c79dfe',
66 'title': 'Office Christmas Party Review – Jason Bateman, Olivia Munn, T.J. Miller',
67 'description': 'Office Christmas Party Review - Jason Bateman, Olivia Munn, T.J. Miller',
68 'thumbnail': r're:^https?:.*\.(?:jpg|png)$',
70 'timestamp': 1493651285,
71 'upload_date': '20170501',
72 'uploader': 'Deadline',
73 'uploader_id': 'x1xm8ri',
77 'url': 'https://www.dailymotion.com/video/x2iuewm_steam-machine-models-pricing-listed-on-steam-store-ign-news_videogames',
78 'md5': '2137c41a8e78554bb09225b8eb322406',
82 'title': 'Steam Machine Models, Pricing Listed on Steam Store - IGN News',
83 'description': 'Several come bundled with the Steam Controller.',
84 'thumbnail': r're:^https?:.*\.(?:jpg|png)$',
86 'timestamp': 1425657362,
87 'upload_date': '20150306',
89 'uploader_id': 'xijv66',
96 'url': 'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi',
98 'title': 'Roar (Official)',
101 'uploader': 'Katy Perry',
102 'upload_date': '20130905',
105 'skip_download': True,
107 'skip': 'VEVO is only available in some countries',
109 # age-restricted video
110 'url': 'http://www.dailymotion.com/video/xyh2zz_leanna-decker-cyber-girl-of-the-year-desires-nude-playboy-plus_redband',
111 'md5': '0d667a7b9cebecc3c89ee93099c4159d',
115 'title': 'Leanna Decker - Cyber Girl Of The Year Desires Nude [Playboy Plus]',
116 'uploader': 'HotWaves1012',
119 'skip': 'video gone',
121 # geo-restricted, player v5
122 'url': 'http://www.dailymotion.com/video/xhza0o',
123 'only_matching': True,
126 'url': 'http://www.dailymotion.com/video/x20su5f_the-power-of-nightmares-1-the-rise-of-the-politics-of-fear-bbc-2004_news',
127 'only_matching': True,
129 'url': 'http://www.dailymotion.com/swf/video/x3n92nf',
130 'only_matching': True,
132 'url': 'http://www.dailymotion.com/swf/x3ss1m_funny-magic-trick-barry-and-stuart_fun',
133 'only_matching': True,
137 def _extract_urls(webpage):
138 # Look for embedded Dailymotion player
139 matches = re.findall(
140 r'<(?:(?:embed|iframe)[^>]+?src=|input[^>]+id=[\'"]dmcloudUrlEmissionSelect[\'"][^>]+value=)(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/(?:embed|swf)/video/.+?)\1', webpage)
141 return list(map(lambda m: unescapeHTML(m[1]), matches))
143 def _real_extract(self, url):
144 video_id = self._match_id(url)
146 webpage = self._download_webpage_no_ff(
147 'https://www.dailymotion.com/video/%s' % video_id, video_id)
149 age_limit = self._rta_search(webpage)
151 description = self._og_search_description(
152 webpage, default=None) or self._html_search_meta(
153 'description', webpage, 'description')
155 view_count_str = self._search_regex(
156 (r'<meta[^>]+itemprop="interactionCount"[^>]+content="UserPlays:([\s\d,.]+)"',
157 r'video_views_count[^>]+>\s+([\s\d\,.]+)'),
158 webpage, 'view count', default=None)
160 view_count_str = re.sub(r'\s', '', view_count_str)
161 view_count = str_to_int(view_count_str)
162 comment_count = int_or_none(self._search_regex(
163 r'<meta[^>]+itemprop="interactionCount"[^>]+content="UserComments:(\d+)"',
164 webpage, 'comment count', default=None))
166 player_v5 = self._search_regex(
167 [r'buildPlayer\(({.+?})\);\n', # See https://github.com/rg3/youtube-dl/issues/7826
168 r'playerV5\s*=\s*dmp\.create\([^,]+?,\s*({.+?})\);',
169 r'buildPlayer\(({.+?})\);',
170 r'var\s+config\s*=\s*({.+?});',
171 # New layout regex (see https://github.com/rg3/youtube-dl/issues/13580)
172 r'__PLAYER_CONFIG__\s*=\s*({.+?});'],
173 webpage, 'player v5', default=None)
175 player = self._parse_json(player_v5, video_id)
177 player, lambda x: x['metadata'], dict) or self._download_json(
178 'http://www.dailymotion.com/player/metadata/video/%s' % video_id, video_id, query={
179 'integration': 'inline',
183 if metadata.get('error', {}).get('type') == 'password_protected':
184 password = self._downloader.params.get('videopassword')
186 r = int(metadata['id'][1:], 36)
187 us64e = lambda x: base64.urlsafe_b64encode(x).decode().strip('=')
188 t = ''.join(random.choice(string.ascii_letters) for i in range(10))
189 n = us64e(compat_struct_pack('I', r))
190 i = us64e(hashlib.md5(('%s%d%s' % (password, r, t)).encode()).digest())
191 metadata = self._download_json(
192 'http://www.dailymotion.com/player/metadata/video/p' + i + t + n, video_id)
194 self._check_error(metadata)
197 for quality, media_list in metadata['qualities'].items():
198 for media in media_list:
199 media_url = media.get('url')
202 type_ = media.get('type')
203 if type_ == 'application/vnd.lumberjack.manifest':
205 ext = mimetype2ext(type_) or determine_ext(media_url)
207 m3u8_formats = self._extract_m3u8_formats(
208 media_url, video_id, 'mp4', preference=-1,
209 m3u8_id='hls', fatal=False)
210 for f in m3u8_formats:
211 f['url'] = f['url'].split('#')[0]
214 formats.extend(self._extract_f4m_formats(
215 media_url, video_id, preference=-1, f4m_id='hds', fatal=False))
219 'format_id': 'http-%s' % quality,
222 m = re.search(r'H264-(?P<width>\d+)x(?P<height>\d+)', media_url)
225 'width': int(m.group('width')),
226 'height': int(m.group('height')),
229 self._sort_formats(formats)
231 title = metadata['title']
232 duration = int_or_none(metadata.get('duration'))
233 timestamp = int_or_none(metadata.get('created_time'))
234 thumbnail = metadata.get('poster_url')
235 uploader = metadata.get('owner', {}).get('screenname')
236 uploader_id = metadata.get('owner', {}).get('id')
239 subtitles_data = metadata.get('subtitles', {}).get('data', {})
240 if subtitles_data and isinstance(subtitles_data, dict):
241 for subtitle_lang, subtitle in subtitles_data.items():
242 subtitles[subtitle_lang] = [{
243 'ext': determine_ext(subtitle_url),
245 } for subtitle_url in subtitle.get('urls', [])]
250 'description': description,
251 'thumbnail': thumbnail,
252 'duration': duration,
253 'timestamp': timestamp,
254 'uploader': uploader,
255 'uploader_id': uploader_id,
256 'age_limit': age_limit,
257 'view_count': view_count,
258 'comment_count': comment_count,
260 'subtitles': subtitles,
264 vevo_id = self._search_regex(
265 r'<link rel="video_src" href="[^"]*?vevo\.com[^"]*?video=(?P<id>[\w]*)',
266 webpage, 'vevo embed', default=None)
268 return self.url_result('vevo:%s' % vevo_id, 'Vevo')
270 # fallback old player
271 embed_page = self._download_webpage_no_ff(
272 'https://www.dailymotion.com/embed/video/%s' % video_id,
273 video_id, 'Downloading embed page')
275 timestamp = parse_iso8601(self._html_search_meta(
276 'video:release_date', webpage, 'upload date'))
278 info = self._parse_json(
280 r'var info = ({.*?}),$', embed_page,
281 'video info', flags=re.MULTILINE),
284 self._check_error(info)
287 for (key, format_id) in self._FORMATS:
288 video_url = info.get(key)
289 if video_url is not None:
290 m_size = re.search(r'H264-(\d+)x(\d+)', video_url)
291 if m_size is not None:
292 width, height = map(int_or_none, (m_size.group(1), m_size.group(2)))
294 width, height = None, None
298 'format_id': format_id,
302 self._sort_formats(formats)
305 video_subtitles = self.extract_subtitles(video_id, webpage)
307 title = self._og_search_title(webpage, default=None)
309 title = self._html_search_regex(
310 r'(?s)<span\s+id="video_title"[^>]*>(.*?)</span>', webpage,
316 'uploader': info['owner.screenname'],
317 'timestamp': timestamp,
319 'description': description,
320 'subtitles': video_subtitles,
321 'thumbnail': info['thumbnail_url'],
322 'age_limit': age_limit,
323 'view_count': view_count,
324 'duration': info['duration']
327 def _check_error(self, info):
328 error = info.get('error')
330 title = error.get('title') or error['message']
331 # See https://developer.dailymotion.com/api#access-error
332 if error.get('code') == 'DM007':
333 self.raise_geo_restricted(msg=title)
334 raise ExtractorError(
335 '%s said: %s' % (self.IE_NAME, title), expected=True)
337 def _get_subtitles(self, video_id, webpage):
339 sub_list = self._download_webpage(
340 'https://api.dailymotion.com/video/%s/subtitles?fields=id,language,url' % video_id,
341 video_id, note=False)
342 except ExtractorError as err:
343 self._downloader.report_warning('unable to download video subtitles: %s' % error_to_compat_str(err))
345 info = json.loads(sub_list)
346 if (info['total'] > 0):
347 sub_lang_list = dict((l['language'], [{'url': l['url'], 'ext': 'srt'}]) for l in info['list'])
349 self._downloader.report_warning('video doesn\'t have subtitles')
353 class DailymotionPlaylistIE(DailymotionBaseInfoExtractor):
354 IE_NAME = 'dailymotion:playlist'
355 _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>x[0-9a-z]+)'
357 'url': 'http://www.dailymotion.com/playlist/xv4bw_nqtv_sport/1#video=xl8v3q',
362 'playlist_mincount': 20,
366 def _fetch_page(self, playlist_id, authorizaion, page):
368 videos = self._download_json(
369 'https://graphql.api.dailymotion.com',
370 playlist_id, 'Downloading page %d' % page,
373 collection(xid: "%s") {
374 videos(first: %d, page: %d) {
387 }''' % (playlist_id, self._PAGE_SIZE, page)
388 }).encode(), headers={
389 'Authorization': authorizaion,
390 'Origin': 'https://www.dailymotion.com',
391 })['data']['collection']['videos']
392 for edge in videos['edges']:
394 yield self.url_result(
395 node['url'], DailymotionIE.ie_key(), node['xid'])
397 def _real_extract(self, url):
398 playlist_id = self._match_id(url)
399 webpage = self._download_webpage(url, playlist_id)
400 api = self._parse_json(self._search_regex(
401 r'__PLAYER_CONFIG__\s*=\s*({.+?});',
402 webpage, 'player config'), playlist_id)['context']['api']
403 auth = self._download_json(
404 api.get('auth_url', 'https://graphql.api.dailymotion.com/oauth/token'),
405 playlist_id, data=urlencode_postdata({
406 'client_id': api.get('client_id', 'f1a362d288c1b98099c7'),
407 'client_secret': api.get('client_secret', 'eea605b96e01c796ff369935357eca920c5da4c5'),
408 'grant_type': 'client_credentials',
410 authorizaion = '%s %s' % (auth.get('token_type', 'Bearer'), auth['access_token'])
411 entries = OnDemandPagedList(functools.partial(
412 self._fetch_page, playlist_id, authorizaion), self._PAGE_SIZE)
413 return self.playlist_result(
414 entries, playlist_id,
415 self._og_search_title(webpage))
418 class DailymotionUserIE(DailymotionBaseInfoExtractor):
419 IE_NAME = 'dailymotion:user'
420 _VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/(?!(?:embed|swf|#|video|playlist)/)(?:(?:old/)?user/)?(?P<user>[^/]+)'
421 _MORE_PAGES_INDICATOR = r'(?s)<div class="pages[^"]*">.*?<a\s+class="[^"]*?icon-arrow_right[^"]*?"'
422 _PAGE_TEMPLATE = 'http://www.dailymotion.com/user/%s/%s'
424 'url': 'https://www.dailymotion.com/user/nqtv',
427 'title': 'Rémi Gaillard',
429 'playlist_mincount': 100,
431 'url': 'http://www.dailymotion.com/user/UnderProject',
433 'id': 'UnderProject',
434 'title': 'UnderProject',
436 'playlist_mincount': 1800,
437 'expected_warnings': [
438 'Stopped at duplicated page',
440 'skip': 'Takes too long time',
443 def _extract_entries(self, id):
445 processed_urls = set()
446 for pagenum in itertools.count(1):
447 page_url = self._PAGE_TEMPLATE % (id, pagenum)
448 webpage, urlh = self._download_webpage_handle_no_ff(
449 page_url, id, 'Downloading page %s' % pagenum)
450 if urlh.geturl() in processed_urls:
451 self.report_warning('Stopped at duplicated page %s, which is the same as %s' % (
452 page_url, urlh.geturl()), id)
455 processed_urls.add(urlh.geturl())
457 for video_id in re.findall(r'data-xid="(.+?)"', webpage):
458 if video_id not in video_ids:
459 yield self.url_result(
460 'http://www.dailymotion.com/video/%s' % video_id,
461 DailymotionIE.ie_key(), video_id)
462 video_ids.add(video_id)
464 if re.search(self._MORE_PAGES_INDICATOR, webpage) is None:
467 def _real_extract(self, url):
468 mobj = re.match(self._VALID_URL, url)
469 user = mobj.group('user')
470 webpage = self._download_webpage(
471 'https://www.dailymotion.com/user/%s' % user, user)
472 full_user = unescapeHTML(self._html_search_regex(
473 r'<a class="nav-image" title="([^"]+)" href="/%s">' % re.escape(user),
480 'entries': self._extract_entries(user),