mtv.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. from __future__ import unicode_literals
  2. import re
  3. from .common import InfoExtractor
  4. from ..compat import (
  5. compat_str,
  6. compat_xpath,
  7. )
  8. from ..utils import (
  9. ExtractorError,
  10. find_xpath_attr,
  11. fix_xml_ampersands,
  12. float_or_none,
  13. HEADRequest,
  14. NO_DEFAULT,
  15. RegexNotFoundError,
  16. sanitized_Request,
  17. strip_or_none,
  18. timeconvert,
  19. unescapeHTML,
  20. update_url_query,
  21. url_basename,
  22. xpath_text,
  23. )
  24. def _media_xml_tag(tag):
  25. return '{http://search.yahoo.com/mrss/}%s' % tag
  26. class MTVServicesInfoExtractor(InfoExtractor):
  27. _MOBILE_TEMPLATE = None
  28. _LANG = None
  29. @staticmethod
  30. def _id_from_uri(uri):
  31. return uri.split(':')[-1]
  32. @staticmethod
  33. def _remove_template_parameter(url):
  34. # Remove the templates, like &device={device}
  35. return re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', url)
  36. # This was originally implemented for ComedyCentral, but it also works here
  37. @classmethod
  38. def _transform_rtmp_url(cls, rtmp_video_url):
  39. m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp\..+?/.*)$', rtmp_video_url)
  40. if not m:
  41. return {'rtmp': rtmp_video_url}
  42. base = 'http://viacommtvstrmfs.fplive.net/'
  43. return {'http': base + m.group('finalid')}
  44. def _get_feed_url(self, uri):
  45. return self._FEED_URL
  46. def _get_thumbnail_url(self, uri, itemdoc):
  47. search_path = '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail'))
  48. thumb_node = itemdoc.find(search_path)
  49. if thumb_node is None:
  50. return None
  51. else:
  52. return thumb_node.attrib['url']
  53. def _extract_mobile_video_formats(self, mtvn_id):
  54. webpage_url = self._MOBILE_TEMPLATE % mtvn_id
  55. req = sanitized_Request(webpage_url)
  56. # Otherwise we get a webpage that would execute some javascript
  57. req.add_header('User-Agent', 'curl/7')
  58. webpage = self._download_webpage(req, mtvn_id,
  59. 'Downloading mobile page')
  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)
  66. 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.',
  74. expected=True)
  75. formats = []
  76. for rendition in mdoc.findall('.//rendition'):
  77. if rendition.attrib['method'] == 'hls':
  78. hls_url = rendition.find('./src').text
  79. formats.extend(self._extract_m3u8_formats(hls_url, video_id, ext='mp4'))
  80. else:
  81. # fms
  82. try:
  83. _, _, ext = rendition.attrib['type'].partition('/')
  84. rtmp_video_url = rendition.find('./src').text
  85. if rtmp_video_url.endswith('siteunavail.png'):
  86. continue
  87. new_urls = self._transform_rtmp_url(rtmp_video_url)
  88. formats.extend([{
  89. 'ext': 'flv' if new_url.startswith('rtmp') else ext,
  90. 'url': new_url,
  91. 'format_id': '-'.join(filter(None, [kind, rendition.get('bitrate')])),
  92. 'width': int(rendition.get('width')),
  93. 'height': int(rendition.get('height')),
  94. } for kind, new_url in new_urls.items()])
  95. except (KeyError, TypeError):
  96. raise ExtractorError('Invalid rendition field.')
  97. self._sort_formats(formats)
  98. return formats
  99. def _extract_subtitles(self, mdoc, mtvn_id):
  100. subtitles = {}
  101. for transcript in mdoc.findall('.//transcript'):
  102. if transcript.get('kind') != 'captions':
  103. continue
  104. lang = transcript.get('srclang')
  105. subtitles[lang] = [{
  106. 'url': compat_str(typographic.get('src')),
  107. 'ext': typographic.get('format')
  108. } for typographic in transcript.findall('./typographic')]
  109. return subtitles
  110. def _get_video_info(self, itemdoc, use_hls):
  111. uri = itemdoc.find('guid').text
  112. video_id = self._id_from_uri(uri)
  113. self.report_extraction(video_id)
  114. content_el = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content')))
  115. mediagen_url = self._remove_template_parameter(content_el.attrib['url'])
  116. mediagen_url = mediagen_url.replace('device={device}', '')
  117. if 'acceptMethods' not in mediagen_url:
  118. mediagen_url += '&' if '?' in mediagen_url else '?'
  119. mediagen_url += 'acceptMethods='
  120. mediagen_url += 'hls' if use_hls else 'fms'
  121. mediagen_doc = self._download_xml(mediagen_url, video_id,
  122. 'Downloading video urls')
  123. item = mediagen_doc.find('./video/item')
  124. if item is not None and item.get('type') == 'text':
  125. message = '%s returned error: ' % self.IE_NAME
  126. if item.get('code') is not None:
  127. message += '%s - ' % item.get('code')
  128. message += item.text
  129. raise ExtractorError(message, expected=True)
  130. description = strip_or_none(xpath_text(itemdoc, 'description'))
  131. timestamp = timeconvert(xpath_text(itemdoc, 'pubDate'))
  132. title_el = None
  133. if title_el is None:
  134. title_el = find_xpath_attr(
  135. itemdoc, './/{http://search.yahoo.com/mrss/}category',
  136. 'scheme', 'urn:mtvn:video_title')
  137. if title_el is None:
  138. title_el = itemdoc.find(compat_xpath('.//{http://search.yahoo.com/mrss/}title'))
  139. if title_el is None:
  140. title_el = itemdoc.find(compat_xpath('.//title'))
  141. if title_el.text is None:
  142. title_el = None
  143. title = title_el.text
  144. if title is None:
  145. raise ExtractorError('Could not find video title')
  146. title = title.strip()
  147. # This a short id that's used in the webpage urls
  148. mtvn_id = None
  149. mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
  150. 'scheme', 'urn:mtvn:id')
  151. if mtvn_id_node is not None:
  152. mtvn_id = mtvn_id_node.text
  153. formats = self._extract_video_formats(mediagen_doc, mtvn_id, video_id)
  154. return {
  155. 'title': title,
  156. 'formats': formats,
  157. 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
  158. 'id': video_id,
  159. 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
  160. 'description': description,
  161. 'duration': float_or_none(content_el.attrib.get('duration')),
  162. 'timestamp': timestamp,
  163. }
  164. def _get_feed_query(self, uri):
  165. data = {'uri': uri}
  166. if self._LANG:
  167. data['lang'] = self._LANG
  168. return data
  169. def _get_videos_info(self, uri, use_hls=False):
  170. video_id = self._id_from_uri(uri)
  171. feed_url = self._get_feed_url(uri)
  172. info_url = update_url_query(feed_url, self._get_feed_query(uri))
  173. return self._get_videos_info_from_url(info_url, video_id, use_hls)
  174. def _get_videos_info_from_url(self, url, video_id, use_hls):
  175. idoc = self._download_xml(
  176. url, video_id,
  177. 'Downloading info', transform_source=fix_xml_ampersands)
  178. title = xpath_text(idoc, './channel/title')
  179. description = xpath_text(idoc, './channel/description')
  180. return self.playlist_result(
  181. [self._get_video_info(item, use_hls) for item in idoc.findall('.//item')],
  182. playlist_title=title, playlist_description=description)
  183. def _extract_mgid(self, webpage, default=NO_DEFAULT):
  184. try:
  185. # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
  186. # or http://media.mtvnservices.com/{mgid}
  187. og_url = self._og_search_video_url(webpage)
  188. mgid = url_basename(og_url)
  189. if mgid.endswith('.swf'):
  190. mgid = mgid[:-4]
  191. except RegexNotFoundError:
  192. mgid = None
  193. if mgid is None or ':' not in mgid:
  194. mgid = self._search_regex(
  195. [r'data-mgid="(.*?)"', r'swfobject.embedSWF\(".*?(mgid:.*?)"'],
  196. webpage, 'mgid', default=None)
  197. if not mgid:
  198. sm4_embed = self._html_search_meta(
  199. 'sm4:video:embed', webpage, 'sm4 embed', default='')
  200. mgid = self._search_regex(
  201. r'embed/(mgid:.+?)["\'&?/]', sm4_embed, 'mgid', default=default)
  202. return mgid
  203. def _real_extract(self, url):
  204. title = url_basename(url)
  205. webpage = self._download_webpage(url, title)
  206. mgid = self._extract_mgid(webpage)
  207. videos_info = self._get_videos_info(mgid)
  208. return videos_info
  209. class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
  210. IE_NAME = 'mtvservices:embedded'
  211. _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
  212. _TEST = {
  213. # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
  214. 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
  215. 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
  216. 'info_dict': {
  217. 'id': '1043906',
  218. 'ext': 'mp4',
  219. 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
  220. 'description': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage as he tries summarizing "Game of Thrones" in under a minute.',
  221. 'timestamp': 1400126400,
  222. 'upload_date': '20140515',
  223. },
  224. }
  225. @staticmethod
  226. def _extract_url(webpage):
  227. mobj = re.search(
  228. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//media.mtvnservices.com/embed/.+?)\1', webpage)
  229. if mobj:
  230. return mobj.group('url')
  231. def _get_feed_url(self, uri):
  232. video_id = self._id_from_uri(uri)
  233. config = self._download_json(
  234. 'http://media.mtvnservices.com/pmt/e1/access/index.html?uri=%s&configtype=edge' % uri, video_id)
  235. return self._remove_template_parameter(config['feedWithQueryParams'])
  236. def _real_extract(self, url):
  237. mobj = re.match(self._VALID_URL, url)
  238. mgid = mobj.group('mgid')
  239. return self._get_videos_info(mgid)
  240. class MTVIE(MTVServicesInfoExtractor):
  241. IE_NAME = 'mtv'
  242. _VALID_URL = r'https?://(?:www\.)?mtv\.com/(?:video-clips|full-episodes)/(?P<id>[^/?#.]+)'
  243. _FEED_URL = 'http://www.mtv.com/feeds/mrss/'
  244. _TESTS = [{
  245. 'url': 'http://www.mtv.com/video-clips/vl8qof/unlocking-the-truth-trailer',
  246. 'md5': '1edbcdf1e7628e414a8c5dcebca3d32b',
  247. 'info_dict': {
  248. 'id': '5e14040d-18a4-47c4-a582-43ff602de88e',
  249. 'ext': 'mp4',
  250. 'title': 'Unlocking The Truth|July 18, 2016|1|101|Trailer',
  251. 'description': '"Unlocking the Truth" premieres August 17th at 11/10c.',
  252. 'timestamp': 1468846800,
  253. 'upload_date': '20160718',
  254. },
  255. }, {
  256. 'url': 'http://www.mtv.com/full-episodes/94tujl/unlocking-the-truth-gates-of-hell-season-1-ep-101',
  257. 'only_matching': True,
  258. }]
  259. class MTVVideoIE(MTVServicesInfoExtractor):
  260. IE_NAME = 'mtv:video'
  261. _VALID_URL = r'''(?x)^https?://
  262. (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
  263. m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
  264. _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
  265. _TESTS = [
  266. {
  267. 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
  268. 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
  269. 'info_dict': {
  270. 'id': '853555',
  271. 'ext': 'mp4',
  272. 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
  273. 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
  274. 'timestamp': 1352610000,
  275. 'upload_date': '20121111',
  276. },
  277. },
  278. ]
  279. def _get_thumbnail_url(self, uri, itemdoc):
  280. return 'http://mtv.mtvnimages.com/uri/' + uri
  281. def _real_extract(self, url):
  282. mobj = re.match(self._VALID_URL, url)
  283. video_id = mobj.group('videoid')
  284. uri = mobj.groupdict().get('mgid')
  285. if uri is None:
  286. webpage = self._download_webpage(url, video_id)
  287. # Some videos come from Vevo.com
  288. m_vevo = re.search(
  289. r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
  290. if m_vevo:
  291. vevo_id = m_vevo.group(1)
  292. self.to_screen('Vevo video detected: %s' % vevo_id)
  293. return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
  294. uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
  295. return self._get_videos_info(uri)
  296. class MTVDEIE(MTVServicesInfoExtractor):
  297. IE_NAME = 'mtv.de'
  298. _VALID_URL = r'https?://(?:www\.)?mtv\.de/(?:artists|shows|news)/(?:[^/]+/)*(?P<id>\d+)-[^/#?]+/*(?:[#?].*)?$'
  299. _TESTS = [{
  300. 'url': 'http://www.mtv.de/artists/10571-cro/videos/61131-traum',
  301. 'info_dict': {
  302. 'id': 'music_video-a50bc5f0b3aa4b3190aa',
  303. 'ext': 'flv',
  304. 'title': 'MusicVideo_cro-traum',
  305. 'description': 'Cro - Traum',
  306. },
  307. 'params': {
  308. # rtmp download
  309. 'skip_download': True,
  310. },
  311. 'skip': 'Blocked at Travis CI',
  312. }, {
  313. # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97)
  314. 'url': 'http://www.mtv.de/shows/933-teen-mom-2/staffeln/5353/folgen/63565-enthullungen',
  315. 'info_dict': {
  316. 'id': 'local_playlist-f5ae778b9832cc837189',
  317. 'ext': 'flv',
  318. 'title': 'Episode_teen-mom-2_shows_season-5_episode-1_full-episode_part1',
  319. },
  320. 'params': {
  321. # rtmp download
  322. 'skip_download': True,
  323. },
  324. 'skip': 'Blocked at Travis CI',
  325. }, {
  326. 'url': 'http://www.mtv.de/news/77491-mtv-movies-spotlight-pixels-teil-3',
  327. 'info_dict': {
  328. 'id': 'local_playlist-4e760566473c4c8c5344',
  329. 'ext': 'mp4',
  330. 'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1',
  331. 'description': 'MTV Movies Supercut',
  332. },
  333. 'params': {
  334. # rtmp download
  335. 'skip_download': True,
  336. },
  337. 'skip': 'Das Video kann zur Zeit nicht abgespielt werden.',
  338. }]
  339. def _real_extract(self, url):
  340. video_id = self._match_id(url)
  341. webpage = self._download_webpage(url, video_id)
  342. playlist = self._parse_json(
  343. self._search_regex(
  344. r'window\.pagePlaylist\s*=\s*(\[.+?\]);\n', webpage, 'page playlist'),
  345. video_id)
  346. def _mrss_url(item):
  347. return item['mrss'] + item.get('mrssvars', '')
  348. # news pages contain single video in playlist with different id
  349. if len(playlist) == 1:
  350. return self._get_videos_info_from_url(_mrss_url(playlist[0]), video_id)
  351. for item in playlist:
  352. item_id = item.get('id')
  353. if item_id and compat_str(item_id) == video_id:
  354. return self._get_videos_info_from_url(_mrss_url(item), video_id)