[spike] Add support for downloading the mobile version if the normal version is geobl...
[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     compat_urllib_request,
9     ExtractorError,
10     find_xpath_attr,
11     fix_xml_ampersands,
12     unescapeHTML,
13     url_basename,
14     RegexNotFoundError,
15 )
16
17
18 def _media_xml_tag(tag):
19     return '{http://search.yahoo.com/mrss/}%s' % tag
20
21
22 class MTVServicesInfoExtractor(InfoExtractor):
23     _MOBILE_TEMPLATE = None
24     @staticmethod
25     def _id_from_uri(uri):
26         return uri.split(':')[-1]
27
28     # This was originally implemented for ComedyCentral, but it also works here
29     @staticmethod
30     def _transform_rtmp_url(rtmp_video_url):
31         m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp\..+?/.*)$', rtmp_video_url)
32         if not m:
33             return rtmp_video_url
34         base = 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=1+_pxI0=Ripod-h264+_pxL0=undefined+_pxM0=+_pxK=18639+_pxE=mp4/44620/mtvnorigin/'
35         return base + m.group('finalid')
36
37     def _get_thumbnail_url(self, uri, itemdoc):
38         search_path = '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail'))
39         thumb_node = itemdoc.find(search_path)
40         if thumb_node is None:
41             return None
42         else:
43             return thumb_node.attrib['url']
44
45     def _extract_mobile_video_formats(self, mtvn_id):
46         webpage_url = self._MOBILE_TEMPLATE % mtvn_id
47         req = compat_urllib_request.Request(webpage_url)
48         # Otherwise we get a webpage that would execute some javascript
49         req.add_header('Youtubedl-user-agent', 'curl/7')
50         webpage = self._download_webpage(req, mtvn_id,
51             'Downloading mobile page')
52         url = unescapeHTML(self._search_regex(r'<a href="(http://metrics.+?)"', webpage, 'url'))
53         return [{'url': url,'ext': 'mp4',}]
54
55     def _extract_video_formats(self, mdoc, mtvn_id):
56         if re.match(r'.*/(error_country_block\.swf|geoblock\.mp4)$', mdoc.find('.//src').text) is not None:
57             if mtvn_id is not None and self._MOBILE_TEMPLATE is not None:
58                 self._downloader.report_warning('The normal version is not '
59                     'available from your country, trying with the mobile version')
60                 return self._extract_mobile_video_formats(mtvn_id)
61             raise ExtractorError('This video is not available from your country.',
62                 expected=True)
63
64         formats = []
65         for rendition in mdoc.findall('.//rendition'):
66             try:
67                 _, _, ext = rendition.attrib['type'].partition('/')
68                 rtmp_video_url = rendition.find('./src').text
69                 formats.append({'ext': ext,
70                                 'url': self._transform_rtmp_url(rtmp_video_url),
71                                 'format_id': rendition.get('bitrate'),
72                                 'width': int(rendition.get('width')),
73                                 'height': int(rendition.get('height')),
74                                 })
75             except (KeyError, TypeError):
76                 raise ExtractorError('Invalid rendition field.')
77         return formats
78
79     def _get_video_info(self, itemdoc):
80         uri = itemdoc.find('guid').text
81         video_id = self._id_from_uri(uri)
82         self.report_extraction(video_id)
83         mediagen_url = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content'))).attrib['url']
84         # Remove the templates, like &device={device}
85         mediagen_url = re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', mediagen_url)
86         if 'acceptMethods' not in mediagen_url:
87             mediagen_url += '&acceptMethods=fms'
88
89         mediagen_doc = self._download_xml(mediagen_url, video_id,
90             'Downloading video urls')
91
92         description_node = itemdoc.find('description')
93         if description_node is not None:
94             description = description_node.text.strip()
95         else:
96             description = None
97
98         title_el = None
99         if title_el is None:
100             title_el = find_xpath_attr(
101                 itemdoc, './/{http://search.yahoo.com/mrss/}category',
102                 'scheme', 'urn:mtvn:video_title')
103         if title_el is None:
104             title_el = itemdoc.find('.//{http://search.yahoo.com/mrss/}title')
105         if title_el is None:
106             title_el = itemdoc.find('.//title')
107             if title_el.text is None:
108                 title_el = None
109
110         title = title_el.text
111         if title is None:
112             raise ExtractorError('Could not find video title')
113         title = title.strip()
114
115         # This a short id that's used in the webpage urls
116         mtvn_id = None
117         mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
118                 'scheme', 'urn:mtvn:id')
119         if mtvn_id_node is not None:
120             mtvn_id = mtvn_id_node.text
121
122         return {
123             'title': title,
124             'formats': self._extract_video_formats(mediagen_doc, mtvn_id),
125             'id': video_id,
126             'thumbnail': self._get_thumbnail_url(uri, itemdoc),
127             'description': description,
128         }
129
130     def _get_videos_info(self, uri):
131         video_id = self._id_from_uri(uri)
132         data = compat_urllib_parse.urlencode({'uri': uri})
133
134         idoc = self._download_xml(
135             self._FEED_URL + '?' + data, video_id,
136             'Downloading info', transform_source=fix_xml_ampersands)
137         return [self._get_video_info(item) for item in idoc.findall('.//item')]
138
139     def _real_extract(self, url):
140         title = url_basename(url)
141         webpage = self._download_webpage(url, title)
142         try:
143             # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
144             # or http://media.mtvnservices.com/{mgid}
145             og_url = self._og_search_video_url(webpage)
146             mgid = url_basename(og_url)
147             if mgid.endswith('.swf'):
148                 mgid = mgid[:-4]
149         except RegexNotFoundError:
150             mgid = self._search_regex(
151                 [r'data-mgid="(.*?)"', r'swfobject.embedSWF\(".*?(mgid:.*?)"'],
152                 webpage, u'mgid')
153         return self._get_videos_info(mgid)
154
155
156 class MTVIE(MTVServicesInfoExtractor):
157     _VALID_URL = r'''(?x)^https?://
158         (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
159            m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
160
161     _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
162
163     _TESTS = [
164         {
165             'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
166             'file': '853555.mp4',
167             'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
168             'info_dict': {
169                 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
170                 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
171             },
172         },
173         {
174             'add_ie': ['Vevo'],
175             'url': 'http://www.mtv.com/videos/taylor-swift/916187/everything-has-changed-ft-ed-sheeran.jhtml',
176             'file': 'USCJY1331283.mp4',
177             'md5': '73b4e7fcadd88929292fe52c3ced8caf',
178             'info_dict': {
179                 'title': 'Everything Has Changed',
180                 'upload_date': '20130606',
181                 'uploader': 'Taylor Swift',
182             },
183             'skip': 'VEVO is only available in some countries',
184         },
185     ]
186
187     def _get_thumbnail_url(self, uri, itemdoc):
188         return 'http://mtv.mtvnimages.com/uri/' + uri
189
190     def _real_extract(self, url):
191         mobj = re.match(self._VALID_URL, url)
192         video_id = mobj.group('videoid')
193         uri = mobj.groupdict().get('mgid')
194         if uri is None:
195             webpage = self._download_webpage(url, video_id)
196     
197             # Some videos come from Vevo.com
198             m_vevo = re.search(r'isVevoVideo = true;.*?vevoVideoId = "(.*?)";',
199                                webpage, re.DOTALL)
200             if m_vevo:
201                 vevo_id = m_vevo.group(1);
202                 self.to_screen('Vevo video detected: %s' % vevo_id)
203                 return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
204     
205             uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
206         return self._get_videos_info(uri)
207
208
209 class MTVIggyIE(MTVServicesInfoExtractor):
210     IE_NAME = 'mtviggy.com'
211     _VALID_URL = r'https?://www\.mtviggy\.com/videos/.+'
212     _TEST = {
213         'url': 'http://www.mtviggy.com/videos/arcade-fire-behind-the-scenes-at-the-biggest-music-experiment-yet/',
214         'info_dict': {
215             'id': '984696',
216             'ext': 'mp4',
217             'title': 'Arcade Fire: Behind the Scenes at the Biggest Music Experiment Yet',
218         }
219     }
220     _FEED_URL = 'http://all.mtvworldverticals.com/feed-xml/'