]> jfr.im git - yt-dlp.git/blob - youtube_dl/extractor/dailymotion.py
[packtpub] add support for authentication(closes #12622)
[yt-dlp.git] / youtube_dl / extractor / dailymotion.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import json
6 import itertools
7
8 from .common import InfoExtractor
9
10 from ..utils import (
11 determine_ext,
12 error_to_compat_str,
13 ExtractorError,
14 int_or_none,
15 parse_iso8601,
16 sanitized_Request,
17 str_to_int,
18 unescapeHTML,
19 mimetype2ext,
20 )
21
22
23 class DailymotionBaseInfoExtractor(InfoExtractor):
24 @staticmethod
25 def _build_request(url):
26 """Build a request with the family filter disabled"""
27 request = sanitized_Request(url)
28 request.add_header('Cookie', 'family_filter=off; ff=off')
29 return request
30
31 def _download_webpage_handle_no_ff(self, url, *args, **kwargs):
32 request = self._build_request(url)
33 return self._download_webpage_handle(request, *args, **kwargs)
34
35 def _download_webpage_no_ff(self, url, *args, **kwargs):
36 request = self._build_request(url)
37 return self._download_webpage(request, *args, **kwargs)
38
39
40 class DailymotionIE(DailymotionBaseInfoExtractor):
41 _VALID_URL = r'(?i)(?:https?://)?(?:(www|touch)\.)?dailymotion\.[a-z]{2,3}/(?:(?:embed|swf|#)/)?video/(?P<id>[^/?_]+)'
42 IE_NAME = 'dailymotion'
43
44 _FORMATS = [
45 ('stream_h264_ld_url', 'ld'),
46 ('stream_h264_url', 'standard'),
47 ('stream_h264_hq_url', 'hq'),
48 ('stream_h264_hd_url', 'hd'),
49 ('stream_h264_hd1080_url', 'hd180'),
50 ]
51
52 _TESTS = [
53 {
54 'url': 'http://www.dailymotion.com/video/x5kesuj_office-christmas-party-review-jason-bateman-olivia-munn-t-j-miller_news',
55 'md5': '074b95bdee76b9e3654137aee9c79dfe',
56 'info_dict': {
57 'id': 'x5kesuj',
58 'ext': 'mp4',
59 'title': 'Office Christmas Party Review – Jason Bateman, Olivia Munn, T.J. Miller',
60 'description': 'Office Christmas Party Review - Jason Bateman, Olivia Munn, T.J. Miller',
61 'thumbnail': r're:^https?:.*\.(?:jpg|png)$',
62 'duration': 187,
63 'timestamp': 1493651285,
64 'upload_date': '20170501',
65 'uploader': 'Deadline',
66 'uploader_id': 'x1xm8ri',
67 'age_limit': 0,
68 'view_count': int,
69 },
70 },
71 {
72 'url': 'https://www.dailymotion.com/video/x2iuewm_steam-machine-models-pricing-listed-on-steam-store-ign-news_videogames',
73 'md5': '2137c41a8e78554bb09225b8eb322406',
74 'info_dict': {
75 'id': 'x2iuewm',
76 'ext': 'mp4',
77 'title': 'Steam Machine Models, Pricing Listed on Steam Store - IGN News',
78 'description': 'Several come bundled with the Steam Controller.',
79 'thumbnail': r're:^https?:.*\.(?:jpg|png)$',
80 'duration': 74,
81 'timestamp': 1425657362,
82 'upload_date': '20150306',
83 'uploader': 'IGN',
84 'uploader_id': 'xijv66',
85 'age_limit': 0,
86 'view_count': int,
87 },
88 'skip': 'video gone',
89 },
90 # Vevo video
91 {
92 'url': 'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi',
93 'info_dict': {
94 'title': 'Roar (Official)',
95 'id': 'USUV71301934',
96 'ext': 'mp4',
97 'uploader': 'Katy Perry',
98 'upload_date': '20130905',
99 },
100 'params': {
101 'skip_download': True,
102 },
103 'skip': 'VEVO is only available in some countries',
104 },
105 # age-restricted video
106 {
107 'url': 'http://www.dailymotion.com/video/xyh2zz_leanna-decker-cyber-girl-of-the-year-desires-nude-playboy-plus_redband',
108 'md5': '0d667a7b9cebecc3c89ee93099c4159d',
109 'info_dict': {
110 'id': 'xyh2zz',
111 'ext': 'mp4',
112 'title': 'Leanna Decker - Cyber Girl Of The Year Desires Nude [Playboy Plus]',
113 'uploader': 'HotWaves1012',
114 'age_limit': 18,
115 },
116 'skip': 'video gone',
117 },
118 # geo-restricted, player v5
119 {
120 'url': 'http://www.dailymotion.com/video/xhza0o',
121 'only_matching': True,
122 },
123 # with subtitles
124 {
125 'url': 'http://www.dailymotion.com/video/x20su5f_the-power-of-nightmares-1-the-rise-of-the-politics-of-fear-bbc-2004_news',
126 'only_matching': True,
127 },
128 {
129 'url': 'http://www.dailymotion.com/swf/video/x3n92nf',
130 'only_matching': True,
131 }
132 ]
133
134 @staticmethod
135 def _extract_urls(webpage):
136 # Look for embedded Dailymotion player
137 matches = re.findall(
138 r'<(?:(?:embed|iframe)[^>]+?src=|input[^>]+id=[\'"]dmcloudUrlEmissionSelect[\'"][^>]+value=)(["\'])(?P<url>(?:https?:)?//(?:www\.)?dailymotion\.com/(?:embed|swf)/video/.+?)\1', webpage)
139 return list(map(lambda m: unescapeHTML(m[1]), matches))
140
141 def _real_extract(self, url):
142 video_id = self._match_id(url)
143
144 webpage = self._download_webpage_no_ff(
145 'https://www.dailymotion.com/video/%s' % video_id, video_id)
146
147 age_limit = self._rta_search(webpage)
148
149 description = self._og_search_description(webpage) or self._html_search_meta(
150 'description', webpage, 'description')
151
152 view_count_str = self._search_regex(
153 (r'<meta[^>]+itemprop="interactionCount"[^>]+content="UserPlays:([\s\d,.]+)"',
154 r'video_views_count[^>]+>\s+([\s\d\,.]+)'),
155 webpage, 'view count', fatal=False)
156 if view_count_str:
157 view_count_str = re.sub(r'\s', '', view_count_str)
158 view_count = str_to_int(view_count_str)
159 comment_count = int_or_none(self._search_regex(
160 r'<meta[^>]+itemprop="interactionCount"[^>]+content="UserComments:(\d+)"',
161 webpage, 'comment count', default=None))
162
163 player_v5 = self._search_regex(
164 [r'buildPlayer\(({.+?})\);\n', # See https://github.com/rg3/youtube-dl/issues/7826
165 r'playerV5\s*=\s*dmp\.create\([^,]+?,\s*({.+?})\);',
166 r'buildPlayer\(({.+?})\);',
167 r'var\s+config\s*=\s*({.+?});'],
168 webpage, 'player v5', default=None)
169 if player_v5:
170 player = self._parse_json(player_v5, video_id)
171 metadata = player['metadata']
172
173 self._check_error(metadata)
174
175 formats = []
176 for quality, media_list in metadata['qualities'].items():
177 for media in media_list:
178 media_url = media.get('url')
179 if not media_url:
180 continue
181 type_ = media.get('type')
182 if type_ == 'application/vnd.lumberjack.manifest':
183 continue
184 ext = mimetype2ext(type_) or determine_ext(media_url)
185 if ext == 'm3u8':
186 formats.extend(self._extract_m3u8_formats(
187 media_url, video_id, 'mp4', preference=-1,
188 m3u8_id='hls', fatal=False))
189 elif ext == 'f4m':
190 formats.extend(self._extract_f4m_formats(
191 media_url, video_id, preference=-1, f4m_id='hds', fatal=False))
192 else:
193 f = {
194 'url': media_url,
195 'format_id': 'http-%s' % quality,
196 'ext': ext,
197 }
198 m = re.search(r'H264-(?P<width>\d+)x(?P<height>\d+)', media_url)
199 if m:
200 f.update({
201 'width': int(m.group('width')),
202 'height': int(m.group('height')),
203 })
204 formats.append(f)
205 self._sort_formats(formats)
206
207 title = metadata['title']
208 duration = int_or_none(metadata.get('duration'))
209 timestamp = int_or_none(metadata.get('created_time'))
210 thumbnail = metadata.get('poster_url')
211 uploader = metadata.get('owner', {}).get('screenname')
212 uploader_id = metadata.get('owner', {}).get('id')
213
214 subtitles = {}
215 subtitles_data = metadata.get('subtitles', {}).get('data', {})
216 if subtitles_data and isinstance(subtitles_data, dict):
217 for subtitle_lang, subtitle in subtitles_data.items():
218 subtitles[subtitle_lang] = [{
219 'ext': determine_ext(subtitle_url),
220 'url': subtitle_url,
221 } for subtitle_url in subtitle.get('urls', [])]
222
223 return {
224 'id': video_id,
225 'title': title,
226 'description': description,
227 'thumbnail': thumbnail,
228 'duration': duration,
229 'timestamp': timestamp,
230 'uploader': uploader,
231 'uploader_id': uploader_id,
232 'age_limit': age_limit,
233 'view_count': view_count,
234 'comment_count': comment_count,
235 'formats': formats,
236 'subtitles': subtitles,
237 }
238
239 # vevo embed
240 vevo_id = self._search_regex(
241 r'<link rel="video_src" href="[^"]*?vevo.com[^"]*?video=(?P<id>[\w]*)',
242 webpage, 'vevo embed', default=None)
243 if vevo_id:
244 return self.url_result('vevo:%s' % vevo_id, 'Vevo')
245
246 # fallback old player
247 embed_page = self._download_webpage_no_ff(
248 'https://www.dailymotion.com/embed/video/%s' % video_id,
249 video_id, 'Downloading embed page')
250
251 timestamp = parse_iso8601(self._html_search_meta(
252 'video:release_date', webpage, 'upload date'))
253
254 info = self._parse_json(
255 self._search_regex(
256 r'var info = ({.*?}),$', embed_page,
257 'video info', flags=re.MULTILINE),
258 video_id)
259
260 self._check_error(info)
261
262 formats = []
263 for (key, format_id) in self._FORMATS:
264 video_url = info.get(key)
265 if video_url is not None:
266 m_size = re.search(r'H264-(\d+)x(\d+)', video_url)
267 if m_size is not None:
268 width, height = map(int_or_none, (m_size.group(1), m_size.group(2)))
269 else:
270 width, height = None, None
271 formats.append({
272 'url': video_url,
273 'ext': 'mp4',
274 'format_id': format_id,
275 'width': width,
276 'height': height,
277 })
278 self._sort_formats(formats)
279
280 # subtitles
281 video_subtitles = self.extract_subtitles(video_id, webpage)
282
283 title = self._og_search_title(webpage, default=None)
284 if title is None:
285 title = self._html_search_regex(
286 r'(?s)<span\s+id="video_title"[^>]*>(.*?)</span>', webpage,
287 'title')
288
289 return {
290 'id': video_id,
291 'formats': formats,
292 'uploader': info['owner.screenname'],
293 'timestamp': timestamp,
294 'title': title,
295 'description': description,
296 'subtitles': video_subtitles,
297 'thumbnail': info['thumbnail_url'],
298 'age_limit': age_limit,
299 'view_count': view_count,
300 'duration': info['duration']
301 }
302
303 def _check_error(self, info):
304 error = info.get('error')
305 if info.get('error') is not None:
306 title = error['title']
307 # See https://developer.dailymotion.com/api#access-error
308 if error.get('code') == 'DM007':
309 self.raise_geo_restricted(msg=title)
310 raise ExtractorError(
311 '%s said: %s' % (self.IE_NAME, title), expected=True)
312
313 def _get_subtitles(self, video_id, webpage):
314 try:
315 sub_list = self._download_webpage(
316 'https://api.dailymotion.com/video/%s/subtitles?fields=id,language,url' % video_id,
317 video_id, note=False)
318 except ExtractorError as err:
319 self._downloader.report_warning('unable to download video subtitles: %s' % error_to_compat_str(err))
320 return {}
321 info = json.loads(sub_list)
322 if (info['total'] > 0):
323 sub_lang_list = dict((l['language'], [{'url': l['url'], 'ext': 'srt'}]) for l in info['list'])
324 return sub_lang_list
325 self._downloader.report_warning('video doesn\'t have subtitles')
326 return {}
327
328
329 class DailymotionPlaylistIE(DailymotionBaseInfoExtractor):
330 IE_NAME = 'dailymotion:playlist'
331 _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>.+?)/'
332 _MORE_PAGES_INDICATOR = r'(?s)<div class="pages[^"]*">.*?<a\s+class="[^"]*?icon-arrow_right[^"]*?"'
333 _PAGE_TEMPLATE = 'https://www.dailymotion.com/playlist/%s/%s'
334 _TESTS = [{
335 'url': 'http://www.dailymotion.com/playlist/xv4bw_nqtv_sport/1#video=xl8v3q',
336 'info_dict': {
337 'title': 'SPORT',
338 'id': 'xv4bw_nqtv_sport',
339 },
340 'playlist_mincount': 20,
341 }]
342
343 def _extract_entries(self, id):
344 video_ids = set()
345 processed_urls = set()
346 for pagenum in itertools.count(1):
347 page_url = self._PAGE_TEMPLATE % (id, pagenum)
348 webpage, urlh = self._download_webpage_handle_no_ff(
349 page_url, id, 'Downloading page %s' % pagenum)
350 if urlh.geturl() in processed_urls:
351 self.report_warning('Stopped at duplicated page %s, which is the same as %s' % (
352 page_url, urlh.geturl()), id)
353 break
354
355 processed_urls.add(urlh.geturl())
356
357 for video_id in re.findall(r'data-xid="(.+?)"', webpage):
358 if video_id not in video_ids:
359 yield self.url_result(
360 'http://www.dailymotion.com/video/%s' % video_id,
361 DailymotionIE.ie_key(), video_id)
362 video_ids.add(video_id)
363
364 if re.search(self._MORE_PAGES_INDICATOR, webpage) is None:
365 break
366
367 def _real_extract(self, url):
368 mobj = re.match(self._VALID_URL, url)
369 playlist_id = mobj.group('id')
370 webpage = self._download_webpage(url, playlist_id)
371
372 return {
373 '_type': 'playlist',
374 'id': playlist_id,
375 'title': self._og_search_title(webpage),
376 'entries': self._extract_entries(playlist_id),
377 }
378
379
380 class DailymotionUserIE(DailymotionPlaylistIE):
381 IE_NAME = 'dailymotion:user'
382 _VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/(?!(?:embed|swf|#|video|playlist)/)(?:(?:old/)?user/)?(?P<user>[^/]+)'
383 _PAGE_TEMPLATE = 'http://www.dailymotion.com/user/%s/%s'
384 _TESTS = [{
385 'url': 'https://www.dailymotion.com/user/nqtv',
386 'info_dict': {
387 'id': 'nqtv',
388 'title': 'Rémi Gaillard',
389 },
390 'playlist_mincount': 100,
391 }, {
392 'url': 'http://www.dailymotion.com/user/UnderProject',
393 'info_dict': {
394 'id': 'UnderProject',
395 'title': 'UnderProject',
396 },
397 'playlist_mincount': 1800,
398 'expected_warnings': [
399 'Stopped at duplicated page',
400 ],
401 'skip': 'Takes too long time',
402 }]
403
404 def _real_extract(self, url):
405 mobj = re.match(self._VALID_URL, url)
406 user = mobj.group('user')
407 webpage = self._download_webpage(
408 'https://www.dailymotion.com/user/%s' % user, user)
409 full_user = unescapeHTML(self._html_search_regex(
410 r'<a class="nav-image" title="([^"]+)" href="/%s">' % re.escape(user),
411 webpage, 'user'))
412
413 return {
414 '_type': 'playlist',
415 'id': user,
416 'title': full_user,
417 'entries': self._extract_entries(user),
418 }
419
420
421 class DailymotionCloudIE(DailymotionBaseInfoExtractor):
422 _VALID_URL_PREFIX = r'https?://api\.dmcloud\.net/(?:player/)?embed/'
423 _VALID_URL = r'%s[^/]+/(?P<id>[^/?]+)' % _VALID_URL_PREFIX
424 _VALID_EMBED_URL = r'%s[^/]+/[^\'"]+' % _VALID_URL_PREFIX
425
426 _TESTS = [{
427 # From http://www.francetvinfo.fr/economie/entreprises/les-entreprises-familiales-le-secret-de-la-reussite_933271.html
428 # Tested at FranceTvInfo_2
429 'url': 'http://api.dmcloud.net/embed/4e7343f894a6f677b10006b4/556e03339473995ee145930c?auth=1464865870-0-jyhsm84b-ead4c701fb750cf9367bf4447167a3db&autoplay=1',
430 'only_matching': True,
431 }, {
432 # http://www.francetvinfo.fr/societe/larguez-les-amarres-le-cobaturage-se-developpe_980101.html
433 'url': 'http://api.dmcloud.net/player/embed/4e7343f894a6f677b10006b4/559545469473996d31429f06?auth=1467430263-0-90tglw2l-a3a4b64ed41efe48d7fccad85b8b8fda&autoplay=1',
434 'only_matching': True,
435 }]
436
437 @classmethod
438 def _extract_dmcloud_url(cls, webpage):
439 mobj = re.search(r'<iframe[^>]+src=[\'"](%s)[\'"]' % cls._VALID_EMBED_URL, webpage)
440 if mobj:
441 return mobj.group(1)
442
443 mobj = re.search(
444 r'<input[^>]+id=[\'"]dmcloudUrlEmissionSelect[\'"][^>]+value=[\'"](%s)[\'"]' % cls._VALID_EMBED_URL,
445 webpage)
446 if mobj:
447 return mobj.group(1)
448
449 def _real_extract(self, url):
450 video_id = self._match_id(url)
451
452 webpage = self._download_webpage_no_ff(url, video_id)
453
454 title = self._html_search_regex(r'<title>([^>]+)</title>', webpage, 'title')
455
456 video_info = self._parse_json(self._search_regex(
457 r'var\s+info\s*=\s*([^;]+);', webpage, 'video info'), video_id)
458
459 # TODO: parse ios_url, which is in fact a manifest
460 video_url = video_info['mp4_url']
461
462 return {
463 'id': video_id,
464 'url': video_url,
465 'title': title,
466 'thumbnail': video_info.get('thumbnail_url'),
467 }