]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/mtv.py
debian/changelog: Initiate new release.
[youtubedl] / youtube_dl / extractor / mtv.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from ..compat import (
7 compat_urllib_parse,
8 compat_urllib_request,
9 )
10 from ..utils import (
11 ExtractorError,
12 find_xpath_attr,
13 fix_xml_ampersands,
14 HEADRequest,
15 unescapeHTML,
16 url_basename,
17 RegexNotFoundError,
18 )
19
20
21 def _media_xml_tag(tag):
22 return '{http://search.yahoo.com/mrss/}%s' % tag
23
24
25 class MTVServicesInfoExtractor(InfoExtractor):
26 _MOBILE_TEMPLATE = None
27
28 @staticmethod
29 def _id_from_uri(uri):
30 return uri.split(':')[-1]
31
32 # This was originally implemented for ComedyCentral, but it also works here
33 @staticmethod
34 def _transform_rtmp_url(rtmp_video_url):
35 m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp\..+?/.*)$', rtmp_video_url)
36 if not m:
37 return rtmp_video_url
38 base = 'http://viacommtvstrmfs.fplive.net/'
39 return base + m.group('finalid')
40
41 def _get_feed_url(self, uri):
42 return self._FEED_URL
43
44 def _get_thumbnail_url(self, uri, itemdoc):
45 search_path = '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail'))
46 thumb_node = itemdoc.find(search_path)
47 if thumb_node is None:
48 return None
49 else:
50 return thumb_node.attrib['url']
51
52 def _extract_mobile_video_formats(self, mtvn_id):
53 webpage_url = self._MOBILE_TEMPLATE % mtvn_id
54 req = compat_urllib_request.Request(webpage_url)
55 # Otherwise we get a webpage that would execute some javascript
56 req.add_header('Youtubedl-user-agent', 'curl/7')
57 webpage = self._download_webpage(req, mtvn_id,
58 'Downloading mobile page')
59 metrics_url = unescapeHTML(self._search_regex(r'<a href="(http://metrics.+?)"', webpage, 'url'))
60 req = HEADRequest(metrics_url)
61 response = self._request_webpage(req, mtvn_id, 'Resolving url')
62 url = response.geturl()
63 # Transform the url to get the best quality:
64 url = re.sub(r'.+pxE=mp4', 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=0+_pxK=18639+_pxE=mp4', url, 1)
65 return [{'url': url, 'ext': 'mp4'}]
66
67 def _extract_video_formats(self, mdoc, mtvn_id):
68 if re.match(r'.*/(error_country_block\.swf|geoblock\.mp4)$', mdoc.find('.//src').text) is not None:
69 if mtvn_id is not None and self._MOBILE_TEMPLATE is not None:
70 self.to_screen('The normal version is not available from your '
71 'country, trying with the mobile version')
72 return self._extract_mobile_video_formats(mtvn_id)
73 raise ExtractorError('This video is not available from your country.',
74 expected=True)
75
76 formats = []
77 for rendition in mdoc.findall('.//rendition'):
78 try:
79 _, _, ext = rendition.attrib['type'].partition('/')
80 rtmp_video_url = rendition.find('./src').text
81 formats.append({'ext': ext,
82 'url': self._transform_rtmp_url(rtmp_video_url),
83 'format_id': rendition.get('bitrate'),
84 'width': int(rendition.get('width')),
85 'height': int(rendition.get('height')),
86 })
87 except (KeyError, TypeError):
88 raise ExtractorError('Invalid rendition field.')
89 self._sort_formats(formats)
90 return formats
91
92 def _get_video_info(self, itemdoc):
93 uri = itemdoc.find('guid').text
94 video_id = self._id_from_uri(uri)
95 self.report_extraction(video_id)
96 mediagen_url = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content'))).attrib['url']
97 # Remove the templates, like &device={device}
98 mediagen_url = re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', mediagen_url)
99 if 'acceptMethods' not in mediagen_url:
100 mediagen_url += '&acceptMethods=fms'
101
102 mediagen_doc = self._download_xml(mediagen_url, video_id,
103 'Downloading video urls')
104
105 description_node = itemdoc.find('description')
106 if description_node is not None:
107 description = description_node.text.strip()
108 else:
109 description = None
110
111 title_el = None
112 if title_el is None:
113 title_el = find_xpath_attr(
114 itemdoc, './/{http://search.yahoo.com/mrss/}category',
115 'scheme', 'urn:mtvn:video_title')
116 if title_el is None:
117 title_el = itemdoc.find('.//{http://search.yahoo.com/mrss/}title')
118 if title_el is None:
119 title_el = itemdoc.find('.//title')
120 if title_el.text is None:
121 title_el = None
122
123 title = title_el.text
124 if title is None:
125 raise ExtractorError('Could not find video title')
126 title = title.strip()
127
128 # This a short id that's used in the webpage urls
129 mtvn_id = None
130 mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
131 'scheme', 'urn:mtvn:id')
132 if mtvn_id_node is not None:
133 mtvn_id = mtvn_id_node.text
134
135 return {
136 'title': title,
137 'formats': self._extract_video_formats(mediagen_doc, mtvn_id),
138 'id': video_id,
139 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
140 'description': description,
141 }
142
143 def _get_videos_info(self, uri):
144 video_id = self._id_from_uri(uri)
145 feed_url = self._get_feed_url(uri)
146 data = compat_urllib_parse.urlencode({'uri': uri})
147 idoc = self._download_xml(
148 feed_url + '?' + data, video_id,
149 'Downloading info', transform_source=fix_xml_ampersands)
150 return self.playlist_result(
151 [self._get_video_info(item) for item in idoc.findall('.//item')])
152
153 def _real_extract(self, url):
154 title = url_basename(url)
155 webpage = self._download_webpage(url, title)
156 try:
157 # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
158 # or http://media.mtvnservices.com/{mgid}
159 og_url = self._og_search_video_url(webpage)
160 mgid = url_basename(og_url)
161 if mgid.endswith('.swf'):
162 mgid = mgid[:-4]
163 except RegexNotFoundError:
164 mgid = None
165
166 if mgid is None or ':' not in mgid:
167 mgid = self._search_regex(
168 [r'data-mgid="(.*?)"', r'swfobject.embedSWF\(".*?(mgid:.*?)"'],
169 webpage, 'mgid')
170 return self._get_videos_info(mgid)
171
172
173 class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
174 IE_NAME = 'mtvservices:embedded'
175 _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
176
177 _TEST = {
178 # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
179 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
180 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
181 'info_dict': {
182 'id': '1043906',
183 'ext': 'mp4',
184 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
185 'description': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage as he tries summarizing "Game of Thrones" in under a minute.',
186 },
187 }
188
189 def _get_feed_url(self, uri):
190 video_id = self._id_from_uri(uri)
191 site_id = uri.replace(video_id, '')
192 config_url = ('http://media.mtvnservices.com/pmt/e1/players/{0}/'
193 'context4/context5/config.xml'.format(site_id))
194 config_doc = self._download_xml(config_url, video_id)
195 feed_node = config_doc.find('.//feed')
196 feed_url = feed_node.text.strip().split('?')[0]
197 return feed_url
198
199 def _real_extract(self, url):
200 mobj = re.match(self._VALID_URL, url)
201 mgid = mobj.group('mgid')
202 return self._get_videos_info(mgid)
203
204
205 class MTVIE(MTVServicesInfoExtractor):
206 _VALID_URL = r'''(?x)^https?://
207 (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
208 m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
209
210 _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
211
212 _TESTS = [
213 {
214 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
215 'file': '853555.mp4',
216 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
217 'info_dict': {
218 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
219 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
220 },
221 },
222 {
223 'add_ie': ['Vevo'],
224 'url': 'http://www.mtv.com/videos/taylor-swift/916187/everything-has-changed-ft-ed-sheeran.jhtml',
225 'file': 'USCJY1331283.mp4',
226 'md5': '73b4e7fcadd88929292fe52c3ced8caf',
227 'info_dict': {
228 'title': 'Everything Has Changed',
229 'upload_date': '20130606',
230 'uploader': 'Taylor Swift',
231 },
232 'skip': 'VEVO is only available in some countries',
233 },
234 ]
235
236 def _get_thumbnail_url(self, uri, itemdoc):
237 return 'http://mtv.mtvnimages.com/uri/' + uri
238
239 def _real_extract(self, url):
240 mobj = re.match(self._VALID_URL, url)
241 video_id = mobj.group('videoid')
242 uri = mobj.groupdict().get('mgid')
243 if uri is None:
244 webpage = self._download_webpage(url, video_id)
245
246 # Some videos come from Vevo.com
247 m_vevo = re.search(r'isVevoVideo = true;.*?vevoVideoId = "(.*?)";',
248 webpage, re.DOTALL)
249 if m_vevo:
250 vevo_id = m_vevo.group(1)
251 self.to_screen('Vevo video detected: %s' % vevo_id)
252 return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
253
254 uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
255 return self._get_videos_info(uri)
256
257
258 class MTVIggyIE(MTVServicesInfoExtractor):
259 IE_NAME = 'mtviggy.com'
260 _VALID_URL = r'https?://www\.mtviggy\.com/videos/.+'
261 _TEST = {
262 'url': 'http://www.mtviggy.com/videos/arcade-fire-behind-the-scenes-at-the-biggest-music-experiment-yet/',
263 'info_dict': {
264 'id': '984696',
265 'ext': 'mp4',
266 'title': 'Arcade Fire: Behind the Scenes at the Biggest Music Experiment Yet',
267 }
268 }
269 _FEED_URL = 'http://all.mtvworldverticals.com/feed-xml/'