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