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