3 from .common
import InfoExtractor
4 from ..compat
import compat_str
25 def _media_xml_tag(tag
):
26 return '{http://search.yahoo.com/mrss/}%s' % tag
29 class MTVServicesInfoExtractor(InfoExtractor
):
30 _MOBILE_TEMPLATE
= None
34 def _id_from_uri(uri
):
35 return uri
.split(':')[-1]
38 def _remove_template_parameter(url
):
39 # Remove the templates, like &device={device}
40 return re
.sub(r
'&[^=]*?={.*?}(?=(&|$))', '', url
)
42 def _get_feed_url(self
, uri
, url
=None):
45 def _get_thumbnail_url(self
, uri
, itemdoc
):
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:
50 return thumb_node
.get('url') or thumb_node
.text
or None
52 def _extract_mobile_video_formats(self
, mtvn_id
):
53 webpage_url
= self
._MOBILE
_TEMPLATE
% mtvn_id
54 req
= sanitized_Request(webpage_url
)
55 # Otherwise we get a webpage that would execute some javascript
56 req
.add_header('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'}
]
67 def _extract_video_formats(self
, mdoc
, mtvn_id
, video_id
):
68 if re
.match(r
'.*/(error_country_block\.swf|geoblock\.mp4|copyright_error\.flv(?:\?geo\b.+?)?)$', 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.',
77 for rendition
in mdoc
.findall('.//rendition'):
78 if rendition
.get('method') == 'hls':
79 hls_url
= rendition
.find('./src').text
80 formats
.extend(self
._extract
_m
3u8_formats
(
81 hls_url
, video_id
, ext
='mp4', entry_protocol
='m3u8_native',
82 m3u8_id
='hls', fatal
=False))
86 _
, _
, ext
= rendition
.attrib
['type'].partition('/')
87 rtmp_video_url
= rendition
.find('./src').text
88 if 'error_not_available.swf' in rtmp_video_url
:
90 '%s said: video is not available' % self
.IE_NAME
,
92 if rtmp_video_url
.endswith('siteunavail.png'):
95 'ext': 'flv' if rtmp_video_url
.startswith('rtmp') else ext
,
96 'url': rtmp_video_url
,
97 'format_id': join_nonempty(
98 'rtmp' if rtmp_video_url
.startswith('rtmp') else None,
99 rendition
.get('bitrate')),
100 'width': int(rendition
.get('width')),
101 'height': int(rendition
.get('height')),
103 except (KeyError, TypeError):
104 raise ExtractorError('Invalid rendition field.')
107 def _extract_subtitles(self
, mdoc
, mtvn_id
):
109 for transcript
in mdoc
.findall('.//transcript'):
110 if transcript
.get('kind') != 'captions':
112 lang
= transcript
.get('srclang')
113 for typographic
in transcript
.findall('./typographic'):
114 sub_src
= typographic
.get('src')
117 ext
= typographic
.get('format')
120 subtitles
.setdefault(lang
, []).append({
121 'url': compat_str(sub_src
),
126 def _get_video_info(self
, itemdoc
, use_hls
=True):
127 uri
= itemdoc
.find('guid').text
128 video_id
= self
._id
_from
_uri
(uri
)
129 self
.report_extraction(video_id
)
130 content_el
= itemdoc
.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content')))
131 mediagen_url
= self
._remove
_template
_parameter
(content_el
.attrib
['url'])
132 mediagen_url
= mediagen_url
.replace('device={device}', '')
133 if 'acceptMethods' not in mediagen_url
:
134 mediagen_url
+= '&' if '?' in mediagen_url
else '?'
135 mediagen_url
+= 'acceptMethods='
136 mediagen_url
+= 'hls' if use_hls
else 'fms'
138 mediagen_doc
= self
._download
_xml
(
139 mediagen_url
, video_id
, 'Downloading video urls', fatal
=False)
141 if mediagen_doc
is False:
144 item
= mediagen_doc
.find('./video/item')
145 if item
is not None and item
.get('type') == 'text':
146 message
= '%s returned error: ' % self
.IE_NAME
147 if item
.get('code') is not None:
148 message
+= '%s - ' % item
.get('code')
150 raise ExtractorError(message
, expected
=True)
152 description
= strip_or_none(xpath_text(itemdoc
, 'description'))
154 timestamp
= timeconvert(xpath_text(itemdoc
, 'pubDate'))
158 title_el
= find_xpath_attr(
159 itemdoc
, './/{http://search.yahoo.com/mrss/}category',
160 'scheme', 'urn:mtvn:video_title')
162 title_el
= itemdoc
.find('.//{http://search.yahoo.com/mrss/}title')
164 title_el
= itemdoc
.find('.//title')
165 if title_el
.text
is None:
168 title
= title_el
.text
170 raise ExtractorError('Could not find video title')
171 title
= title
.strip()
173 series
= find_xpath_attr(
174 itemdoc
, './/{http://search.yahoo.com/mrss/}category',
175 'scheme', 'urn:mtvn:franchise')
176 season
= find_xpath_attr(
177 itemdoc
, './/{http://search.yahoo.com/mrss/}category',
178 'scheme', 'urn:mtvn:seasonN')
179 episode
= find_xpath_attr(
180 itemdoc
, './/{http://search.yahoo.com/mrss/}category',
181 'scheme', 'urn:mtvn:episodeN')
182 series
= series
.text
if series
is not None else None
183 season
= season
.text
if season
is not None else None
184 episode
= episode
.text
if episode
is not None else None
185 if season
and episode
:
186 # episode number includes season, so remove it
187 episode
= re
.sub(r
'^%s' % season
, '', episode
)
189 # This a short id that's used in the webpage urls
191 mtvn_id_node
= find_xpath_attr(itemdoc
, './/{http://search.yahoo.com/mrss/}category',
192 'scheme', 'urn:mtvn:id')
193 if mtvn_id_node
is not None:
194 mtvn_id
= mtvn_id_node
.text
196 formats
= self
._extract
_video
_formats
(mediagen_doc
, mtvn_id
, video_id
)
198 # Some parts of complete video may be missing (e.g. missing Act 3 in
199 # http://www.southpark.de/alle-episoden/s14e01-sexual-healing)
206 'subtitles': self
._extract
_subtitles
(mediagen_doc
, mtvn_id
),
208 'thumbnail': self
._get
_thumbnail
_url
(uri
, itemdoc
),
209 'description': description
,
210 'duration': float_or_none(content_el
.attrib
.get('duration')),
211 'timestamp': timestamp
,
213 'season_number': int_or_none(season
),
214 'episode_number': int_or_none(episode
),
217 def _get_feed_query(self
, uri
):
220 data
['lang'] = self
._LANG
223 def _get_videos_info(self
, uri
, use_hls
=True, url
=None):
224 video_id
= self
._id
_from
_uri
(uri
)
225 feed_url
= self
._get
_feed
_url
(uri
, url
)
226 info_url
= update_url_query(feed_url
, self
._get
_feed
_query
(uri
))
227 return self
._get
_videos
_info
_from
_url
(info_url
, video_id
, use_hls
)
229 def _get_videos_info_from_url(self
, url
, video_id
, use_hls
=True):
230 idoc
= self
._download
_xml
(
232 'Downloading info', transform_source
=fix_xml_ampersands
)
234 title
= xpath_text(idoc
, './channel/title')
235 description
= xpath_text(idoc
, './channel/description')
238 for item
in idoc
.findall('.//item'):
239 info
= self
._get
_video
_info
(item
, use_hls
)
243 # TODO: should be multi-video
244 return self
.playlist_result(
245 entries
, playlist_title
=title
, playlist_description
=description
)
247 def _extract_triforce_mgid(self
, webpage
, data_zone
=None, video_id
=None):
248 triforce_feed
= self
._parse
_json
(self
._search
_regex
(
249 r
'triforceManifestFeed\s*=\s*({.+?})\s*;\s*\n', webpage
,
250 'triforce feed', default
='{}'), video_id
, fatal
=False)
252 data_zone
= self
._search
_regex
(
253 r
'data-zone=(["\'])(?P
<zone
>.+?_lc_promo
.*?
)\
1', webpage,
254 'data zone
', default=data_zone, group='zone
')
257 triforce_feed, lambda x: x['manifest
']['zones
'][data_zone]['feed
'],
262 feed = self._download_json(feed_url, video_id, fatal=False)
266 return try_get(feed, lambda x: x['result
']['data
']['id'], compat_str)
269 def _extract_child_with_type(parent, t):
270 for c in parent['children
']:
271 if c.get('type') == t:
274 def _extract_mgid(self, webpage):
276 # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
277 # or http://media.mtvnservices.com/{mgid}
278 og_url = self._og_search_video_url(webpage)
279 mgid = url_basename(og_url)
280 if mgid.endswith('.swf
'):
282 except RegexNotFoundError:
285 if mgid is None or ':' not in mgid:
286 mgid = self._search_regex(
287 [r'data
-mgid
="(.*?)"', r'swfobject\
.embedSWF\
(".*?(mgid:.*?)"'],
288 webpage, 'mgid
', default=None)
291 sm4_embed = self._html_search_meta(
292 'sm4
:video
:embed
', webpage, 'sm4 embed
', default='')
293 mgid = self._search_regex(
294 r'embed
/(mgid
:.+?
)["\'&?/]', sm4_embed, 'mgid', default=None)
297 mgid = self._extract_triforce_mgid(webpage)
300 data = self._parse_json(self._search_regex(
301 r'__DATA__\s*=\s*({.+?});', webpage, 'data'), None)
302 main_container = self._extract_child_with_type(data, 'MainContainer')
303 ab_testing = self._extract_child_with_type(main_container, 'ABTesting')
304 video_player = self._extract_child_with_type(ab_testing or main_container, 'VideoPlayer')
306 mgid = try_get(video_player, lambda x: x['props']['media']['video']['config']['uri'])
308 flex_wrapper = self._extract_child_with_type(ab_testing or main_container, 'FlexWrapper')
309 auth_suite_wrapper = self._extract_child_with_type(flex_wrapper, 'AuthSuiteWrapper')
310 player = self._extract_child_with_type(auth_suite_wrapper or flex_wrapper, 'Player')
312 mgid = try_get(player, lambda x: x['props']['videoDetail']['mgid'])
315 raise ExtractorError('Could not extract mgid')
319 def _real_extract(self, url):
320 title = url_basename(url)
321 webpage = self._download_webpage(url, title)
322 mgid = self._extract_mgid(webpage)
323 videos_info = self._get_videos_info(mgid, url=url)
327 class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
328 IE_NAME = 'mtvservices:embedded'
329 _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
330 _EMBED_REGEX = [r'<iframe[^>]+?src=(["\'])(?P
<url
>(?
:https?
:)?
//media\
.mtvnservices\
.com
/embed
/.+?
)\
1']
333 # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
334 'url
': 'http
://media
.mtvnservices
.com
/embed
/mgid
:uma
:video
:mtv
.com
:1043906/cp~vid
%3D1043906
%26uri
%3Dmgid
%3Auma
%3Avideo
%3Amtv
.com
%3A1043906
',
335 'md5
': 'cb349b21a7897164cede95bd7bf3fbb9
',
339 'title
': 'Peter Dinklage Sums Up
\'Game Of Thrones
\' In
45 Seconds
',
340 'description
': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage
as he tries summarizing
"Game of Thrones" in under a minute
.',
341 'timestamp
': 1400126400,
342 'upload_date
': '20140515',
346 def _get_feed_url(self, uri, url=None):
347 video_id = self._id_from_uri(uri)
348 config = self._download_json(
349 'http
://media
.mtvnservices
.com
/pmt
/e1
/access
/index
.html?uri
=%s&configtype
=edge
' % uri, video_id)
350 return self._remove_template_parameter(config['feedWithQueryParams
'])
352 def _real_extract(self, url):
353 mobj = self._match_valid_url(url)
354 mgid = mobj.group('mgid
')
355 return self._get_videos_info(mgid)
358 class MTVIE(MTVServicesInfoExtractor):
360 _VALID_URL = r'https?
://(?
:www\
.)?mtv\
.com
/(?
:video
-clips|
(?
:full
-)?episodes
)/(?P
<id>[^
/?
#.]+)'
361 _FEED_URL
= 'http://www.mtv.com/feeds/mrss/'
364 'url': 'http://www.mtv.com/video-clips/vl8qof/unlocking-the-truth-trailer',
365 'md5': '1edbcdf1e7628e414a8c5dcebca3d32b',
367 'id': '5e14040d-18a4-47c4-a582-43ff602de88e',
369 'title': 'Unlocking The Truth|July 18, 2016|1|101|Trailer',
370 'description': '"Unlocking the Truth" premieres August 17th at 11/10c.',
371 'timestamp': 1468846800,
372 'upload_date': '20160718',
375 'url': 'http://www.mtv.com/full-episodes/94tujl/unlocking-the-truth-gates-of-hell-season-1-ep-101',
376 'only_matching': True,
378 'url': 'http://www.mtv.com/episodes/g8xu7q/teen-mom-2-breaking-the-wall-season-7-ep-713',
379 'only_matching': True,
383 class MTVJapanIE(MTVServicesInfoExtractor
):
385 _VALID_URL
= r
'https?://(?:www\.)?mtvjapan\.com/videos/(?P<id>[0-9a-z]+)'
388 'url': 'http://www.mtvjapan.com/videos/prayht/fresh-info-cadillac-escalade',
390 'id': 'bc01da03-6fe5-4284-8880-f291f4e368f5',
392 'title': '【Fresh Info】Cadillac ESCALADE Sport Edition',
395 'skip_download': True,
398 _GEO_COUNTRIES
= ['JP']
399 _FEED_URL
= 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
401 def _get_feed_query(self
, uri
):
403 'arcEp': 'mtvjapan.com',
408 class MTVVideoIE(MTVServicesInfoExtractor
):
409 IE_NAME
= 'mtv:video'
410 _VALID_URL
= r
'''(?x)^https?://
411 (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
412 m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
414 _FEED_URL
= 'http://www.mtv.com/player/embed/AS3/rss/'
418 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
419 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
423 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
424 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
425 'timestamp': 1352610000,
426 'upload_date': '20121111',
431 def _get_thumbnail_url(self
, uri
, itemdoc
):
432 return 'http://mtv.mtvnimages.com/uri/' + uri
434 def _real_extract(self
, url
):
435 mobj
= self
._match
_valid
_url
(url
)
436 video_id
= mobj
.group('videoid')
437 uri
= mobj
.groupdict().get('mgid')
439 webpage
= self
._download
_webpage
(url
, video_id
)
441 # Some videos come from Vevo.com
443 r
'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage
)
445 vevo_id
= m_vevo
.group(1)
446 self
.to_screen('Vevo video detected: %s' % vevo_id
)
447 return self
.url_result('vevo:%s' % vevo_id
, ie
='Vevo')
449 uri
= self
._html
_search
_regex
(r
'/uri/(.*?)\?', webpage
, 'uri')
450 return self
._get
_videos
_info
(uri
)
453 class MTVDEIE(MTVServicesInfoExtractor
):
455 _VALID_URL
= r
'https?://(?:www\.)?mtv\.de/(?:musik/videoclips|folgen|news)/(?P<id>[0-9a-z]+)'
457 'url': 'http://www.mtv.de/musik/videoclips/2gpnv7/Traum',
459 'id': 'd5d472bc-f5b7-11e5-bffd-a4badb20dab5',
462 'description': 'Traum',
466 'skip_download': True,
468 'skip': 'Blocked at Travis CI',
470 # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97)
471 'url': 'http://www.mtv.de/folgen/6b1ylu/teen-mom-2-enthuellungen-S5-F1',
473 'id': '1e5a878b-31c5-11e7-a442-0e40cf2fc285',
475 'title': 'Teen Mom 2',
476 'description': 'md5:dc65e357ef7e1085ed53e9e9d83146a7',
480 'skip_download': True,
482 'skip': 'Blocked at Travis CI',
484 'url': 'http://www.mtv.de/news/glolix/77491-mtv-movies-spotlight--pixels--teil-3',
486 'id': 'local_playlist-4e760566473c4c8c5344',
488 'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1',
489 'description': 'MTV Movies Supercut',
493 'skip_download': True,
495 'skip': 'Das Video kann zur Zeit nicht abgespielt werden.',
497 _GEO_COUNTRIES
= ['DE']
498 _FEED_URL
= 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
500 def _get_feed_query(self
, uri
):
507 class MTVItaliaIE(MTVServicesInfoExtractor
):
509 _VALID_URL
= r
'https?://(?:www\.)?mtv\.it/(?:episodi|video|musica)/(?P<id>[0-9a-z]+)'
511 'url': 'http://www.mtv.it/episodi/24bqab/mario-una-serie-di-maccio-capatonda-cavoli-amario-episodio-completo-S1-E1',
513 'id': '0f0fc78e-45fc-4cce-8f24-971c25477530',
515 'title': 'Cavoli amario (episodio completo)',
516 'description': 'md5:4962bccea8fed5b7c03b295ae1340660',
517 'series': 'Mario - Una Serie Di Maccio Capatonda',
522 'skip_download': True,
525 _GEO_COUNTRIES
= ['IT']
526 _FEED_URL
= 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
528 def _get_feed_query(self
, uri
):
535 class MTVItaliaProgrammaIE(MTVItaliaIE
): # XXX: Do not subclass from concrete IE
536 IE_NAME
= 'mtv.it:programma'
537 _VALID_URL
= r
'https?://(?:www\.)?mtv\.it/(?:programmi|playlist)/(?P<id>[0-9a-z]+)'
539 # program page: general
540 'url': 'http://www.mtv.it/programmi/s2rppv/mario-una-serie-di-maccio-capatonda',
542 'id': 'a6f155bc-8220-4640-aa43-9b95f64ffa3d',
543 'title': 'Mario - Una Serie Di Maccio Capatonda',
544 'description': 'md5:72fbffe1f77ccf4e90757dd4e3216153',
548 'skip_download': True,
551 # program page: specific season
552 'url': 'http://www.mtv.it/programmi/d9ncjf/mario-una-serie-di-maccio-capatonda-S2',
554 'id': '4deeb5d8-f272-490c-bde2-ff8d261c6dd1',
555 'title': 'Mario - Una Serie Di Maccio Capatonda - Stagione 2',
557 'playlist_count': 34,
559 'skip_download': True,
562 # playlist page + redirect
563 'url': 'http://www.mtv.it/playlist/sexy-videos/ilctal',
565 'id': 'dee8f9ee-756d-493b-bf37-16d1d2783359',
566 'title': 'Sexy Videos',
568 'playlist_mincount': 145,
570 'skip_download': True,
573 _GEO_COUNTRIES
= ['IT']
574 _FEED_URL
= 'http://www.mtv.it/feeds/triforce/manifest/v8'
576 def _get_entries(self
, title
, url
):
578 pg
= self
._search
_regex
(r
'/(\d+)$', url
, 'entries', '1')
579 entries
= self
._download
_json
(url
, title
, 'page %s' % pg
)
581 entries
, lambda x
: x
['result']['nextPageURL'], compat_str
)
584 lambda x
: x
['result']['data']['items'],
585 lambda x
: x
['result']['data']['seasons']),
587 for entry
in entries
or []:
588 if entry
.get('canonicalURL'):
589 yield self
.url_result(entry
['canonicalURL'])
593 def _real_extract(self
, url
):
595 info_url
= update_url_query(self
._FEED
_URL
, query
)
596 video_id
= self
._match
_id
(url
)
597 info
= self
._download
_json
(info_url
, video_id
).get('manifest')
600 info
, lambda x
: x
['newLocation']['url'], compat_str
)
602 return self
.url_result(redirect
)
604 title
= info
.get('title')
606 info
, lambda x
: x
['reporting']['itemId'], compat_str
)
608 info
, lambda x
: x
['reporting']['parentId'], compat_str
)
610 playlist_url
= current_url
= None
611 for z
in (info
.get('zones') or {}).values():
612 if z
.get('moduleName') in ('INTL_M304', 'INTL_M209'):
613 info_url
= z
.get('feed')
614 if z
.get('moduleName') in ('INTL_M308', 'INTL_M317'):
615 playlist_url
= playlist_url
or z
.get('feed')
616 if z
.get('moduleName') in ('INTL_M300',):
617 current_url
= current_url
or z
.get('feed')
620 raise ExtractorError('No info found')
622 if video_id
== parent_id
:
623 video_id
= self
._search
_regex
(
624 r
'([^\/]+)/[^\/]+$', info_url
, 'video_id')
626 info
= self
._download
_json
(info_url
, video_id
, 'Show infos')
627 info
= try_get(info
, lambda x
: x
['result']['data'], dict)
628 title
= title
or try_get(
630 lambda x
: x
['title'],
631 lambda x
: x
['headline']),
633 description
= try_get(info
, lambda x
: x
['content'], compat_str
)
637 self
._download
_json
(playlist_url
, video_id
, 'Seasons info'),
638 lambda x
: x
['result']['data'], dict)
640 season
, lambda x
: x
['currentSeason'], compat_str
)
642 season
, lambda x
: x
['seasons'], list) or []
644 if current
in [s
.get('eTitle') for s
in seasons
]:
645 playlist_url
= current_url
648 r
'[-|]\s*(?:mtv\s*italia|programma|playlist)',
649 '', title
, flags
=re
.IGNORECASE
).strip()
651 return self
.playlist_result(
652 self
._get
_entries
(title
, playlist_url
),
653 video_id
, title
, description
)