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