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