[dailymotion] Correct test case
[youtube-dl] / youtube_dl / extractor / dailymotion.py
1 import re
2 import json
3 import itertools
4
5 from .common import InfoExtractor
6 from .subtitles import SubtitlesInfoExtractor
7
8 from ..utils import (
9     compat_urllib_request,
10     compat_str,
11     orderedSet,
12     str_to_int,
13     int_or_none,
14     ExtractorError,
15     unescapeHTML,
16 )
17
18 class DailymotionBaseInfoExtractor(InfoExtractor):
19     @staticmethod
20     def _build_request(url):
21         """Build a request with the family filter disabled"""
22         request = compat_urllib_request.Request(url)
23         request.add_header('Cookie', 'family_filter=off')
24         request.add_header('Cookie', 'ff=off')
25         return request
26
27 class DailymotionIE(DailymotionBaseInfoExtractor, SubtitlesInfoExtractor):
28     """Information Extractor for Dailymotion"""
29
30     _VALID_URL = r'(?i)(?:https?://)?(?:(www|touch)\.)?dailymotion\.[a-z]{2,3}/(?:(embed|#)/)?video/(?P<id>[^/?_]+)'
31     IE_NAME = 'dailymotion'
32
33     _FORMATS = [
34         ('stream_h264_ld_url', 'ld'),
35         ('stream_h264_url', 'standard'),
36         ('stream_h264_hq_url', 'hq'),
37         ('stream_h264_hd_url', 'hd'),
38         ('stream_h264_hd1080_url', 'hd180'),
39     ]
40
41     _TESTS = [
42         {
43             'url': 'http://www.dailymotion.com/video/x33vw9_tutoriel-de-youtubeur-dl-des-video_tech',
44             'md5': '392c4b85a60a90dc4792da41ce3144eb',
45             'info_dict': {
46                 'id': 'x33vw9',
47                 'ext': 'mp4',
48                 'uploader': 'Amphora Alex and Van .',
49                 'title': 'Tutoriel de Youtubeur"DL DES VIDEO DE YOUTUBE"',
50             }
51         },
52         # Vevo video
53         {
54             'url': 'http://www.dailymotion.com/video/x149uew_katy-perry-roar-official_musi',
55             'info_dict': {
56                 'title': 'Roar (Official)',
57                 'id': 'USUV71301934',
58                 'ext': 'mp4',
59                 'uploader': 'Katy Perry',
60                 'upload_date': '20130905',
61             },
62             'params': {
63                 'skip_download': True,
64             },
65             'skip': 'VEVO is only available in some countries',
66         },
67         # age-restricted video
68         {
69             'url': 'http://www.dailymotion.com/video/xyh2zz_leanna-decker-cyber-girl-of-the-year-desires-nude-playboy-plus_redband',
70             'md5': '0d667a7b9cebecc3c89ee93099c4159d',
71             'info_dict': {
72                 'id': 'xyh2zz',
73                 'ext': 'mp4',
74                 'title': 'Leanna Decker - Cyber Girl Of The Year Desires Nude [Playboy Plus]',
75                 'uploader': 'HotWaves1012',
76                 'age_limit': 18,
77             }
78         }
79     ]
80
81     def _real_extract(self, url):
82         # Extract id and simplified title from URL
83         mobj = re.match(self._VALID_URL, url)
84
85         video_id = mobj.group('id')
86
87         url = 'http://www.dailymotion.com/video/%s' % video_id
88
89         # Retrieve video webpage to extract further information
90         request = self._build_request(url)
91         webpage = self._download_webpage(request, video_id)
92
93         # Extract URL, uploader and title from webpage
94         self.report_extraction(video_id)
95
96         # It may just embed a vevo video:
97         m_vevo = re.search(
98             r'<link rel="video_src" href="[^"]*?vevo.com[^"]*?videoId=(?P<id>[\w]*)',
99             webpage)
100         if m_vevo is not None:
101             vevo_id = m_vevo.group('id')
102             self.to_screen(u'Vevo video detected: %s' % vevo_id)
103             return self.url_result(u'vevo:%s' % vevo_id, ie='Vevo')
104
105         age_limit = self._rta_search(webpage)
106
107         video_upload_date = None
108         mobj = re.search(r'<div class="[^"]*uploaded_cont[^"]*" title="[^"]*">([0-9]{2})-([0-9]{2})-([0-9]{4})</div>', webpage)
109         if mobj is not None:
110             video_upload_date = mobj.group(3) + mobj.group(2) + mobj.group(1)
111
112         embed_url = 'http://www.dailymotion.com/embed/video/%s' % video_id
113         embed_page = self._download_webpage(embed_url, video_id,
114                                             u'Downloading embed page')
115         info = self._search_regex(r'var info = ({.*?}),$', embed_page,
116             'video info', flags=re.MULTILINE)
117         info = json.loads(info)
118         if info.get('error') is not None:
119             msg = 'Couldn\'t get video, Dailymotion says: %s' % info['error']['title']
120             raise ExtractorError(msg, expected=True)
121
122         formats = []
123         for (key, format_id) in self._FORMATS:
124             video_url = info.get(key)
125             if video_url is not None:
126                 m_size = re.search(r'H264-(\d+)x(\d+)', video_url)
127                 if m_size is not None:
128                     width, height = map(int_or_none, (m_size.group(1), m_size.group(2)))
129                 else:
130                     width, height = None, None
131                 formats.append({
132                     'url': video_url,
133                     'ext': 'mp4',
134                     'format_id': format_id,
135                     'width': width,
136                     'height': height,
137                 })
138         if not formats:
139             raise ExtractorError(u'Unable to extract video URL')
140
141         # subtitles
142         video_subtitles = self.extract_subtitles(video_id, webpage)
143         if self._downloader.params.get('listsubtitles', False):
144             self._list_available_subtitles(video_id, webpage)
145             return
146
147         view_count = self._search_regex(
148             r'video_views_count[^>]+>\s+([\d\.,]+)', webpage, u'view count', fatal=False)
149         if view_count is not None:
150             view_count = str_to_int(view_count)
151
152         return {
153             'id':       video_id,
154             'formats': formats,
155             'uploader': info['owner.screenname'],
156             'upload_date':  video_upload_date,
157             'title':    self._og_search_title(webpage),
158             'subtitles':    video_subtitles,
159             'thumbnail': info['thumbnail_url'],
160             'age_limit': age_limit,
161             'view_count': view_count,
162         }
163
164     def _get_available_subtitles(self, video_id, webpage):
165         try:
166             sub_list = self._download_webpage(
167                 'https://api.dailymotion.com/video/%s/subtitles?fields=id,language,url' % video_id,
168                 video_id, note=False)
169         except ExtractorError as err:
170             self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
171             return {}
172         info = json.loads(sub_list)
173         if (info['total'] > 0):
174             sub_lang_list = dict((l['language'], l['url']) for l in info['list'])
175             return sub_lang_list
176         self._downloader.report_warning(u'video doesn\'t have subtitles')
177         return {}
178
179
180 class DailymotionPlaylistIE(DailymotionBaseInfoExtractor):
181     IE_NAME = u'dailymotion:playlist'
182     _VALID_URL = r'(?:https?://)?(?:www\.)?dailymotion\.[a-z]{2,3}/playlist/(?P<id>.+?)/'
183     _MORE_PAGES_INDICATOR = r'(?s)<div class="pages[^"]*">.*?<a\s+class="[^"]*?icon-arrow_right[^"]*?"'
184     _PAGE_TEMPLATE = 'https://www.dailymotion.com/playlist/%s/%s'
185
186     def _extract_entries(self, id):
187         video_ids = []
188         for pagenum in itertools.count(1):
189             request = self._build_request(self._PAGE_TEMPLATE % (id, pagenum))
190             webpage = self._download_webpage(request,
191                                              id, u'Downloading page %s' % pagenum)
192
193             video_ids.extend(re.findall(r'data-xid="(.+?)"', webpage))
194
195             if re.search(self._MORE_PAGES_INDICATOR, webpage) is None:
196                 break
197         return [self.url_result('http://www.dailymotion.com/video/%s' % video_id, 'Dailymotion')
198                    for video_id in orderedSet(video_ids)]
199
200     def _real_extract(self, url):
201         mobj = re.match(self._VALID_URL, url)
202         playlist_id = mobj.group('id')
203         webpage = self._download_webpage(url, playlist_id)
204
205         return {
206             '_type': 'playlist',
207             'id': playlist_id,
208             'title': self._og_search_title(webpage),
209             'entries': self._extract_entries(playlist_id),
210         }
211
212
213 class DailymotionUserIE(DailymotionPlaylistIE):
214     IE_NAME = u'dailymotion:user'
215     _VALID_URL = r'https?://(?:www\.)?dailymotion\.[a-z]{2,3}/user/(?P<user>[^/]+)'
216     _PAGE_TEMPLATE = 'http://www.dailymotion.com/user/%s/%s'
217
218     def _real_extract(self, url):
219         mobj = re.match(self._VALID_URL, url)
220         user = mobj.group('user')
221         webpage = self._download_webpage(url, user)
222         full_user = unescapeHTML(self._html_search_regex(
223             r'<a class="nav-image" title="([^"]+)" href="/%s">' % re.escape(user),
224             webpage, u'user', flags=re.DOTALL))
225
226         return {
227             '_type': 'playlist',
228             'id': user,
229             'title': full_user,
230             'entries': self._extract_entries(user),
231         }