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