logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

mtv.py (18713B)


  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. from .common import InfoExtractor
  5. from ..compat import (
  6. compat_str,
  7. compat_xpath,
  8. )
  9. from ..utils import (
  10. ExtractorError,
  11. find_xpath_attr,
  12. fix_xml_ampersands,
  13. float_or_none,
  14. HEADRequest,
  15. RegexNotFoundError,
  16. sanitized_Request,
  17. strip_or_none,
  18. timeconvert,
  19. try_get,
  20. unescapeHTML,
  21. update_url_query,
  22. url_basename,
  23. xpath_text,
  24. )
  25. def _media_xml_tag(tag):
  26. return '{http://search.yahoo.com/mrss/}%s' % tag
  27. class MTVServicesInfoExtractor(InfoExtractor):
  28. _MOBILE_TEMPLATE = None
  29. _LANG = None
  30. @staticmethod
  31. def _id_from_uri(uri):
  32. return uri.split(':')[-1]
  33. @staticmethod
  34. def _remove_template_parameter(url):
  35. # Remove the templates, like &device={device}
  36. return re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', url)
  37. def _get_feed_url(self, uri):
  38. return self._FEED_URL
  39. def _get_thumbnail_url(self, uri, itemdoc):
  40. search_path = '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail'))
  41. thumb_node = itemdoc.find(search_path)
  42. if thumb_node is None:
  43. return None
  44. return thumb_node.get('url') or thumb_node.text or None
  45. def _extract_mobile_video_formats(self, mtvn_id):
  46. webpage_url = self._MOBILE_TEMPLATE % mtvn_id
  47. req = sanitized_Request(webpage_url)
  48. # Otherwise we get a webpage that would execute some javascript
  49. req.add_header('User-Agent', 'curl/7')
  50. webpage = self._download_webpage(req, mtvn_id,
  51. 'Downloading mobile page')
  52. metrics_url = unescapeHTML(self._search_regex(r'<a href="(http://metrics.+?)"', webpage, 'url'))
  53. req = HEADRequest(metrics_url)
  54. response = self._request_webpage(req, mtvn_id, 'Resolving url')
  55. url = response.geturl()
  56. # Transform the url to get the best quality:
  57. url = re.sub(r'.+pxE=mp4', 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=0+_pxK=18639+_pxE=mp4', url, 1)
  58. return [{'url': url, 'ext': 'mp4'}]
  59. def _extract_video_formats(self, mdoc, mtvn_id, video_id):
  60. if re.match(r'.*/(error_country_block\.swf|geoblock\.mp4|copyright_error\.flv(?:\?geo\b.+?)?)$', mdoc.find('.//src').text) is not None:
  61. if mtvn_id is not None and self._MOBILE_TEMPLATE is not None:
  62. self.to_screen('The normal version is not available from your '
  63. 'country, trying with the mobile version')
  64. return self._extract_mobile_video_formats(mtvn_id)
  65. raise ExtractorError('This video is not available from your country.',
  66. expected=True)
  67. formats = []
  68. for rendition in mdoc.findall('.//rendition'):
  69. if rendition.get('method') == 'hls':
  70. hls_url = rendition.find('./src').text
  71. formats.extend(self._extract_m3u8_formats(
  72. hls_url, video_id, ext='mp4', entry_protocol='m3u8_native',
  73. m3u8_id='hls', fatal=False))
  74. else:
  75. # fms
  76. try:
  77. _, _, ext = rendition.attrib['type'].partition('/')
  78. rtmp_video_url = rendition.find('./src').text
  79. if 'error_not_available.swf' in rtmp_video_url:
  80. raise ExtractorError(
  81. '%s said: video is not available' % self.IE_NAME,
  82. expected=True)
  83. if rtmp_video_url.endswith('siteunavail.png'):
  84. continue
  85. formats.extend([{
  86. 'ext': 'flv' if rtmp_video_url.startswith('rtmp') else ext,
  87. 'url': rtmp_video_url,
  88. 'format_id': '-'.join(filter(None, [
  89. 'rtmp' if rtmp_video_url.startswith('rtmp') else None,
  90. rendition.get('bitrate')])),
  91. 'width': int(rendition.get('width')),
  92. 'height': int(rendition.get('height')),
  93. }])
  94. except (KeyError, TypeError):
  95. raise ExtractorError('Invalid rendition field.')
  96. if formats:
  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. for typographic in transcript.findall('./typographic'):
  106. sub_src = typographic.get('src')
  107. if not sub_src:
  108. continue
  109. ext = typographic.get('format')
  110. if ext == 'cea-608':
  111. ext = 'scc'
  112. subtitles.setdefault(lang, []).append({
  113. 'url': compat_str(sub_src),
  114. 'ext': ext
  115. })
  116. return subtitles
  117. def _get_video_info(self, itemdoc, use_hls=True):
  118. uri = itemdoc.find('guid').text
  119. video_id = self._id_from_uri(uri)
  120. self.report_extraction(video_id)
  121. content_el = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content')))
  122. mediagen_url = self._remove_template_parameter(content_el.attrib['url'])
  123. mediagen_url = mediagen_url.replace('device={device}', '')
  124. if 'acceptMethods' not in mediagen_url:
  125. mediagen_url += '&' if '?' in mediagen_url else '?'
  126. mediagen_url += 'acceptMethods='
  127. mediagen_url += 'hls' if use_hls else 'fms'
  128. mediagen_doc = self._download_xml(
  129. mediagen_url, video_id, 'Downloading video urls', fatal=False)
  130. if mediagen_doc is False:
  131. return None
  132. item = mediagen_doc.find('./video/item')
  133. if item is not None and item.get('type') == 'text':
  134. message = '%s returned error: ' % self.IE_NAME
  135. if item.get('code') is not None:
  136. message += '%s - ' % item.get('code')
  137. message += item.text
  138. raise ExtractorError(message, expected=True)
  139. description = strip_or_none(xpath_text(itemdoc, 'description'))
  140. timestamp = timeconvert(xpath_text(itemdoc, 'pubDate'))
  141. title_el = None
  142. if title_el is None:
  143. title_el = find_xpath_attr(
  144. itemdoc, './/{http://search.yahoo.com/mrss/}category',
  145. 'scheme', 'urn:mtvn:video_title')
  146. if title_el is None:
  147. title_el = itemdoc.find(compat_xpath('.//{http://search.yahoo.com/mrss/}title'))
  148. if title_el is None:
  149. title_el = itemdoc.find(compat_xpath('.//title'))
  150. if title_el.text is None:
  151. title_el = None
  152. title = title_el.text
  153. if title is None:
  154. raise ExtractorError('Could not find video title')
  155. title = title.strip()
  156. # This a short id that's used in the webpage urls
  157. mtvn_id = None
  158. mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
  159. 'scheme', 'urn:mtvn:id')
  160. if mtvn_id_node is not None:
  161. mtvn_id = mtvn_id_node.text
  162. formats = self._extract_video_formats(mediagen_doc, mtvn_id, video_id)
  163. # Some parts of complete video may be missing (e.g. missing Act 3 in
  164. # http://www.southpark.de/alle-episoden/s14e01-sexual-healing)
  165. if not formats:
  166. return None
  167. self._sort_formats(formats)
  168. return {
  169. 'title': title,
  170. 'formats': formats,
  171. 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
  172. 'id': video_id,
  173. 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
  174. 'description': description,
  175. 'duration': float_or_none(content_el.attrib.get('duration')),
  176. 'timestamp': timestamp,
  177. }
  178. def _get_feed_query(self, uri):
  179. data = {'uri': uri}
  180. if self._LANG:
  181. data['lang'] = self._LANG
  182. return data
  183. def _get_videos_info(self, uri, use_hls=True):
  184. video_id = self._id_from_uri(uri)
  185. feed_url = self._get_feed_url(uri)
  186. info_url = update_url_query(feed_url, self._get_feed_query(uri))
  187. return self._get_videos_info_from_url(info_url, video_id, use_hls)
  188. def _get_videos_info_from_url(self, url, video_id, use_hls=True):
  189. idoc = self._download_xml(
  190. url, video_id,
  191. 'Downloading info', transform_source=fix_xml_ampersands)
  192. title = xpath_text(idoc, './channel/title')
  193. description = xpath_text(idoc, './channel/description')
  194. entries = []
  195. for item in idoc.findall('.//item'):
  196. info = self._get_video_info(item, use_hls)
  197. if info:
  198. entries.append(info)
  199. return self.playlist_result(
  200. entries, playlist_title=title, playlist_description=description)
  201. def _extract_triforce_mgid(self, webpage, data_zone=None, video_id=None):
  202. triforce_feed = self._parse_json(self._search_regex(
  203. r'triforceManifestFeed\s*=\s*({.+?})\s*;\s*\n', webpage,
  204. 'triforce feed', default='{}'), video_id, fatal=False)
  205. data_zone = self._search_regex(
  206. r'data-zone=(["\'])(?P<zone>.+?_lc_promo.*?)\1', webpage,
  207. 'data zone', default=data_zone, group='zone')
  208. feed_url = try_get(
  209. triforce_feed, lambda x: x['manifest']['zones'][data_zone]['feed'],
  210. compat_str)
  211. if not feed_url:
  212. return
  213. feed = self._download_json(feed_url, video_id, fatal=False)
  214. if not feed:
  215. return
  216. return try_get(feed, lambda x: x['result']['data']['id'], compat_str)
  217. @staticmethod
  218. def _extract_child_with_type(parent, t):
  219. for c in parent['children']:
  220. if c.get('type') == t:
  221. return c
  222. def _extract_mgid(self, webpage):
  223. try:
  224. # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
  225. # or http://media.mtvnservices.com/{mgid}
  226. og_url = self._og_search_video_url(webpage)
  227. mgid = url_basename(og_url)
  228. if mgid.endswith('.swf'):
  229. mgid = mgid[:-4]
  230. except RegexNotFoundError:
  231. mgid = None
  232. if mgid is None or ':' not in mgid:
  233. mgid = self._search_regex(
  234. [r'data-mgid="(.*?)"', r'swfobject\.embedSWF\(".*?(mgid:.*?)"'],
  235. webpage, 'mgid', default=None)
  236. if not mgid:
  237. sm4_embed = self._html_search_meta(
  238. 'sm4:video:embed', webpage, 'sm4 embed', default='')
  239. mgid = self._search_regex(
  240. r'embed/(mgid:.+?)["\'&?/]', sm4_embed, 'mgid', default=None)
  241. if not mgid:
  242. mgid = self._extract_triforce_mgid(webpage)
  243. if not mgid:
  244. data = self._parse_json(self._search_regex(
  245. r'__DATA__\s*=\s*({.+?});', webpage, 'data'), None)
  246. main_container = self._extract_child_with_type(data, 'MainContainer')
  247. ab_testing = self._extract_child_with_type(main_container, 'ABTesting')
  248. video_player = self._extract_child_with_type(ab_testing or main_container, 'VideoPlayer')
  249. mgid = video_player['props']['media']['video']['config']['uri']
  250. return mgid
  251. def _real_extract(self, url):
  252. title = url_basename(url)
  253. webpage = self._download_webpage(url, title)
  254. mgid = self._extract_mgid(webpage)
  255. videos_info = self._get_videos_info(mgid)
  256. return videos_info
  257. class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
  258. IE_NAME = 'mtvservices:embedded'
  259. _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
  260. _TEST = {
  261. # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
  262. 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
  263. 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
  264. 'info_dict': {
  265. 'id': '1043906',
  266. 'ext': 'mp4',
  267. 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
  268. 'description': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage as he tries summarizing "Game of Thrones" in under a minute.',
  269. 'timestamp': 1400126400,
  270. 'upload_date': '20140515',
  271. },
  272. }
  273. @staticmethod
  274. def _extract_url(webpage):
  275. mobj = re.search(
  276. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//media\.mtvnservices\.com/embed/.+?)\1', webpage)
  277. if mobj:
  278. return mobj.group('url')
  279. def _get_feed_url(self, uri):
  280. video_id = self._id_from_uri(uri)
  281. config = self._download_json(
  282. 'http://media.mtvnservices.com/pmt/e1/access/index.html?uri=%s&configtype=edge' % uri, video_id)
  283. return self._remove_template_parameter(config['feedWithQueryParams'])
  284. def _real_extract(self, url):
  285. mobj = re.match(self._VALID_URL, url)
  286. mgid = mobj.group('mgid')
  287. return self._get_videos_info(mgid)
  288. class MTVIE(MTVServicesInfoExtractor):
  289. IE_NAME = 'mtv'
  290. _VALID_URL = r'https?://(?:www\.)?mtv\.com/(?:video-clips|(?:full-)?episodes)/(?P<id>[^/?#.]+)'
  291. _FEED_URL = 'http://www.mtv.com/feeds/mrss/'
  292. _TESTS = [{
  293. 'url': 'http://www.mtv.com/video-clips/vl8qof/unlocking-the-truth-trailer',
  294. 'md5': '1edbcdf1e7628e414a8c5dcebca3d32b',
  295. 'info_dict': {
  296. 'id': '5e14040d-18a4-47c4-a582-43ff602de88e',
  297. 'ext': 'mp4',
  298. 'title': 'Unlocking The Truth|July 18, 2016|1|101|Trailer',
  299. 'description': '"Unlocking the Truth" premieres August 17th at 11/10c.',
  300. 'timestamp': 1468846800,
  301. 'upload_date': '20160718',
  302. },
  303. }, {
  304. 'url': 'http://www.mtv.com/full-episodes/94tujl/unlocking-the-truth-gates-of-hell-season-1-ep-101',
  305. 'only_matching': True,
  306. }, {
  307. 'url': 'http://www.mtv.com/episodes/g8xu7q/teen-mom-2-breaking-the-wall-season-7-ep-713',
  308. 'only_matching': True,
  309. }]
  310. class MTVJapanIE(MTVServicesInfoExtractor):
  311. IE_NAME = 'mtvjapan'
  312. _VALID_URL = r'https?://(?:www\.)?mtvjapan\.com/videos/(?P<id>[0-9a-z]+)'
  313. _TEST = {
  314. 'url': 'http://www.mtvjapan.com/videos/prayht/fresh-info-cadillac-escalade',
  315. 'info_dict': {
  316. 'id': 'bc01da03-6fe5-4284-8880-f291f4e368f5',
  317. 'ext': 'mp4',
  318. 'title': '【Fresh Info】Cadillac ESCALADE Sport Edition',
  319. },
  320. 'params': {
  321. 'skip_download': True,
  322. },
  323. }
  324. _GEO_COUNTRIES = ['JP']
  325. _FEED_URL = 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
  326. def _get_feed_query(self, uri):
  327. return {
  328. 'arcEp': 'mtvjapan.com',
  329. 'mgid': uri,
  330. }
  331. class MTVVideoIE(MTVServicesInfoExtractor):
  332. IE_NAME = 'mtv:video'
  333. _VALID_URL = r'''(?x)^https?://
  334. (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
  335. m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
  336. _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
  337. _TESTS = [
  338. {
  339. 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
  340. 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
  341. 'info_dict': {
  342. 'id': '853555',
  343. 'ext': 'mp4',
  344. 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
  345. 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
  346. 'timestamp': 1352610000,
  347. 'upload_date': '20121111',
  348. },
  349. },
  350. ]
  351. def _get_thumbnail_url(self, uri, itemdoc):
  352. return 'http://mtv.mtvnimages.com/uri/' + uri
  353. def _real_extract(self, url):
  354. mobj = re.match(self._VALID_URL, url)
  355. video_id = mobj.group('videoid')
  356. uri = mobj.groupdict().get('mgid')
  357. if uri is None:
  358. webpage = self._download_webpage(url, video_id)
  359. # Some videos come from Vevo.com
  360. m_vevo = re.search(
  361. r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
  362. if m_vevo:
  363. vevo_id = m_vevo.group(1)
  364. self.to_screen('Vevo video detected: %s' % vevo_id)
  365. return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
  366. uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
  367. return self._get_videos_info(uri)
  368. class MTVDEIE(MTVServicesInfoExtractor):
  369. IE_NAME = 'mtv.de'
  370. _VALID_URL = r'https?://(?:www\.)?mtv\.de/(?:musik/videoclips|folgen|news)/(?P<id>[0-9a-z]+)'
  371. _TESTS = [{
  372. 'url': 'http://www.mtv.de/musik/videoclips/2gpnv7/Traum',
  373. 'info_dict': {
  374. 'id': 'd5d472bc-f5b7-11e5-bffd-a4badb20dab5',
  375. 'ext': 'mp4',
  376. 'title': 'Traum',
  377. 'description': 'Traum',
  378. },
  379. 'params': {
  380. # rtmp download
  381. 'skip_download': True,
  382. },
  383. 'skip': 'Blocked at Travis CI',
  384. }, {
  385. # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97)
  386. 'url': 'http://www.mtv.de/folgen/6b1ylu/teen-mom-2-enthuellungen-S5-F1',
  387. 'info_dict': {
  388. 'id': '1e5a878b-31c5-11e7-a442-0e40cf2fc285',
  389. 'ext': 'mp4',
  390. 'title': 'Teen Mom 2',
  391. 'description': 'md5:dc65e357ef7e1085ed53e9e9d83146a7',
  392. },
  393. 'params': {
  394. # rtmp download
  395. 'skip_download': True,
  396. },
  397. 'skip': 'Blocked at Travis CI',
  398. }, {
  399. 'url': 'http://www.mtv.de/news/glolix/77491-mtv-movies-spotlight--pixels--teil-3',
  400. 'info_dict': {
  401. 'id': 'local_playlist-4e760566473c4c8c5344',
  402. 'ext': 'mp4',
  403. 'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1',
  404. 'description': 'MTV Movies Supercut',
  405. },
  406. 'params': {
  407. # rtmp download
  408. 'skip_download': True,
  409. },
  410. 'skip': 'Das Video kann zur Zeit nicht abgespielt werden.',
  411. }]
  412. _GEO_COUNTRIES = ['DE']
  413. _FEED_URL = 'http://feeds.mtvnservices.com/od/feed/intl-mrss-player-feed'
  414. def _get_feed_query(self, uri):
  415. return {
  416. 'arcEp': 'mtv.de',
  417. 'mgid': uri,
  418. }