You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

369 lines
14 KiB

10 years ago
10 years ago
10 years ago
  1. from __future__ import unicode_literals
  2. import re
  3. from .common import InfoExtractor
  4. from ..compat import (
  5. compat_urllib_parse,
  6. compat_urllib_request,
  7. compat_str,
  8. )
  9. from ..utils import (
  10. ExtractorError,
  11. find_xpath_attr,
  12. fix_xml_ampersands,
  13. HEADRequest,
  14. unescapeHTML,
  15. url_basename,
  16. RegexNotFoundError,
  17. )
  18. def _media_xml_tag(tag):
  19. return '{http://search.yahoo.com/mrss/}%s' % tag
  20. class MTVServicesInfoExtractor(InfoExtractor):
  21. _MOBILE_TEMPLATE = None
  22. _LANG = None
  23. @staticmethod
  24. def _id_from_uri(uri):
  25. return uri.split(':')[-1]
  26. # This was originally implemented for ComedyCentral, but it also works here
  27. @staticmethod
  28. def _transform_rtmp_url(rtmp_video_url):
  29. m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp\..+?/.*)$', rtmp_video_url)
  30. if not m:
  31. return rtmp_video_url
  32. base = 'http://viacommtvstrmfs.fplive.net/'
  33. return base + m.group('finalid')
  34. def _get_feed_url(self, uri):
  35. return self._FEED_URL
  36. def _get_thumbnail_url(self, uri, itemdoc):
  37. search_path = '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail'))
  38. thumb_node = itemdoc.find(search_path)
  39. if thumb_node is None:
  40. return None
  41. else:
  42. return thumb_node.attrib['url']
  43. def _extract_mobile_video_formats(self, mtvn_id):
  44. webpage_url = self._MOBILE_TEMPLATE % mtvn_id
  45. req = compat_urllib_request.Request(webpage_url)
  46. # Otherwise we get a webpage that would execute some javascript
  47. req.add_header('User-Agent', 'curl/7')
  48. webpage = self._download_webpage(req, mtvn_id,
  49. 'Downloading mobile page')
  50. metrics_url = unescapeHTML(self._search_regex(r'<a href="(http://metrics.+?)"', webpage, 'url'))
  51. req = HEADRequest(metrics_url)
  52. response = self._request_webpage(req, mtvn_id, 'Resolving url')
  53. url = response.geturl()
  54. # Transform the url to get the best quality:
  55. url = re.sub(r'.+pxE=mp4', 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=0+_pxK=18639+_pxE=mp4', url, 1)
  56. return [{'url': url, 'ext': 'mp4'}]
  57. def _extract_video_formats(self, mdoc, mtvn_id):
  58. if re.match(r'.*/(error_country_block\.swf|geoblock\.mp4|copyright_error\.flv(?:\?geo\b.+?)?)$', mdoc.find('.//src').text) is not None:
  59. if mtvn_id is not None and self._MOBILE_TEMPLATE is not None:
  60. self.to_screen('The normal version is not available from your '
  61. 'country, trying with the mobile version')
  62. return self._extract_mobile_video_formats(mtvn_id)
  63. raise ExtractorError('This video is not available from your country.',
  64. expected=True)
  65. formats = []
  66. for rendition in mdoc.findall('.//rendition'):
  67. try:
  68. _, _, ext = rendition.attrib['type'].partition('/')
  69. rtmp_video_url = rendition.find('./src').text
  70. if rtmp_video_url.endswith('siteunavail.png'):
  71. continue
  72. formats.append({
  73. 'ext': ext,
  74. 'url': self._transform_rtmp_url(rtmp_video_url),
  75. 'format_id': rendition.get('bitrate'),
  76. 'width': int(rendition.get('width')),
  77. 'height': int(rendition.get('height')),
  78. })
  79. except (KeyError, TypeError):
  80. raise ExtractorError('Invalid rendition field.')
  81. self._sort_formats(formats)
  82. return formats
  83. def _extract_subtitles(self, mdoc, mtvn_id):
  84. subtitles = {}
  85. for transcript in mdoc.findall('.//transcript'):
  86. if transcript.get('kind') != 'captions':
  87. continue
  88. lang = transcript.get('srclang')
  89. subtitles[lang] = [{
  90. 'url': compat_str(typographic.get('src')),
  91. 'ext': typographic.get('format')
  92. } for typographic in transcript.findall('./typographic')]
  93. return subtitles
  94. def _get_video_info(self, itemdoc):
  95. uri = itemdoc.find('guid').text
  96. video_id = self._id_from_uri(uri)
  97. self.report_extraction(video_id)
  98. mediagen_url = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content'))).attrib['url']
  99. # Remove the templates, like &device={device}
  100. mediagen_url = re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', mediagen_url)
  101. if 'acceptMethods' not in mediagen_url:
  102. mediagen_url += '&' if '?' in mediagen_url else '?'
  103. mediagen_url += 'acceptMethods=fms'
  104. mediagen_doc = self._download_xml(mediagen_url, video_id,
  105. 'Downloading video urls')
  106. item = mediagen_doc.find('./video/item')
  107. if item is not None and item.get('type') == 'text':
  108. message = '%s returned error: ' % self.IE_NAME
  109. if item.get('code') is not None:
  110. message += '%s - ' % item.get('code')
  111. message += item.text
  112. raise ExtractorError(message, expected=True)
  113. description_node = itemdoc.find('description')
  114. if description_node is not None:
  115. description = description_node.text.strip()
  116. else:
  117. description = None
  118. title_el = None
  119. if title_el is None:
  120. title_el = find_xpath_attr(
  121. itemdoc, './/{http://search.yahoo.com/mrss/}category',
  122. 'scheme', 'urn:mtvn:video_title')
  123. if title_el is None:
  124. title_el = itemdoc.find('.//{http://search.yahoo.com/mrss/}title')
  125. if title_el is None:
  126. title_el = itemdoc.find('.//title') or itemdoc.find('./title')
  127. if title_el.text is None:
  128. title_el = None
  129. title = title_el.text
  130. if title is None:
  131. raise ExtractorError('Could not find video title')
  132. title = title.strip()
  133. # This a short id that's used in the webpage urls
  134. mtvn_id = None
  135. mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
  136. 'scheme', 'urn:mtvn:id')
  137. if mtvn_id_node is not None:
  138. mtvn_id = mtvn_id_node.text
  139. return {
  140. 'title': title,
  141. 'formats': self._extract_video_formats(mediagen_doc, mtvn_id),
  142. 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
  143. 'id': video_id,
  144. 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
  145. 'description': description,
  146. }
  147. def _get_videos_info(self, uri):
  148. video_id = self._id_from_uri(uri)
  149. feed_url = self._get_feed_url(uri)
  150. data = compat_urllib_parse.urlencode({'uri': uri})
  151. info_url = feed_url + '?'
  152. if self._LANG:
  153. info_url += 'lang=%s&' % self._LANG
  154. info_url += data
  155. return self._get_videos_info_from_url(info_url, video_id)
  156. def _get_videos_info_from_url(self, url, video_id):
  157. idoc = self._download_xml(
  158. url, video_id,
  159. 'Downloading info', transform_source=fix_xml_ampersands)
  160. return self.playlist_result(
  161. [self._get_video_info(item) for item in idoc.findall('.//item')])
  162. def _real_extract(self, url):
  163. title = url_basename(url)
  164. webpage = self._download_webpage(url, title)
  165. try:
  166. # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
  167. # or http://media.mtvnservices.com/{mgid}
  168. og_url = self._og_search_video_url(webpage)
  169. mgid = url_basename(og_url)
  170. if mgid.endswith('.swf'):
  171. mgid = mgid[:-4]
  172. except RegexNotFoundError:
  173. mgid = None
  174. if mgid is None or ':' not in mgid:
  175. mgid = self._search_regex(
  176. [r'data-mgid="(.*?)"', r'swfobject.embedSWF\(".*?(mgid:.*?)"'],
  177. webpage, 'mgid', default=None)
  178. if not mgid:
  179. sm4_embed = self._html_search_meta(
  180. 'sm4:video:embed', webpage, 'sm4 embed', default='')
  181. mgid = self._search_regex(
  182. r'embed/(mgid:.+?)["\'&?/]', sm4_embed, 'mgid')
  183. videos_info = self._get_videos_info(mgid)
  184. return videos_info
  185. class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
  186. IE_NAME = 'mtvservices:embedded'
  187. _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
  188. _TEST = {
  189. # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
  190. 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
  191. 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
  192. 'info_dict': {
  193. 'id': '1043906',
  194. 'ext': 'mp4',
  195. 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
  196. 'description': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage as he tries summarizing "Game of Thrones" in under a minute.',
  197. },
  198. }
  199. @staticmethod
  200. def _extract_url(webpage):
  201. mobj = re.search(
  202. r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//media.mtvnservices.com/embed/.+?)\1', webpage)
  203. if mobj:
  204. return mobj.group('url')
  205. def _get_feed_url(self, uri):
  206. video_id = self._id_from_uri(uri)
  207. site_id = uri.replace(video_id, '')
  208. config_url = ('http://media.mtvnservices.com/pmt/e1/players/{0}/'
  209. 'context4/context5/config.xml'.format(site_id))
  210. config_doc = self._download_xml(config_url, video_id)
  211. feed_node = config_doc.find('.//feed')
  212. feed_url = feed_node.text.strip().split('?')[0]
  213. return feed_url
  214. def _real_extract(self, url):
  215. mobj = re.match(self._VALID_URL, url)
  216. mgid = mobj.group('mgid')
  217. return self._get_videos_info(mgid)
  218. class MTVIE(MTVServicesInfoExtractor):
  219. _VALID_URL = r'''(?x)^https?://
  220. (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
  221. m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
  222. _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
  223. _TESTS = [
  224. {
  225. 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
  226. 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
  227. 'info_dict': {
  228. 'id': '853555',
  229. 'ext': 'mp4',
  230. 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
  231. 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
  232. },
  233. },
  234. ]
  235. def _get_thumbnail_url(self, uri, itemdoc):
  236. return 'http://mtv.mtvnimages.com/uri/' + uri
  237. def _real_extract(self, url):
  238. mobj = re.match(self._VALID_URL, url)
  239. video_id = mobj.group('videoid')
  240. uri = mobj.groupdict().get('mgid')
  241. if uri is None:
  242. webpage = self._download_webpage(url, video_id)
  243. # Some videos come from Vevo.com
  244. m_vevo = re.search(
  245. r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
  246. if m_vevo:
  247. vevo_id = m_vevo.group(1)
  248. self.to_screen('Vevo video detected: %s' % vevo_id)
  249. return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
  250. uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
  251. return self._get_videos_info(uri)
  252. class MTVIggyIE(MTVServicesInfoExtractor):
  253. IE_NAME = 'mtviggy.com'
  254. _VALID_URL = r'https?://www\.mtviggy\.com/videos/.+'
  255. _TEST = {
  256. 'url': 'http://www.mtviggy.com/videos/arcade-fire-behind-the-scenes-at-the-biggest-music-experiment-yet/',
  257. 'info_dict': {
  258. 'id': '984696',
  259. 'ext': 'mp4',
  260. 'title': 'Arcade Fire: Behind the Scenes at the Biggest Music Experiment Yet',
  261. }
  262. }
  263. _FEED_URL = 'http://all.mtvworldverticals.com/feed-xml/'
  264. class MTVDEIE(MTVServicesInfoExtractor):
  265. IE_NAME = 'mtv.de'
  266. _VALID_URL = r'https?://(?:www\.)?mtv\.de/(?:artists|shows|news)/(?:[^/]+/)*(?P<id>\d+)-[^/#?]+/*(?:[#?].*)?$'
  267. _TESTS = [{
  268. 'url': 'http://www.mtv.de/artists/10571-cro/videos/61131-traum',
  269. 'info_dict': {
  270. 'id': 'music_video-a50bc5f0b3aa4b3190aa',
  271. 'ext': 'mp4',
  272. 'title': 'MusicVideo_cro-traum',
  273. 'description': 'Cro - Traum',
  274. },
  275. 'params': {
  276. # rtmp download
  277. 'skip_download': True,
  278. },
  279. }, {
  280. # mediagen URL without query (e.g. http://videos.mtvnn.com/mediagen/e865da714c166d18d6f80893195fcb97)
  281. 'url': 'http://www.mtv.de/shows/933-teen-mom-2/staffeln/5353/folgen/63565-enthullungen',
  282. 'info_dict': {
  283. 'id': 'local_playlist-f5ae778b9832cc837189',
  284. 'ext': 'mp4',
  285. 'title': 'Episode_teen-mom-2_shows_season-5_episode-1_full-episode_part1',
  286. },
  287. 'params': {
  288. # rtmp download
  289. 'skip_download': True,
  290. },
  291. }, {
  292. # single video in pagePlaylist with different id
  293. 'url': 'http://www.mtv.de/news/77491-mtv-movies-spotlight-pixels-teil-3',
  294. 'info_dict': {
  295. 'id': 'local_playlist-4e760566473c4c8c5344',
  296. 'ext': 'mp4',
  297. 'title': 'Article_mtv-movies-spotlight-pixels-teil-3_short-clips_part1',
  298. 'description': 'MTV Movies Supercut',
  299. },
  300. 'params': {
  301. # rtmp download
  302. 'skip_download': True,
  303. },
  304. }]
  305. def _real_extract(self, url):
  306. video_id = self._match_id(url)
  307. webpage = self._download_webpage(url, video_id)
  308. playlist = self._parse_json(
  309. self._search_regex(
  310. r'window\.pagePlaylist\s*=\s*(\[.+?\]);\n', webpage, 'page playlist'),
  311. video_id)
  312. # news pages contain single video in playlist with different id
  313. if len(playlist) == 1:
  314. return self._get_videos_info_from_url(playlist[0]['mrss'], video_id)
  315. for item in playlist:
  316. item_id = item.get('id')
  317. if item_id and compat_str(item_id) == video_id:
  318. return self._get_videos_info_from_url(item['mrss'], video_id)