2 from __future__
import unicode_literals
6 from .common
import InfoExtractor
31 def _media_xml_tag(tag
):
32 return '{http://search.yahoo.com/mrss/}%s' % tag
35 class MTVServicesInfoExtractor(InfoExtractor
):
36 _MOBILE_TEMPLATE
= None
40 def _id_from_uri(uri
):
41 return uri
.split(':')[-1]
44 def _remove_template_parameter(url
):
45 # Remove the templates, like &device={device}
46 return re
.sub(r
'&[^=]*?={.*?}(?=(&|$))', '', url
)
48 def _get_feed_url(self
, uri
, url
=None):
51 def _get_thumbnail_url(self
, uri
, itemdoc
):
52 search_path
= '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail'))
53 thumb_node
= itemdoc
.find(search_path
)
54 if thumb_node
is None:
56 return thumb_node
.get('url') or thumb_node
.text
or None
58 def _extract_mobile_video_formats(self
, mtvn_id
):
59 webpage_url
= self
._MOBILE
_TEMPLATE
% mtvn_id
60 req
= sanitized_Request(webpage_url
)
61 # Otherwise we get a webpage that would execute some javascript
62 req
.add_header('User-Agent', 'curl/7')
63 webpage
= self
._download
_webpage
(req
, mtvn_id
,
64 'Downloading mobile page')
65 metrics_url
= unescapeHTML(self
._search
_regex
(r
'<a href="(http://metrics.+?)"', webpage
, 'url'))
66 req
= HEADRequest(metrics_url
)
67 response
= self
._request
_webpage
(req
, mtvn_id
, 'Resolving url')
68 url
= response
.geturl()
69 # Transform the url to get the best quality:
70 url
= re
.sub(r
'.+pxE=mp4', 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=0+_pxK=18639+_pxE=mp4', url
, 1)
71 return [{'url': url, 'ext': 'mp4'}
]
73 def _extract_video_formats(self
, mdoc
, mtvn_id
, video_id
):
74 if re
.match(r
'.*/(error_country_block\.swf|geoblock\.mp4|copyright_error\.flv(?:\?geo\b.+?)?)$', mdoc
.find('.//src').text
) is not None:
75 if mtvn_id
is not None and self
._MOBILE
_TEMPLATE
is not None:
76 self
.to_screen('The normal version is not available from your '
77 'country, trying with the mobile version')
78 return self
._extract
_mobile
_video
_formats
(mtvn_id
)
79 raise ExtractorError('This video is not available from your country.',
83 for rendition
in mdoc
.findall('.//rendition'):
84 if rendition
.get('method') == 'hls':
85 hls_url
= rendition
.find('./src').text
86 formats
.extend(self
._extract
_m
3u8_formats
(
87 hls_url
, video_id
, ext
='mp4', entry_protocol
='m3u8_native',
88 m3u8_id
='hls', fatal
=False))
92 _
, _
, ext
= rendition
.attrib
['type'].partition('/')
93 rtmp_video_url
= rendition
.find('./src').text
94 if 'error_not_available.swf' in rtmp_video_url
:
96 '%s said: video is not available' % self
.IE_NAME
,
98 if rtmp_video_url
.endswith('siteunavail.png'):
101 'ext': 'flv' if rtmp_video_url
.startswith('rtmp') else ext
,
102 'url': rtmp_video_url
,
103 'format_id': '-'.join(filter(None, [
104 'rtmp' if rtmp_video_url
.startswith('rtmp') else None,
105 rendition
.get('bitrate')])),
106 'width': int(rendition
.get('width')),
107 'height': int(rendition
.get('height')),
109 except (KeyError, TypeError):
110 raise ExtractorError('Invalid rendition field.')
112 self
._sort
_formats
(formats
)
115 def _extract_subtitles(self
, mdoc
, mtvn_id
):
117 for transcript
in mdoc
.findall('.//transcript'):
118 if transcript
.get('kind') != 'captions':
120 lang
= transcript
.get('srclang')
121 for typographic
in transcript
.findall('./typographic'):
122 sub_src
= typographic
.get('src')
125 ext
= typographic
.get('format')
128 subtitles
.setdefault(lang
, []).append({
129 'url': compat_str(sub_src
),
134 def _get_video_info(self
, itemdoc
, use_hls
=True):
135 uri
= itemdoc
.find('guid').text
136 video_id
= self
._id
_from
_uri
(uri
)
137 self
.report_extraction(video_id
)
138 content_el
= itemdoc
.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content')))
139 mediagen_url
= self
._remove
_template
_parameter
(content_el
.attrib
['url'])
140 mediagen_url
= mediagen_url
.replace('device={device}', '')
141 if 'acceptMethods' not in mediagen_url
:
142 mediagen_url
+= '&' if '?' in mediagen_url
else '?'
143 mediagen_url
+= 'acceptMethods='
144 mediagen_url
+= 'hls' if use_hls
else 'fms'
146 mediagen_doc
= self
._download
_xml
(
147 mediagen_url
, video_id
, 'Downloading video urls', fatal
=False)
149 if mediagen_doc
is False:
152 item
= mediagen_doc
.find('./video/item')
153 if item
is not None and item
.get('type') == 'text':
154 message
= '%s returned error: ' % self
.IE_NAME
155 if item
.get('code') is not None:
156 message
+= '%s - ' % item
.get('code')
158 raise ExtractorError(message
, expected
=True)
160 description
= strip_or_none(xpath_text(itemdoc
, 'description'))
162 timestamp
= timeconvert(xpath_text(itemdoc
, 'pubDate'))
166 title_el
= find_xpath_attr(
167 itemdoc
, './/{http://search.yahoo.com/mrss/}category',
168 'scheme', 'urn:mtvn:video_title')
170 title_el
= itemdoc
.find(compat_xpath('.//{http://search.yahoo.com/mrss/}title'))
172 title_el
= itemdoc
.find(compat_xpath('.//title'))
173 if title_el
.text
is None:
176 title
= title_el
.text
178 raise ExtractorError('Could not find video title')
179 title
= title
.strip()
181 # This a short id that's used in the webpage urls
183 mtvn_id_node
= find_xpath_attr(itemdoc
, './/{http://search.yahoo.com/mrss/}category',
184 'scheme', 'urn:mtvn:id')
185 if mtvn_id_node
is not None:
186 mtvn_id
= mtvn_id_node
.text
188 formats
= self
._extract
_video
_formats
(mediagen_doc
, mtvn_id
, video_id
)
190 # Some parts of complete video may be missing (e.g. missing Act 3 in
191 # http://www.southpark.de/alle-episoden/s14e01-sexual-healing)
195 self
._sort
_formats
(formats
)
200 'subtitles': self
._extract
_subtitles
(mediagen_doc
, mtvn_id
),
202 'thumbnail': self
._get
_thumbnail
_url
(uri
, itemdoc
),
203 'description': description
,
204 'duration': float_or_none(content_el
.attrib
.get('duration')),
205 'timestamp': timestamp
,
208 def _get_feed_query(self
, uri
):
211 data
['lang'] = self
._LANG
214 def _get_videos_info(self
, uri
, use_hls
=True, url
=None):
215 video_id
= self
._id
_from
_uri
(uri
)
216 feed_url
= self
._get
_feed
_url
(uri
, url
)
217 info_url
= update_url_query(feed_url
, self
._get
_feed
_query
(uri
))
218 return self
._get
_videos
_info
_from
_url
(info_url
, video_id
, use_hls
)
220 def _get_videos_info_from_url(self
, url
, video_id
, use_hls
=True):
221 idoc
= self
._download
_xml
(
223 'Downloading info', transform_source
=fix_xml_ampersands
)
225 title
= xpath_text(idoc
, './channel/title')
226 description
= xpath_text(idoc
, './channel/description')
229 for item
in idoc
.findall('.//item'):
230 info
= self
._get
_video
_info
(item
, use_hls
)
234 return self
.playlist_result(
235 entries
, playlist_title
=title
, playlist_description
=description
)
237 def _extract_triforce_mgid(self
, webpage
, data_zone
=None, video_id
=None):
238 triforce_feed
= self
._parse
_json
(self
._search
_regex
(
239 r
'triforceManifestFeed\s*=\s*({.+?})\s*;\s*\n', webpage
,
240 'triforce feed', default
='{}'), video_id
, fatal
=False)
242 data_zone
= self
._search
_regex
(
243 r
'data-zone=(["\'])(?P
<zone
>.+?_lc_promo
.*?
)\
1', webpage,
244 'data zone
', default=data_zone, group='zone
')
247 triforce_feed, lambda x: x['manifest
']['zones
'][data_zone]['feed
'],
252 feed = self._download_json(feed_url, video_id, fatal=False)
256 return try_get(feed, lambda x: x['result
']['data
']['id'], compat_str)
258 def _extract_new_triforce_mgid(self, webpage, url='', video_id=None):
261 domain = get_domain(url)
263 raise ExtractorError(
264 '[%s] could
not get domain
' % self.IE_NAME,
266 url = url.replace("https://", "http://")
267 enc_url = compat_urlparse.quote(url, safe='')
268 _TRIFORCE_V8_TEMPLATE = 'https
://%s/feeds
/triforce
/manifest
/v8?url
=%s'
269 triforce_manifest_url = _TRIFORCE_V8_TEMPLATE % (domain, enc_url)
271 manifest = self._download_json(triforce_manifest_url, video_id, fatal=False)
273 if manifest.get('manifest
').get('type') == 'redirect
':
274 self.to_screen('Found a redirect
. Downloading manifest
from new location
')
275 new_loc = manifest.get('manifest
').get('newLocation
')
276 new_loc = new_loc.replace("https://", "http://")
277 enc_new_loc = compat_urlparse.quote(new_loc, safe='')
278 triforce_manifest_new_loc = _TRIFORCE_V8_TEMPLATE % (domain, enc_new_loc)
279 manifest = self._download_json(triforce_manifest_new_loc, video_id, fatal=False)
281 item_id = try_get(manifest, lambda x: x['manifest
']['reporting
']['itemId
'], compat_str)
283 self.to_screen('No
id found
!')
286 # 'episode
' can be anything. 'content
' is used often as well
287 _MGID_TEMPLATE = 'mgid
:arc
:episode
:%s:%s'
288 mgid = _MGID_TEMPLATE % (domain, item_id)
292 def _extract_mgid(self, webpage, url, title=None, data_zone=None):
294 # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
295 # or http://media.mtvnservices.com/{mgid}
296 og_url = self._og_search_video_url(webpage)
297 mgid = url_basename(og_url)
298 if mgid.endswith('.swf
'):
300 except RegexNotFoundError:
304 title = url_basename(url)
307 window_data = self._parse_json(self._search_regex(
308 r'(?s
)window
.__DATA
__ = (?P
<json
>{.+}
);', webpage,
309 'JSON Window Data
', default=None, fatal=False, group='json
'), title, fatal=False)
310 main_container = None
311 for i in range(len(window_data['children
'])):
312 if window_data['children
'][i]['type'] == 'MainContainer
':
313 main_container = window_data['children
'][i]
314 mgid = main_container['children
'][0]['props
']['media
']['video
']['config
']['uri
']
315 except (KeyError, IndexError, TypeError):
318 if mgid is None or ':' not in mgid:
319 mgid = self._search_regex(
320 [r'data
-mgid
="(.*?)"', r'swfobject\
.embedSWF\
(".*?(mgid:.*?)"'],
321 webpage, 'mgid
', default=None)
324 sm4_embed = self._html_search_meta(
325 'sm4
:video
:embed
', webpage, 'sm4 embed
', default='')
326 mgid = self._search_regex(
327 r'embed
/(mgid
:.+?
)["\'&?/]', sm4_embed, 'mgid', default=None)
330 mgid = self._extract_new_triforce_mgid(webpage, url)
333 mgid = self._extract_triforce_mgid(webpage, data_zone)
337 def _real_extract(self, url):
338 title = url_basename(url)
339 webpage = self._download_webpage(url, title)
340 mgid = self._extract_mgid(webpage, url, title=title)
341 videos_info = self._get_videos_info(mgid, url=url)
345 class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
346 IE_NAME = 'mtvservices:embedded'
347 _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
350 # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
351 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
352 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
356 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
357 'description': '"Sexy sexy sexy
, stabby stabby stabby
, beautiful language
," says Peter Dinklage as he tries summarizing "Game of Thrones
" in under a minute.',
358 'timestamp': 1400126400,
359 'upload_date': '20140515',
364 def _extract_url(webpage):
366 r'<iframe[^>]+?src=(["\'])(?P
<url
>(?
:https?
:)?
//media
.mtvnservices
.com
/embed
/.+?
)\
1', webpage)
368 return mobj.group('url
')
370 def _get_feed_url(self, uri):
371 video_id = self._id_from_uri(uri)
372 config = self._download_json(
373 'http
://media
.mtvnservices
.com
/pmt
/e1
/access
/index
.html?uri
=%s&configtype
=edge
' % uri, video_id)
374 return self._remove_template_parameter(config['feedWithQueryParams
'])
376 def _real_extract(self, url):
377 mobj = re.match(self._VALID_URL, url)
378 mgid = mobj.group('mgid
')
379 return self._get_videos_info(mgid)
382 class MTVIE(MTVServicesInfoExtractor):
384 _VALID_URL = r'https?
://(?
:www\
.)?mtv\
.com
/(?
:video
-clips|
(?
:full
-)?episodes
)/(?P
<id>[^
/?
#.]+)'
385 _FEED_URL
= 'http://www.mtv.com/feeds/mrss/'
388 'url': 'http://www.mtv.com/video-clips/vl8qof/unlocking-the-truth-trailer',
389 'md5': '1edbcdf1e7628e414a8c5dcebca3d32b',
391 'id': '5e14040d-18a4-47c4-a582-43ff602de88e',
393 'title': 'Unlocking The Truth|July 18, 2016|1|101|Trailer',
394 'description': '"Unlocking the Truth" premieres August 17th at 11/10c.',
395 'timestamp': 1468846800,
396 'upload_date': '20160718',
399 'url': 'http://www.mtv.com/full-episodes/94tujl/unlocking-the-truth-gates-of-hell-season-1-ep-101',
400 'only_matching': True,
402 'url': 'http://www.mtv.com/episodes/g8xu7q/teen-mom-2-breaking-the-wall-season-7-ep-713',
403 'only_matching': True,
407 def extract_child_with_type(parent
, t
):
408 children
= parent
['children']
409 return next(c
for c
in children
if c
.get('type') == t
)
411 def _extract_mgid(self
, webpage
):
412 data
= self
._parse
_json
(self
._search
_regex
(
413 r
'__DATA__\s*=\s*({.+?});', webpage
, 'data'), None)
414 main_container
= self
.extract_child_with_type(data
, 'MainContainer')
415 video_player
= self
.extract_child_with_type(main_container
, 'VideoPlayer')
416 return video_player
['props']['media']['video']['config']['uri']
419 class MTVJapanIE(MTVServicesInfoExtractor
):
421 _VALID_URL
= r
'https?://(?:www\.)?mtvjapan\.com/videos/(?P<id>[0-9a-z]+)'
424 'url': 'http://www.mtvjapan.com/videos/prayht/fresh-info-cadillac-escalade',
426 'id': 'bc01da03-6fe5-4284-8880-f291f4e368f5',
428 'title': '【Fresh Info】Cadillac ESCALADE Sport Edition',
431 'skip_download': True,
434 _GEO_COUNTRIES
= ['JP']
435 _FEED_URL
= 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
437 def _get_feed_query(self
, uri
):
439 'arcEp': 'mtvjapan.com',
444 class MTVVideoIE(MTVServicesInfoExtractor
):
445 IE_NAME
= 'mtv:video'
446 _VALID_URL
= r
'''(?x)^https?://
447 (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
448 m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
450 _FEED_URL
= 'http://www.mtv.com/player/embed/AS3/rss/'
454 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
455 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
459 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
460 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
461 'timestamp': 1352610000,
462 'upload_date': '20121111',
467 def _get_thumbnail_url(self
, uri
, itemdoc
):
468 return 'http://mtv.mtvnimages.com/uri/' + uri
470 def _real_extract(self
, url
):
471 mobj
= re
.match(self
._VALID
_URL
, url
)
472 video_id
= mobj
.group('videoid')
473 uri
= mobj
.groupdict().get('mgid')
475 webpage
= self
._download
_webpage
(url
, video_id
)
477 # Some videos come from Vevo.com
479 r
'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage
)
481 vevo_id
= m_vevo
.group(1)
482 self
.to_screen('Vevo video detected: %s' % vevo_id
)
483 return self
.url_result('vevo:%s' % vevo_id
, ie
='Vevo')
485 uri
= self
._html
_search
_regex
(r
'/uri/(.*?)\?', webpage
, 'uri')
486 return self
._get
_videos
_info
(uri
)
489 class MTVDEIE(MTVServicesInfoExtractor
):
491 _VALID_URL
= r
'https?://(?:www\.)?mtv\.de/(?:musik/videoclips|folgen|news)/(?P<id>[0-9a-z]+)'
493 'url': 'http://www.mtv.de/musik/videoclips/2gpnv7/Traum',
495 'id': 'd5d472bc-f5b7-11e5-bffd-a4badb20dab5',
498 'description': 'Traum',
502 'skip_download': True,
504 'skip': 'Blocked at Travis CI',
506 # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97)
507 'url': 'http://www.mtv.de/folgen/6b1ylu/teen-mom-2-enthuellungen-S5-F1',
509 'id': '1e5a878b-31c5-11e7-a442-0e40cf2fc285',
511 'title': 'Teen Mom 2',
512 'description': 'md5:dc65e357ef7e1085ed53e9e9d83146a7',
516 'skip_download': True,
518 'skip': 'Blocked at Travis CI',
520 'url': 'http://www.mtv.de/news/glolix/77491-mtv-movies-spotlight--pixels--teil-3',
522 'id': 'local_playlist-4e760566473c4c8c5344',
524 'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1',
525 'description': 'MTV Movies Supercut',
529 'skip_download': True,
531 'skip': 'Das Video kann zur Zeit nicht abgespielt werden.',
533 _GEO_COUNTRIES
= ['DE']
534 _FEED_URL
= 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
536 def _get_feed_query(self
, uri
):