2 from __future__
import unicode_literals
6 from .common
import InfoExtractor
30 def _media_xml_tag(tag
):
31 return '{http://search.yahoo.com/mrss/}%s' % tag
34 class MTVServicesInfoExtractor(InfoExtractor
):
35 _MOBILE_TEMPLATE
= None
39 def _id_from_uri(uri
):
40 return uri
.split(':')[-1]
43 def _remove_template_parameter(url
):
44 # Remove the templates, like &device={device}
45 return re
.sub(r
'&[^=]*?={.*?}(?=(&|$))', '', url
)
47 def _get_feed_url(self
, uri
):
50 def _get_thumbnail_url(self
, uri
, itemdoc
):
51 search_path
= '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail'))
52 thumb_node
= itemdoc
.find(search_path
)
53 if thumb_node
is None:
55 return thumb_node
.get('url') or thumb_node
.text
or None
57 def _extract_mobile_video_formats(self
, mtvn_id
):
58 webpage_url
= self
._MOBILE
_TEMPLATE
% mtvn_id
59 req
= sanitized_Request(webpage_url
)
60 # Otherwise we get a webpage that would execute some javascript
61 req
.add_header('User-Agent', 'curl/7')
62 webpage
= self
._download
_webpage
(req
, mtvn_id
,
63 'Downloading mobile page')
64 metrics_url
= unescapeHTML(self
._search
_regex
(r
'<a href="(http://metrics.+?)"', webpage
, 'url'))
65 req
= HEADRequest(metrics_url
)
66 response
= self
._request
_webpage
(req
, mtvn_id
, 'Resolving url')
67 url
= response
.geturl()
68 # Transform the url to get the best quality:
69 url
= re
.sub(r
'.+pxE=mp4', 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=0+_pxK=18639+_pxE=mp4', url
, 1)
70 return [{'url': url, 'ext': 'mp4'}
]
72 def _extract_video_formats(self
, mdoc
, mtvn_id
, video_id
):
73 if re
.match(r
'.*/(error_country_block\.swf|geoblock\.mp4|copyright_error\.flv(?:\?geo\b.+?)?)$', mdoc
.find('.//src').text
) is not None:
74 if mtvn_id
is not None and self
._MOBILE
_TEMPLATE
is not None:
75 self
.to_screen('The normal version is not available from your '
76 'country, trying with the mobile version')
77 return self
._extract
_mobile
_video
_formats
(mtvn_id
)
78 raise ExtractorError('This video is not available from your country.',
82 for rendition
in mdoc
.findall('.//rendition'):
83 if rendition
.get('method') == 'hls':
84 hls_url
= rendition
.find('./src').text
85 formats
.extend(self
._extract
_m
3u8_formats
(
86 hls_url
, video_id
, ext
='mp4', entry_protocol
='m3u8_native',
87 m3u8_id
='hls', fatal
=False))
91 _
, _
, ext
= rendition
.attrib
['type'].partition('/')
92 rtmp_video_url
= rendition
.find('./src').text
93 if 'error_not_available.swf' in rtmp_video_url
:
95 '%s said: video is not available' % self
.IE_NAME
,
97 if rtmp_video_url
.endswith('siteunavail.png'):
100 'ext': 'flv' if rtmp_video_url
.startswith('rtmp') else ext
,
101 'url': rtmp_video_url
,
102 'format_id': '-'.join(filter(None, [
103 'rtmp' if rtmp_video_url
.startswith('rtmp') else None,
104 rendition
.get('bitrate')])),
105 'width': int(rendition
.get('width')),
106 'height': int(rendition
.get('height')),
108 except (KeyError, TypeError):
109 raise ExtractorError('Invalid rendition field.')
111 self
._sort
_formats
(formats
)
114 def _extract_subtitles(self
, mdoc
, mtvn_id
):
116 for transcript
in mdoc
.findall('.//transcript'):
117 if transcript
.get('kind') != 'captions':
119 lang
= transcript
.get('srclang')
120 for typographic
in transcript
.findall('./typographic'):
121 sub_src
= typographic
.get('src')
124 ext
= typographic
.get('format')
127 subtitles
.setdefault(lang
, []).append({
128 'url': compat_str(sub_src
),
133 def _get_video_info(self
, itemdoc
, use_hls
=True):
134 uri
= itemdoc
.find('guid').text
135 video_id
= self
._id
_from
_uri
(uri
)
136 self
.report_extraction(video_id
)
137 content_el
= itemdoc
.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content')))
138 mediagen_url
= self
._remove
_template
_parameter
(content_el
.attrib
['url'])
139 mediagen_url
= mediagen_url
.replace('device={device}', '')
140 if 'acceptMethods' not in mediagen_url
:
141 mediagen_url
+= '&' if '?' in mediagen_url
else '?'
142 mediagen_url
+= 'acceptMethods='
143 mediagen_url
+= 'hls' if use_hls
else 'fms'
145 mediagen_doc
= self
._download
_xml
(
146 mediagen_url
, video_id
, 'Downloading video urls', fatal
=False)
148 if mediagen_doc
is False:
151 item
= mediagen_doc
.find('./video/item')
152 if item
is not None and item
.get('type') == 'text':
153 message
= '%s returned error: ' % self
.IE_NAME
154 if item
.get('code') is not None:
155 message
+= '%s - ' % item
.get('code')
157 raise ExtractorError(message
, expected
=True)
159 description
= strip_or_none(xpath_text(itemdoc
, 'description'))
161 timestamp
= timeconvert(xpath_text(itemdoc
, 'pubDate'))
165 title_el
= find_xpath_attr(
166 itemdoc
, './/{http://search.yahoo.com/mrss/}category',
167 'scheme', 'urn:mtvn:video_title')
169 title_el
= itemdoc
.find(compat_xpath('.//{http://search.yahoo.com/mrss/}title'))
171 title_el
= itemdoc
.find(compat_xpath('.//title'))
172 if title_el
.text
is None:
175 title
= title_el
.text
177 raise ExtractorError('Could not find video title')
178 title
= title
.strip()
180 series
= find_xpath_attr(
181 itemdoc
, './/{http://search.yahoo.com/mrss/}category',
182 'scheme', 'urn:mtvn:franchise')
183 season
= find_xpath_attr(
184 itemdoc
, './/{http://search.yahoo.com/mrss/}category',
185 'scheme', 'urn:mtvn:seasonN')
186 episode
= find_xpath_attr(
187 itemdoc
, './/{http://search.yahoo.com/mrss/}category',
188 'scheme', 'urn:mtvn:episodeN')
189 series
= series
.text
if series
is not None else None
190 season
= season
.text
if season
is not None else None
191 episode
= episode
.text
if episode
is not None else None
192 if season
and episode
:
193 # episode number includes season, so remove it
194 episode
= re
.sub(r
'^%s' % season
, '', episode
)
196 # This a short id that's used in the webpage urls
198 mtvn_id_node
= find_xpath_attr(itemdoc
, './/{http://search.yahoo.com/mrss/}category',
199 'scheme', 'urn:mtvn:id')
200 if mtvn_id_node
is not None:
201 mtvn_id
= mtvn_id_node
.text
203 formats
= self
._extract
_video
_formats
(mediagen_doc
, mtvn_id
, video_id
)
205 # Some parts of complete video may be missing (e.g. missing Act 3 in
206 # http://www.southpark.de/alle-episoden/s14e01-sexual-healing)
210 self
._sort
_formats
(formats
)
215 'subtitles': self
._extract
_subtitles
(mediagen_doc
, mtvn_id
),
217 'thumbnail': self
._get
_thumbnail
_url
(uri
, itemdoc
),
218 'description': description
,
219 'duration': float_or_none(content_el
.attrib
.get('duration')),
220 'timestamp': timestamp
,
222 'season_number': int_or_none(season
),
223 'episode_number': int_or_none(episode
),
226 def _get_feed_query(self
, uri
):
229 data
['lang'] = self
._LANG
232 def _get_videos_info(self
, uri
, use_hls
=True):
233 video_id
= self
._id
_from
_uri
(uri
)
234 feed_url
= self
._get
_feed
_url
(uri
)
235 info_url
= update_url_query(feed_url
, self
._get
_feed
_query
(uri
))
236 return self
._get
_videos
_info
_from
_url
(info_url
, video_id
, use_hls
)
238 def _get_videos_info_from_url(self
, url
, video_id
, use_hls
=True):
239 idoc
= self
._download
_xml
(
241 'Downloading info', transform_source
=fix_xml_ampersands
)
243 title
= xpath_text(idoc
, './channel/title')
244 description
= xpath_text(idoc
, './channel/description')
247 for item
in idoc
.findall('.//item'):
248 info
= self
._get
_video
_info
(item
, use_hls
)
252 # TODO: should be multi-video
253 return self
.playlist_result(
254 entries
, playlist_title
=title
, playlist_description
=description
)
256 def _extract_triforce_mgid(self
, webpage
, data_zone
=None, video_id
=None):
257 triforce_feed
= self
._parse
_json
(self
._search
_regex
(
258 r
'triforceManifestFeed\s*=\s*({.+?})\s*;\s*\n', webpage
,
259 'triforce feed', default
='{}'), video_id
, fatal
=False)
261 data_zone
= self
._search
_regex
(
262 r
'data-zone=(["\'])(?P
<zone
>.+?_lc_promo
.*?
)\
1', webpage,
263 'data zone
', default=data_zone, group='zone
')
266 triforce_feed, lambda x: x['manifest
']['zones
'][data_zone]['feed
'],
271 feed = self._download_json(feed_url, video_id, fatal=False)
275 return try_get(feed, lambda x: x['result
']['data
']['id'], compat_str)
278 def _extract_child_with_type(parent, t):
279 for c in parent['children
']:
280 if c.get('type') == t:
283 def _extract_mgid(self, webpage):
285 # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
286 # or http://media.mtvnservices.com/{mgid}
287 og_url = self._og_search_video_url(webpage)
288 mgid = url_basename(og_url)
289 if mgid.endswith('.swf
'):
291 except RegexNotFoundError:
294 if mgid is None or ':' not in mgid:
295 mgid = self._search_regex(
296 [r'data
-mgid
="(.*?)"', r'swfobject\
.embedSWF\
(".*?(mgid:.*?)"'],
297 webpage, 'mgid
', default=None)
300 sm4_embed = self._html_search_meta(
301 'sm4
:video
:embed
', webpage, 'sm4 embed
', default='')
302 mgid = self._search_regex(
303 r'embed
/(mgid
:.+?
)["\'&?/]', sm4_embed, 'mgid', default=None)
306 mgid = self._extract_triforce_mgid(webpage)
309 data = self._parse_json(self._search_regex(
310 r'__DATA__\s*=\s*({.+?});', webpage, 'data'), None)
311 main_container = self._extract_child_with_type(data, 'MainContainer')
312 ab_testing = self._extract_child_with_type(main_container, 'ABTesting')
313 video_player = self._extract_child_with_type(ab_testing or main_container, 'VideoPlayer')
314 mgid = video_player['props']['media']['video']['config']['uri']
318 def _real_extract(self, url):
319 title = url_basename(url)
320 webpage = self._download_webpage(url, title)
321 mgid = self._extract_mgid(webpage)
322 videos_info = self._get_videos_info(mgid)
326 class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
327 IE_NAME = 'mtvservices:embedded'
328 _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
331 # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
332 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
333 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
337 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
338 'description': '"Sexy sexy sexy
, stabby stabby stabby
, beautiful language
," says Peter Dinklage as he tries summarizing "Game of Thrones
" in under a minute.',
339 'timestamp': 1400126400,
340 'upload_date': '20140515',
345 def _extract_url(webpage):
347 r'<iframe[^>]+?src=(["\'])(?P
<url
>(?
:https?
:)?
//media\
.mtvnservices\
.com
/embed
/.+?
)\
1', webpage)
349 return mobj.group('url
')
351 def _get_feed_url(self, uri):
352 video_id = self._id_from_uri(uri)
353 config = self._download_json(
354 'http
://media
.mtvnservices
.com
/pmt
/e1
/access
/index
.html?uri
=%s&configtype
=edge
' % uri, video_id)
355 return self._remove_template_parameter(config['feedWithQueryParams
'])
357 def _real_extract(self, url):
358 mobj = re.match(self._VALID_URL, url)
359 mgid = mobj.group('mgid
')
360 return self._get_videos_info(mgid)
363 class MTVIE(MTVServicesInfoExtractor):
365 _VALID_URL = r'https?
://(?
:www\
.)?mtv\
.com
/(?
:video
-clips|
(?
:full
-)?episodes
)/(?P
<id>[^
/?
#.]+)'
366 _FEED_URL
= 'http://www.mtv.com/feeds/mrss/'
369 'url': 'http://www.mtv.com/video-clips/vl8qof/unlocking-the-truth-trailer',
370 'md5': '1edbcdf1e7628e414a8c5dcebca3d32b',
372 'id': '5e14040d-18a4-47c4-a582-43ff602de88e',
374 'title': 'Unlocking The Truth|July 18, 2016|1|101|Trailer',
375 'description': '"Unlocking the Truth" premieres August 17th at 11/10c.',
376 'timestamp': 1468846800,
377 'upload_date': '20160718',
380 'url': 'http://www.mtv.com/full-episodes/94tujl/unlocking-the-truth-gates-of-hell-season-1-ep-101',
381 'only_matching': True,
383 'url': 'http://www.mtv.com/episodes/g8xu7q/teen-mom-2-breaking-the-wall-season-7-ep-713',
384 'only_matching': True,
388 class MTVJapanIE(MTVServicesInfoExtractor
):
390 _VALID_URL
= r
'https?://(?:www\.)?mtvjapan\.com/videos/(?P<id>[0-9a-z]+)'
393 'url': 'http://www.mtvjapan.com/videos/prayht/fresh-info-cadillac-escalade',
395 'id': 'bc01da03-6fe5-4284-8880-f291f4e368f5',
397 'title': '【Fresh Info】Cadillac ESCALADE Sport Edition',
400 'skip_download': True,
403 _GEO_COUNTRIES
= ['JP']
404 _FEED_URL
= 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
406 def _get_feed_query(self
, uri
):
408 'arcEp': 'mtvjapan.com',
413 class MTVVideoIE(MTVServicesInfoExtractor
):
414 IE_NAME
= 'mtv:video'
415 _VALID_URL
= r
'''(?x)^https?://
416 (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
417 m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
419 _FEED_URL
= 'http://www.mtv.com/player/embed/AS3/rss/'
423 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
424 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
428 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
429 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
430 'timestamp': 1352610000,
431 'upload_date': '20121111',
436 def _get_thumbnail_url(self
, uri
, itemdoc
):
437 return 'http://mtv.mtvnimages.com/uri/' + uri
439 def _real_extract(self
, url
):
440 mobj
= re
.match(self
._VALID
_URL
, url
)
441 video_id
= mobj
.group('videoid')
442 uri
= mobj
.groupdict().get('mgid')
444 webpage
= self
._download
_webpage
(url
, video_id
)
446 # Some videos come from Vevo.com
448 r
'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage
)
450 vevo_id
= m_vevo
.group(1)
451 self
.to_screen('Vevo video detected: %s' % vevo_id
)
452 return self
.url_result('vevo:%s' % vevo_id
, ie
='Vevo')
454 uri
= self
._html
_search
_regex
(r
'/uri/(.*?)\?', webpage
, 'uri')
455 return self
._get
_videos
_info
(uri
)
458 class MTVDEIE(MTVServicesInfoExtractor
):
460 _VALID_URL
= r
'https?://(?:www\.)?mtv\.de/(?:musik/videoclips|folgen|news)/(?P<id>[0-9a-z]+)'
462 'url': 'http://www.mtv.de/musik/videoclips/2gpnv7/Traum',
464 'id': 'd5d472bc-f5b7-11e5-bffd-a4badb20dab5',
467 'description': 'Traum',
471 'skip_download': True,
473 'skip': 'Blocked at Travis CI',
475 # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97)
476 'url': 'http://www.mtv.de/folgen/6b1ylu/teen-mom-2-enthuellungen-S5-F1',
478 'id': '1e5a878b-31c5-11e7-a442-0e40cf2fc285',
480 'title': 'Teen Mom 2',
481 'description': 'md5:dc65e357ef7e1085ed53e9e9d83146a7',
485 'skip_download': True,
487 'skip': 'Blocked at Travis CI',
489 'url': 'http://www.mtv.de/news/glolix/77491-mtv-movies-spotlight--pixels--teil-3',
491 'id': 'local_playlist-4e760566473c4c8c5344',
493 'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1',
494 'description': 'MTV Movies Supercut',
498 'skip_download': True,
500 'skip': 'Das Video kann zur Zeit nicht abgespielt werden.',
502 _GEO_COUNTRIES
= ['DE']
503 _FEED_URL
= 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
505 def _get_feed_query(self
, uri
):
512 class MTVItaliaIE(MTVServicesInfoExtractor
):
514 _VALID_URL
= r
'https?://(?:www\.)?mtv\.it/(?:episodi|video|musica)/(?P<id>[0-9a-z]+)'
516 'url': 'http://www.mtv.it/episodi/24bqab/mario-una-serie-di-maccio-capatonda-cavoli-amario-episodio-completo-S1-E1',
518 'id': '0f0fc78e-45fc-4cce-8f24-971c25477530',
520 'title': 'Cavoli amario (episodio completo)',
521 'description': 'md5:4962bccea8fed5b7c03b295ae1340660',
522 'series': 'Mario - Una Serie Di Maccio Capatonda',
527 'skip_download': True,
530 _GEO_COUNTRIES
= ['IT']
531 _FEED_URL
= 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
533 def _get_feed_query(self
, uri
):
540 class MTVItaliaProgrammaIE(MTVItaliaIE
):
541 IE_NAME
= 'mtv.it:programma'
542 _VALID_URL
= r
'https?://(?:www\.)?mtv\.it/(?:programmi|playlist)/(?P<id>[0-9a-z]+)'
544 # program page: general
545 'url': 'http://www.mtv.it/programmi/s2rppv/mario-una-serie-di-maccio-capatonda',
547 'id': 'a6f155bc-8220-4640-aa43-9b95f64ffa3d',
548 'title': 'Mario - Una Serie Di Maccio Capatonda',
549 'description': 'md5:72fbffe1f77ccf4e90757dd4e3216153',
553 'skip_download': True,
556 # program page: specific season
557 'url': 'http://www.mtv.it/programmi/d9ncjf/mario-una-serie-di-maccio-capatonda-S2',
559 'id': '4deeb5d8-f272-490c-bde2-ff8d261c6dd1',
560 'title': 'Mario - Una Serie Di Maccio Capatonda - Stagione 2',
562 'playlist_count': 34,
564 'skip_download': True,
567 # playlist page + redirect
568 'url': 'http://www.mtv.it/playlist/sexy-videos/ilctal',
570 'id': 'dee8f9ee-756d-493b-bf37-16d1d2783359',
571 'title': 'Sexy Videos',
573 'playlist_mincount': 145,
575 'skip_download': True,
578 _GEO_COUNTRIES
= ['IT']
579 _FEED_URL
= 'http://www.mtv.it/feeds/triforce/manifest/v8'
581 def _get_entries(self
, title
, url
):
583 pg
= self
._search
_regex
(r
'/(\d+)$', url
, 'entries', '1')
584 entries
= self
._download
_json
(url
, title
, 'page %s' % pg
)
586 entries
, lambda x
: x
['result']['nextPageURL'], compat_str
)
589 lambda x
: x
['result']['data']['items'],
590 lambda x
: x
['result']['data']['seasons']),
592 for entry
in entries
or []:
593 if entry
.get('canonicalURL'):
594 yield self
.url_result(entry
['canonicalURL'])
598 def _real_extract(self
, url
):
600 info_url
= update_url_query(self
._FEED
_URL
, query
)
601 video_id
= self
._match
_id
(url
)
602 info
= self
._download
_json
(info_url
, video_id
).get('manifest')
605 info
, lambda x
: x
['newLocation']['url'], compat_str
)
607 return self
.url_result(redirect
)
609 title
= info
.get('title')
611 info
, lambda x
: x
['reporting']['itemId'], compat_str
)
613 info
, lambda x
: x
['reporting']['parentId'], compat_str
)
615 playlist_url
= current_url
= None
616 for z
in (info
.get('zones') or {}).values():
617 if z
.get('moduleName') in ('INTL_M304', 'INTL_M209'):
618 info_url
= z
.get('feed')
619 if z
.get('moduleName') in ('INTL_M308', 'INTL_M317'):
620 playlist_url
= playlist_url
or z
.get('feed')
621 if z
.get('moduleName') in ('INTL_M300',):
622 current_url
= current_url
or z
.get('feed')
625 raise ExtractorError('No info found')
627 if video_id
== parent_id
:
628 video_id
= self
._search
_regex
(
629 r
'([^\/]+)/[^\/]+$', info_url
, 'video_id')
631 info
= self
._download
_json
(info_url
, video_id
, 'Show infos')
632 info
= try_get(info
, lambda x
: x
['result']['data'], dict)
633 title
= title
or try_get(
635 lambda x
: x
['title'],
636 lambda x
: x
['headline']),
638 description
= try_get(info
, lambda x
: x
['content'], compat_str
)
642 self
._download
_json
(playlist_url
, video_id
, 'Seasons info'),
643 lambda x
: x
['result']['data'], dict)
645 season
, lambda x
: x
['currentSeason'], compat_str
)
647 season
, lambda x
: x
['seasons'], list) or []
649 if current
in [s
.get('eTitle') for s
in seasons
]:
650 playlist_url
= current_url
653 r
'[-|]\s*(?:mtv\s*italia|programma|playlist)',
654 '', title
, flags
=re
.IGNORECASE
).strip()
656 return self
.playlist_result(
657 self
._get
_entries
(title
, playlist_url
),
658 video_id
, title
, description
)