]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/mtv.py
[npo] Convert to new subtitles system
[yt-dlp.git] / youtube_dl / extractor / mtv.py
CommitLineData
32dac694
PH
1from __future__ import unicode_literals
2
fc287219 3import re
fc287219 4
e525d9a3 5from .subtitles import SubtitlesInfoExtractor
1cc79574 6from ..compat import (
f7e02595 7 compat_urllib_parse,
340b0468 8 compat_urllib_request,
e525d9a3 9 compat_str,
1cc79574
PH
10)
11from ..utils import (
fc287219 12 ExtractorError,
90834c78 13 find_xpath_attr,
5aafe895 14 fix_xml_ampersands,
0ef68e04 15 HEADRequest,
340b0468 16 unescapeHTML,
8d9453b9
JMF
17 url_basename,
18 RegexNotFoundError,
fc287219
PH
19)
20
90834c78 21
300fcad8
JMF
22def _media_xml_tag(tag):
23 return '{http://search.yahoo.com/mrss/}%s' % tag
fc287219 24
f7e02595 25
e525d9a3 26class MTVServicesInfoExtractor(SubtitlesInfoExtractor):
340b0468 27 _MOBILE_TEMPLATE = None
8940c1c0 28
f7e02595
JMF
29 @staticmethod
30 def _id_from_uri(uri):
31 return uri.split(':')[-1]
32
33 # This was originally implemented for ComedyCentral, but it also works here
34 @staticmethod
35 def _transform_rtmp_url(rtmp_video_url):
36 m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp\..+?/.*)$', rtmp_video_url)
37 if not m:
63b7b722 38 return rtmp_video_url
2774852c 39 base = 'http://viacommtvstrmfs.fplive.net/'
ab2f744b
JMF
40 return base + m.group('finalid')
41
8940c1c0
JMF
42 def _get_feed_url(self, uri):
43 return self._FEED_URL
44
ab2f744b 45 def _get_thumbnail_url(self, uri, itemdoc):
84db8181
JMF
46 search_path = '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail'))
47 thumb_node = itemdoc.find(search_path)
48 if thumb_node is None:
49 return None
50 else:
51 return thumb_node.attrib['url']
f7e02595 52
340b0468
JMF
53 def _extract_mobile_video_formats(self, mtvn_id):
54 webpage_url = self._MOBILE_TEMPLATE % mtvn_id
55 req = compat_urllib_request.Request(webpage_url)
56 # Otherwise we get a webpage that would execute some javascript
3fcfb8e9 57 req.add_header('User-Agent', 'curl/7')
340b0468 58 webpage = self._download_webpage(req, mtvn_id,
9e1a5b84 59 'Downloading mobile page')
0ef68e04
JMF
60 metrics_url = unescapeHTML(self._search_regex(r'<a href="(http://metrics.+?)"', webpage, 'url'))
61 req = HEADRequest(metrics_url)
62 response = self._request_webpage(req, mtvn_id, 'Resolving url')
63 url = response.geturl()
64 # Transform the url to get the best quality:
65 url = re.sub(r'.+pxE=mp4', 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=0+_pxK=18639+_pxE=mp4', url, 1)
5f6a1245 66 return [{'url': url, 'ext': 'mp4'}]
340b0468
JMF
67
68 def _extract_video_formats(self, mdoc, mtvn_id):
cc1db7f9 69 if re.match(r'.*/(error_country_block\.swf|geoblock\.mp4)$', mdoc.find('.//src').text) is not None:
340b0468 70 if mtvn_id is not None and self._MOBILE_TEMPLATE is not None:
0ef68e04 71 self.to_screen('The normal version is not available from your '
9e1a5b84 72 'country, trying with the mobile version')
340b0468 73 return self._extract_mobile_video_formats(mtvn_id)
cc1db7f9 74 raise ExtractorError('This video is not available from your country.',
9e1a5b84 75 expected=True)
f7e02595 76
f13d0933
PH
77 formats = []
78 for rendition in mdoc.findall('.//rendition'):
79 try:
80 _, _, ext = rendition.attrib['type'].partition('/')
81 rtmp_video_url = rendition.find('./src').text
ca0f500e
PH
82 if rtmp_video_url.endswith('siteunavail.png'):
83 continue
84 formats.append({
85 'ext': ext,
86 'url': self._transform_rtmp_url(rtmp_video_url),
87 'format_id': rendition.get('bitrate'),
88 'width': int(rendition.get('width')),
89 'height': int(rendition.get('height')),
90 })
f13d0933
PH
91 except (KeyError, TypeError):
92 raise ExtractorError('Invalid rendition field.')
34d863f3 93 self._sort_formats(formats)
f13d0933 94 return formats
f7e02595 95
e525d9a3
S
96 def _extract_subtitles(self, mdoc, mtvn_id):
97 subtitles = {}
98 FORMATS = {
99 'scc': 'cea-608',
100 'eia-608': 'cea-608',
101 'xml': 'ttml',
102 }
103 subtitles_format = FORMATS.get(
104 self._downloader.params.get('subtitlesformat'), 'ttml')
105 for transcript in mdoc.findall('.//transcript'):
106 if transcript.get('kind') != 'captions':
107 continue
108 lang = transcript.get('srclang')
109 for typographic in transcript.findall('./typographic'):
110 captions_format = typographic.get('format')
111 if captions_format == subtitles_format:
112 subtitles[lang] = compat_str(typographic.get('src'))
113 break
114 if self._downloader.params.get('listsubtitles', False):
115 self._list_available_subtitles(mtvn_id, subtitles)
116 return self.extract_subtitles(mtvn_id, subtitles)
117
f7e02595
JMF
118 def _get_video_info(self, itemdoc):
119 uri = itemdoc.find('guid').text
120 video_id = self._id_from_uri(uri)
121 self.report_extraction(video_id)
300fcad8 122 mediagen_url = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content'))).attrib['url']
321a01f9 123 # Remove the templates, like &device={device}
32dac694 124 mediagen_url = re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', mediagen_url)
f7e02595
JMF
125 if 'acceptMethods' not in mediagen_url:
126 mediagen_url += '&acceptMethods=fms'
6562df76 127
e4f320a4 128 mediagen_doc = self._download_xml(mediagen_url, video_id,
9e1a5b84 129 'Downloading video urls')
f7e02595
JMF
130
131 description_node = itemdoc.find('description')
132 if description_node is not None:
0ab4ff63 133 description = description_node.text.strip()
f7e02595
JMF
134 else:
135 description = None
f13d0933 136
90834c78
PH
137 title_el = None
138 if title_el is None:
139 title_el = find_xpath_attr(
140 itemdoc, './/{http://search.yahoo.com/mrss/}category',
141 'scheme', 'urn:mtvn:video_title')
90834c78 142 if title_el is None:
96cb10a5
S
143 title_el = itemdoc.find('.//{http://search.yahoo.com/mrss/}title')
144 if title_el is None:
713d31fa 145 title_el = itemdoc.find('.//title')
1df4229b
PH
146 if title_el.text is None:
147 title_el = None
1df4229b 148
90834c78
PH
149 title = title_el.text
150 if title is None:
151 raise ExtractorError('Could not find video title')
780ee4e5 152 title = title.strip()
90834c78 153
340b0468
JMF
154 # This a short id that's used in the webpage urls
155 mtvn_id = None
156 mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
9e1a5b84 157 'scheme', 'urn:mtvn:id')
340b0468
JMF
158 if mtvn_id_node is not None:
159 mtvn_id = mtvn_id_node.text
160
fb7abb31 161 return {
90834c78 162 'title': title,
340b0468 163 'formats': self._extract_video_formats(mediagen_doc, mtvn_id),
e525d9a3 164 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
f13d0933
PH
165 'id': video_id,
166 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
167 'description': description,
168 }
169
f7e02595
JMF
170 def _get_videos_info(self, uri):
171 video_id = self._id_from_uri(uri)
8940c1c0 172 feed_url = self._get_feed_url(uri)
f7e02595 173 data = compat_urllib_parse.urlencode({'uri': uri})
e2b38da9 174 idoc = self._download_xml(
8940c1c0 175 feed_url + '?' + data, video_id,
32dac694 176 'Downloading info', transform_source=fix_xml_ampersands)
5239075b
PH
177 return self.playlist_result(
178 [self._get_video_info(item) for item in idoc.findall('.//item')])
fc287219 179
8d9453b9
JMF
180 def _real_extract(self, url):
181 title = url_basename(url)
182 webpage = self._download_webpage(url, title)
183 try:
4bbf139a
JMF
184 # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
185 # or http://media.mtvnservices.com/{mgid}
186 og_url = self._og_search_video_url(webpage)
187 mgid = url_basename(og_url)
188 if mgid.endswith('.swf'):
189 mgid = mgid[:-4]
8d9453b9 190 except RegexNotFoundError:
b1298d8e
AMW
191 mgid = None
192
193 if mgid is None or ':' not in mgid:
b9381e43
JMF
194 mgid = self._search_regex(
195 [r'data-mgid="(.*?)"', r'swfobject.embedSWF\(".*?(mgid:.*?)"'],
8865bdeb 196 webpage, 'mgid')
e525d9a3
S
197
198 videos_info = self._get_videos_info(mgid)
199 if self._downloader.params.get('listsubtitles', False):
200 return
201 return videos_info
8d9453b9 202
84db8181 203
8940c1c0
JMF
204class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
205 IE_NAME = 'mtvservices:embedded'
206 _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
207
208 _TEST = {
209 # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
210 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
211 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
212 'info_dict': {
213 'id': '1043906',
214 'ext': 'mp4',
215 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
216 'description': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage as he tries summarizing "Game of Thrones" in under a minute.',
217 },
218 }
219
220 def _get_feed_url(self, uri):
221 video_id = self._id_from_uri(uri)
222 site_id = uri.replace(video_id, '')
71f8c7ce 223 config_url = ('http://media.mtvnservices.com/pmt/e1/players/{0}/'
9e1a5b84 224 'context4/context5/config.xml'.format(site_id))
8940c1c0
JMF
225 config_doc = self._download_xml(config_url, video_id)
226 feed_node = config_doc.find('.//feed')
227 feed_url = feed_node.text.strip().split('?')[0]
228 return feed_url
229
230 def _real_extract(self, url):
231 mobj = re.match(self._VALID_URL, url)
232 mgid = mobj.group('mgid')
233 return self._get_videos_info(mgid)
234
235
84db8181 236class MTVIE(MTVServicesInfoExtractor):
5c541b2c
JMF
237 _VALID_URL = r'''(?x)^https?://
238 (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
239 m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
84db8181
JMF
240
241 _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
242
243 _TESTS = [
244 {
32dac694 245 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
32dac694
PH
246 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
247 'info_dict': {
ca0f500e
PH
248 'id': '853555',
249 'ext': 'mp4',
32dac694
PH
250 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
251 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
84db8181
JMF
252 },
253 },
84db8181
JMF
254 ]
255
256 def _get_thumbnail_url(self, uri, itemdoc):
257 return 'http://mtv.mtvnimages.com/uri/' + uri
258
fc287219
PH
259 def _real_extract(self, url):
260 mobj = re.match(self._VALID_URL, url)
fc287219 261 video_id = mobj.group('videoid')
c801b205 262 uri = mobj.groupdict().get('mgid')
5c541b2c
JMF
263 if uri is None:
264 webpage = self._download_webpage(url, video_id)
5f6a1245 265
5c541b2c 266 # Some videos come from Vevo.com
ca0f500e
PH
267 m_vevo = re.search(
268 r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
5c541b2c 269 if m_vevo:
8bcc8756 270 vevo_id = m_vevo.group(1)
32dac694 271 self.to_screen('Vevo video detected: %s' % vevo_id)
5c541b2c 272 return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
5f6a1245 273
32dac694 274 uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
f7e02595 275 return self._get_videos_info(uri)
bc4ba05f
JMF
276
277
278class MTVIggyIE(MTVServicesInfoExtractor):
279 IE_NAME = 'mtviggy.com'
280 _VALID_URL = r'https?://www\.mtviggy\.com/videos/.+'
281 _TEST = {
282 'url': 'http://www.mtviggy.com/videos/arcade-fire-behind-the-scenes-at-the-biggest-music-experiment-yet/',
283 'info_dict': {
284 'id': '984696',
285 'ext': 'mp4',
af1588c0 286 'title': 'Arcade Fire: Behind the Scenes at the Biggest Music Experiment Yet',
bc4ba05f
JMF
287 }
288 }
289 _FEED_URL = 'http://all.mtvworldverticals.com/feed-xml/'