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