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