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