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