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