[mtv] Extract subtitles (Closes #4811)
[youtube-dl] / youtube_dl / extractor / mtv.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .subtitles import SubtitlesInfoExtractor
6 from ..compat import (
7     compat_urllib_parse,
8     compat_urllib_request,
9     compat_str,
10 )
11 from ..utils import (
12     ExtractorError,
13     find_xpath_attr,
14     fix_xml_ampersands,
15     HEADRequest,
16     unescapeHTML,
17     url_basename,
18     RegexNotFoundError,
19 )
20
21
22 def _media_xml_tag(tag):
23     return '{http://search.yahoo.com/mrss/}%s' % tag
24
25
26 class MTVServicesInfoExtractor(SubtitlesInfoExtractor):
27     _MOBILE_TEMPLATE = None
28
29     @staticmethod
30     def _id_from_uri(uri):
31         return uri.split(':')[-1]
32
33     # This was originally implemented for ComedyCentral, but it also works here
34     @staticmethod
35     def _transform_rtmp_url(rtmp_video_url):
36         m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp\..+?/.*)$', rtmp_video_url)
37         if not m:
38             return rtmp_video_url
39         base = 'http://viacommtvstrmfs.fplive.net/'
40         return base + m.group('finalid')
41
42     def _get_feed_url(self, uri):
43         return self._FEED_URL
44
45     def _get_thumbnail_url(self, uri, itemdoc):
46         search_path = '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail'))
47         thumb_node = itemdoc.find(search_path)
48         if thumb_node is None:
49             return None
50         else:
51             return thumb_node.attrib['url']
52
53     def _extract_mobile_video_formats(self, mtvn_id):
54         webpage_url = self._MOBILE_TEMPLATE % mtvn_id
55         req = compat_urllib_request.Request(webpage_url)
56         # Otherwise we get a webpage that would execute some javascript
57         req.add_header('User-Agent', 'curl/7')
58         webpage = self._download_webpage(req, mtvn_id,
59                                          'Downloading mobile page')
60         metrics_url = unescapeHTML(self._search_regex(r'<a href="(http://metrics.+?)"', webpage, 'url'))
61         req = HEADRequest(metrics_url)
62         response = self._request_webpage(req, mtvn_id, 'Resolving url')
63         url = response.geturl()
64         # Transform the url to get the best quality:
65         url = re.sub(r'.+pxE=mp4', 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=0+_pxK=18639+_pxE=mp4', url, 1)
66         return [{'url': url, 'ext': 'mp4'}]
67
68     def _extract_video_formats(self, mdoc, mtvn_id):
69         if re.match(r'.*/(error_country_block\.swf|geoblock\.mp4)$', mdoc.find('.//src').text) is not None:
70             if mtvn_id is not None and self._MOBILE_TEMPLATE is not None:
71                 self.to_screen('The normal version is not available from your '
72                                'country, trying with the mobile version')
73                 return self._extract_mobile_video_formats(mtvn_id)
74             raise ExtractorError('This video is not available from your country.',
75                                  expected=True)
76
77         formats = []
78         for rendition in mdoc.findall('.//rendition'):
79             try:
80                 _, _, ext = rendition.attrib['type'].partition('/')
81                 rtmp_video_url = rendition.find('./src').text
82                 formats.append({'ext': ext,
83                                 'url': self._transform_rtmp_url(rtmp_video_url),
84                                 'format_id': rendition.get('bitrate'),
85                                 'width': int(rendition.get('width')),
86                                 'height': int(rendition.get('height')),
87                                 })
88             except (KeyError, TypeError):
89                 raise ExtractorError('Invalid rendition field.')
90         self._sort_formats(formats)
91         return formats
92
93     def _extract_subtitles(self, mdoc, mtvn_id):
94         subtitles = {}
95         FORMATS = {
96             'scc': 'cea-608',
97             'eia-608': 'cea-608',
98             'xml': 'ttml',
99         }
100         subtitles_format = FORMATS.get(
101             self._downloader.params.get('subtitlesformat'), 'ttml')
102         for transcript in mdoc.findall('.//transcript'):
103             if transcript.get('kind') != 'captions':
104                 continue
105             lang = transcript.get('srclang')
106             for typographic in transcript.findall('./typographic'):
107                 captions_format = typographic.get('format')
108                 if captions_format == subtitles_format:
109                     subtitles[lang] = compat_str(typographic.get('src'))
110                     break
111         if self._downloader.params.get('listsubtitles', False):
112             self._list_available_subtitles(mtvn_id, subtitles)
113         return self.extract_subtitles(mtvn_id, subtitles)
114
115     def _get_video_info(self, itemdoc):
116         uri = itemdoc.find('guid').text
117         video_id = self._id_from_uri(uri)
118         self.report_extraction(video_id)
119         mediagen_url = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content'))).attrib['url']
120         # Remove the templates, like &device={device}
121         mediagen_url = re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', mediagen_url)
122         if 'acceptMethods' not in mediagen_url:
123             mediagen_url += '&acceptMethods=fms'
124
125         mediagen_doc = self._download_xml(mediagen_url, video_id,
126                                           'Downloading video urls')
127
128         description_node = itemdoc.find('description')
129         if description_node is not None:
130             description = description_node.text.strip()
131         else:
132             description = None
133
134         title_el = None
135         if title_el is None:
136             title_el = find_xpath_attr(
137                 itemdoc, './/{http://search.yahoo.com/mrss/}category',
138                 'scheme', 'urn:mtvn:video_title')
139         if title_el is None:
140             title_el = itemdoc.find('.//{http://search.yahoo.com/mrss/}title')
141         if title_el is None:
142             title_el = itemdoc.find('.//title')
143             if title_el.text is None:
144                 title_el = None
145
146         title = title_el.text
147         if title is None:
148             raise ExtractorError('Could not find video title')
149         title = title.strip()
150
151         # This a short id that's used in the webpage urls
152         mtvn_id = None
153         mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
154                                        'scheme', 'urn:mtvn:id')
155         if mtvn_id_node is not None:
156             mtvn_id = mtvn_id_node.text
157
158         return {
159             'title': title,
160             'formats': self._extract_video_formats(mediagen_doc, mtvn_id),
161             'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
162             'id': video_id,
163             'thumbnail': self._get_thumbnail_url(uri, itemdoc),
164             'description': description,
165         }
166
167     def _get_videos_info(self, uri):
168         video_id = self._id_from_uri(uri)
169         feed_url = self._get_feed_url(uri)
170         data = compat_urllib_parse.urlencode({'uri': uri})
171         idoc = self._download_xml(
172             feed_url + '?' + data, video_id,
173             'Downloading info', transform_source=fix_xml_ampersands)
174         return self.playlist_result(
175             [self._get_video_info(item) for item in idoc.findall('.//item')])
176
177     def _real_extract(self, url):
178         title = url_basename(url)
179         webpage = self._download_webpage(url, title)
180         try:
181             # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
182             # or http://media.mtvnservices.com/{mgid}
183             og_url = self._og_search_video_url(webpage)
184             mgid = url_basename(og_url)
185             if mgid.endswith('.swf'):
186                 mgid = mgid[:-4]
187         except RegexNotFoundError:
188             mgid = None
189
190         if mgid is None or ':' not in mgid:
191             mgid = self._search_regex(
192                 [r'data-mgid="(.*?)"', r'swfobject.embedSWF\(".*?(mgid:.*?)"'],
193                 webpage, 'mgid')
194
195         videos_info = self._get_videos_info(mgid)
196         if self._downloader.params.get('listsubtitles', False):
197             return
198         return videos_info
199
200
201 class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
202     IE_NAME = 'mtvservices:embedded'
203     _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
204
205     _TEST = {
206         # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
207         'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
208         'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
209         'info_dict': {
210             'id': '1043906',
211             'ext': 'mp4',
212             'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
213             'description': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage as he tries summarizing "Game of Thrones" in under a minute.',
214         },
215     }
216
217     def _get_feed_url(self, uri):
218         video_id = self._id_from_uri(uri)
219         site_id = uri.replace(video_id, '')
220         config_url = ('http://media.mtvnservices.com/pmt/e1/players/{0}/'
221                       'context4/context5/config.xml'.format(site_id))
222         config_doc = self._download_xml(config_url, video_id)
223         feed_node = config_doc.find('.//feed')
224         feed_url = feed_node.text.strip().split('?')[0]
225         return feed_url
226
227     def _real_extract(self, url):
228         mobj = re.match(self._VALID_URL, url)
229         mgid = mobj.group('mgid')
230         return self._get_videos_info(mgid)
231
232
233 class MTVIE(MTVServicesInfoExtractor):
234     _VALID_URL = r'''(?x)^https?://
235         (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
236            m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
237
238     _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
239
240     _TESTS = [
241         {
242             'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
243             'file': '853555.mp4',
244             'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
245             'info_dict': {
246                 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
247                 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
248             },
249         },
250         {
251             'add_ie': ['Vevo'],
252             'url': 'http://www.mtv.com/videos/taylor-swift/916187/everything-has-changed-ft-ed-sheeran.jhtml',
253             'file': 'USCJY1331283.mp4',
254             'md5': '73b4e7fcadd88929292fe52c3ced8caf',
255             'info_dict': {
256                 'title': 'Everything Has Changed',
257                 'upload_date': '20130606',
258                 'uploader': 'Taylor Swift',
259             },
260             'skip': 'VEVO is only available in some countries',
261         },
262     ]
263
264     def _get_thumbnail_url(self, uri, itemdoc):
265         return 'http://mtv.mtvnimages.com/uri/' + uri
266
267     def _real_extract(self, url):
268         mobj = re.match(self._VALID_URL, url)
269         video_id = mobj.group('videoid')
270         uri = mobj.groupdict().get('mgid')
271         if uri is None:
272             webpage = self._download_webpage(url, video_id)
273
274             # Some videos come from Vevo.com
275             m_vevo = re.search(r'isVevoVideo = true;.*?vevoVideoId = "(.*?)";',
276                                webpage, re.DOTALL)
277             if m_vevo:
278                 vevo_id = m_vevo.group(1)
279                 self.to_screen('Vevo video detected: %s' % vevo_id)
280                 return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
281
282             uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
283         return self._get_videos_info(uri)
284
285
286 class MTVIggyIE(MTVServicesInfoExtractor):
287     IE_NAME = 'mtviggy.com'
288     _VALID_URL = r'https?://www\.mtviggy\.com/videos/.+'
289     _TEST = {
290         'url': 'http://www.mtviggy.com/videos/arcade-fire-behind-the-scenes-at-the-biggest-music-experiment-yet/',
291         'info_dict': {
292             'id': '984696',
293             'ext': 'mp4',
294             'title': 'Arcade Fire: Behind the Scenes at the Biggest Music Experiment Yet',
295         }
296     }
297     _FEED_URL = 'http://all.mtvworldverticals.com/feed-xml/'