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