Correct XML ampersand fixup
[youtube-dl] / youtube_dl / extractor / mtv.py
1 import re
2 import xml.etree.ElementTree
3
4 from .common import InfoExtractor
5 from ..utils import (
6     compat_urllib_parse,
7     ExtractorError,
8     fix_xml_ampersands,
9 )
10
11 def _media_xml_tag(tag):
12     return '{http://search.yahoo.com/mrss/}%s' % tag
13
14
15 class MTVServicesInfoExtractor(InfoExtractor):
16     @staticmethod
17     def _id_from_uri(uri):
18         return uri.split(':')[-1]
19
20     # This was originally implemented for ComedyCentral, but it also works here
21     @staticmethod
22     def _transform_rtmp_url(rtmp_video_url):
23         m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp\..+?/.*)$', rtmp_video_url)
24         if not m:
25             return rtmp_video_url
26         base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
27         return base + m.group('finalid')
28
29     def _get_thumbnail_url(self, uri, itemdoc):
30         search_path = '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail'))
31         thumb_node = itemdoc.find(search_path)
32         if thumb_node is None:
33             return None
34         else:
35             return thumb_node.attrib['url']
36
37     def _extract_video_formats(self, metadataXml):
38         if '/error_country_block.swf' in metadataXml:
39             raise ExtractorError(u'This video is not available from your country.', expected=True)
40         mdoc = xml.etree.ElementTree.fromstring(metadataXml.encode('utf-8'))
41
42         formats = []
43         for rendition in mdoc.findall('.//rendition'):
44             try:
45                 _, _, ext = rendition.attrib['type'].partition('/')
46                 rtmp_video_url = rendition.find('./src').text
47                 formats.append({'ext': ext,
48                                 'url': self._transform_rtmp_url(rtmp_video_url),
49                                 'format_id': rendition.get('bitrate'),
50                                 'width': int(rendition.get('width')),
51                                 'height': int(rendition.get('height')),
52                                 })
53             except (KeyError, TypeError):
54                 raise ExtractorError('Invalid rendition field.')
55         return formats
56
57     def _get_video_info(self, itemdoc):
58         uri = itemdoc.find('guid').text
59         video_id = self._id_from_uri(uri)
60         self.report_extraction(video_id)
61         mediagen_url = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content'))).attrib['url']
62         # Remove the templates, like &device={device}
63         mediagen_url = re.sub(r'&[^=]*?={.*?}(?=(&|$))', u'', mediagen_url)
64         if 'acceptMethods' not in mediagen_url:
65             mediagen_url += '&acceptMethods=fms'
66         mediagen_page = self._download_webpage(mediagen_url, video_id,
67                                                u'Downloading video urls')
68
69         description_node = itemdoc.find('description')
70         if description_node is not None:
71             description = description_node.text.strip()
72         else:
73             description = None
74
75         return {
76             'title': itemdoc.find('title').text,
77             'formats': self._extract_video_formats(mediagen_page),
78             'id': video_id,
79             'thumbnail': self._get_thumbnail_url(uri, itemdoc),
80             'description': description,
81         }
82
83     def _get_videos_info(self, uri):
84         video_id = self._id_from_uri(uri)
85         data = compat_urllib_parse.urlencode({'uri': uri})
86
87         idoc = self._download_xml(
88             self._FEED_URL + '?' + data, video_id,
89             u'Downloading info', transform_source=fix_xml_ampersands)
90         return [self._get_video_info(item) for item in idoc.findall('.//item')]
91
92
93 class MTVIE(MTVServicesInfoExtractor):
94     _VALID_URL = r'''(?x)^https?://
95         (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
96            m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
97
98     _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
99
100     _TESTS = [
101         {
102             u'url': u'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
103             u'file': u'853555.mp4',
104             u'md5': u'850f3f143316b1e71fa56a4edfd6e0f8',
105             u'info_dict': {
106                 u'title': u'Taylor Swift - "Ours (VH1 Storytellers)"',
107                 u'description': u'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
108             },
109         },
110         {
111             u'add_ie': ['Vevo'],
112             u'url': u'http://www.mtv.com/videos/taylor-swift/916187/everything-has-changed-ft-ed-sheeran.jhtml',
113             u'file': u'USCJY1331283.mp4',
114             u'md5': u'73b4e7fcadd88929292fe52c3ced8caf',
115             u'info_dict': {
116                 u'title': u'Everything Has Changed',
117                 u'upload_date': u'20130606',
118                 u'uploader': u'Taylor Swift',
119             },
120             u'skip': u'VEVO is only available in some countries',
121         },
122     ]
123
124     def _get_thumbnail_url(self, uri, itemdoc):
125         return 'http://mtv.mtvnimages.com/uri/' + uri
126
127     def _real_extract(self, url):
128         mobj = re.match(self._VALID_URL, url)
129         video_id = mobj.group('videoid')
130         uri = mobj.groupdict().get('mgid')
131         if uri is None:
132             webpage = self._download_webpage(url, video_id)
133     
134             # Some videos come from Vevo.com
135             m_vevo = re.search(r'isVevoVideo = true;.*?vevoVideoId = "(.*?)";',
136                                webpage, re.DOTALL)
137             if m_vevo:
138                 vevo_id = m_vevo.group(1);
139                 self.to_screen(u'Vevo video detected: %s' % vevo_id)
140                 return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
141     
142             uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, u'uri')
143         return self._get_videos_info(uri)