[mtv] Check for geo-blocked videos in the xml document, not in the xml’s string
[youtube-dl] / youtube_dl / extractor / mtv.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from ..utils import (
7     compat_urllib_parse,
8     ExtractorError,
9     fix_xml_ampersands,
10 )
11
12 def _media_xml_tag(tag):
13     return '{http://search.yahoo.com/mrss/}%s' % tag
14
15
16 class MTVServicesInfoExtractor(InfoExtractor):
17     @staticmethod
18     def _id_from_uri(uri):
19         return uri.split(':')[-1]
20
21     # This was originally implemented for ComedyCentral, but it also works here
22     @staticmethod
23     def _transform_rtmp_url(rtmp_video_url):
24         m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp\..+?/.*)$', rtmp_video_url)
25         if not m:
26             return rtmp_video_url
27         base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
28         return base + m.group('finalid')
29
30     def _get_thumbnail_url(self, uri, itemdoc):
31         search_path = '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail'))
32         thumb_node = itemdoc.find(search_path)
33         if thumb_node is None:
34             return None
35         else:
36             return thumb_node.attrib['url']
37
38     def _extract_video_formats(self, mdoc):
39         if re.match(r'.*/error_country_block\.swf$', mdoc.find('.//src').text) is not None:
40             raise ExtractorError('This video is not available from your country.', expected=True)
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'&[^=]*?={.*?}(?=(&|$))', '', mediagen_url)
64         if 'acceptMethods' not in mediagen_url:
65             mediagen_url += '&acceptMethods=fms'
66         mediagen_doc = self._download_xml(mediagen_url, video_id,
67             '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_doc),
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             '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             'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
103             'file': '853555.mp4',
104             'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
105             'info_dict': {
106                 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
107                 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
108             },
109         },
110         {
111             'add_ie': ['Vevo'],
112             'url': 'http://www.mtv.com/videos/taylor-swift/916187/everything-has-changed-ft-ed-sheeran.jhtml',
113             'file': 'USCJY1331283.mp4',
114             'md5': '73b4e7fcadd88929292fe52c3ced8caf',
115             'info_dict': {
116                 'title': 'Everything Has Changed',
117                 'upload_date': '20130606',
118                 'uploader': 'Taylor Swift',
119             },
120             'skip': '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('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, 'uri')
143         return self._get_videos_info(uri)