]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/mtv.py
[spike] Improve _VALID_URL
[yt-dlp.git] / youtube_dl / extractor / mtv.py
CommitLineData
32dac694
PH
1from __future__ import unicode_literals
2
fc287219 3import re
fc287219
PH
4
5from .common import InfoExtractor
1cc79574 6from ..compat import (
f7e02595 7 compat_urllib_parse,
340b0468 8 compat_urllib_request,
1cc79574
PH
9)
10from ..utils import (
fc287219 11 ExtractorError,
90834c78 12 find_xpath_attr,
5aafe895 13 fix_xml_ampersands,
0ef68e04 14 HEADRequest,
340b0468 15 unescapeHTML,
8d9453b9
JMF
16 url_basename,
17 RegexNotFoundError,
fc287219
PH
18)
19
90834c78 20
300fcad8
JMF
21def _media_xml_tag(tag):
22 return '{http://search.yahoo.com/mrss/}%s' % tag
fc287219 23
f7e02595 24
84db8181 25class MTVServicesInfoExtractor(InfoExtractor):
340b0468 26 _MOBILE_TEMPLATE = None
8940c1c0 27
f7e02595
JMF
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:
63b7b722 37 return rtmp_video_url
2774852c 38 base = 'http://viacommtvstrmfs.fplive.net/'
ab2f744b
JMF
39 return base + m.group('finalid')
40
8940c1c0
JMF
41 def _get_feed_url(self, uri):
42 return self._FEED_URL
43
ab2f744b 44 def _get_thumbnail_url(self, uri, itemdoc):
84db8181
JMF
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']
f7e02595 51
340b0468
JMF
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
3fcfb8e9 56 req.add_header('User-Agent', 'curl/7')
340b0468 57 webpage = self._download_webpage(req, mtvn_id,
9e1a5b84 58 'Downloading mobile page')
0ef68e04
JMF
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)
5f6a1245 65 return [{'url': url, 'ext': 'mp4'}]
340b0468
JMF
66
67 def _extract_video_formats(self, mdoc, mtvn_id):
cc1db7f9 68 if re.match(r'.*/(error_country_block\.swf|geoblock\.mp4)$', mdoc.find('.//src').text) is not None:
340b0468 69 if mtvn_id is not None and self._MOBILE_TEMPLATE is not None:
0ef68e04 70 self.to_screen('The normal version is not available from your '
9e1a5b84 71 'country, trying with the mobile version')
340b0468 72 return self._extract_mobile_video_formats(mtvn_id)
cc1db7f9 73 raise ExtractorError('This video is not available from your country.',
9e1a5b84 74 expected=True)
f7e02595 75
f13d0933
PH
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.')
34d863f3 89 self._sort_formats(formats)
f13d0933 90 return formats
f7e02595
JMF
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)
300fcad8 96 mediagen_url = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content'))).attrib['url']
321a01f9 97 # Remove the templates, like &device={device}
32dac694 98 mediagen_url = re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', mediagen_url)
f7e02595
JMF
99 if 'acceptMethods' not in mediagen_url:
100 mediagen_url += '&acceptMethods=fms'
6562df76 101
e4f320a4 102 mediagen_doc = self._download_xml(mediagen_url, video_id,
9e1a5b84 103 'Downloading video urls')
f7e02595
JMF
104
105 description_node = itemdoc.find('description')
106 if description_node is not None:
0ab4ff63 107 description = description_node.text.strip()
f7e02595
JMF
108 else:
109 description = None
f13d0933 110
90834c78
PH
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')
90834c78 116 if title_el is None:
96cb10a5
S
117 title_el = itemdoc.find('.//{http://search.yahoo.com/mrss/}title')
118 if title_el is None:
713d31fa 119 title_el = itemdoc.find('.//title')
1df4229b
PH
120 if title_el.text is None:
121 title_el = None
1df4229b 122
90834c78
PH
123 title = title_el.text
124 if title is None:
125 raise ExtractorError('Could not find video title')
780ee4e5 126 title = title.strip()
90834c78 127
340b0468
JMF
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',
9e1a5b84 131 'scheme', 'urn:mtvn:id')
340b0468
JMF
132 if mtvn_id_node is not None:
133 mtvn_id = mtvn_id_node.text
134
fb7abb31 135 return {
90834c78 136 'title': title,
340b0468 137 'formats': self._extract_video_formats(mediagen_doc, mtvn_id),
f13d0933
PH
138 'id': video_id,
139 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
140 'description': description,
141 }
142
f7e02595
JMF
143 def _get_videos_info(self, uri):
144 video_id = self._id_from_uri(uri)
8940c1c0 145 feed_url = self._get_feed_url(uri)
f7e02595 146 data = compat_urllib_parse.urlencode({'uri': uri})
e2b38da9 147 idoc = self._download_xml(
8940c1c0 148 feed_url + '?' + data, video_id,
32dac694 149 'Downloading info', transform_source=fix_xml_ampersands)
5239075b
PH
150 return self.playlist_result(
151 [self._get_video_info(item) for item in idoc.findall('.//item')])
fc287219 152
8d9453b9
JMF
153 def _real_extract(self, url):
154 title = url_basename(url)
155 webpage = self._download_webpage(url, title)
156 try:
4bbf139a
JMF
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]
8d9453b9 163 except RegexNotFoundError:
b1298d8e
AMW
164 mgid = None
165
166 if mgid is None or ':' not in mgid:
b9381e43
JMF
167 mgid = self._search_regex(
168 [r'data-mgid="(.*?)"', r'swfobject.embedSWF\(".*?(mgid:.*?)"'],
8865bdeb 169 webpage, 'mgid')
8d9453b9
JMF
170 return self._get_videos_info(mgid)
171
84db8181 172
8940c1c0
JMF
173class 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, '')
71f8c7ce 192 config_url = ('http://media.mtvnservices.com/pmt/e1/players/{0}/'
9e1a5b84 193 'context4/context5/config.xml'.format(site_id))
8940c1c0
JMF
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
84db8181 205class MTVIE(MTVServicesInfoExtractor):
5c541b2c
JMF
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>[^&]+))'''
84db8181
JMF
209
210 _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
211
212 _TESTS = [
213 {
32dac694
PH
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.',
84db8181
JMF
220 },
221 },
222 {
32dac694
PH
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',
84db8181 231 },
32dac694 232 'skip': 'VEVO is only available in some countries',
84db8181
JMF
233 },
234 ]
235
236 def _get_thumbnail_url(self, uri, itemdoc):
237 return 'http://mtv.mtvnimages.com/uri/' + uri
238
fc287219
PH
239 def _real_extract(self, url):
240 mobj = re.match(self._VALID_URL, url)
fc287219 241 video_id = mobj.group('videoid')
c801b205 242 uri = mobj.groupdict().get('mgid')
5c541b2c
JMF
243 if uri is None:
244 webpage = self._download_webpage(url, video_id)
5f6a1245 245
5c541b2c
JMF
246 # Some videos come from Vevo.com
247 m_vevo = re.search(r'isVevoVideo = true;.*?vevoVideoId = "(.*?)";',
248 webpage, re.DOTALL)
249 if m_vevo:
8bcc8756 250 vevo_id = m_vevo.group(1)
32dac694 251 self.to_screen('Vevo video detected: %s' % vevo_id)
5c541b2c 252 return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
5f6a1245 253
32dac694 254 uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
f7e02595 255 return self._get_videos_info(uri)
bc4ba05f
JMF
256
257
258class 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',
af1588c0 266 'title': 'Arcade Fire: Behind the Scenes at the Biggest Music Experiment Yet',
bc4ba05f
JMF
267 }
268 }
269 _FEED_URL = 'http://all.mtvworldverticals.com/feed-xml/'