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