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