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.

290 lines
11 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)$', 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 += '&acceptMethods=fms'
  103. mediagen_doc = self._download_xml(mediagen_url, video_id,
  104. 'Downloading video urls')
  105. item = mediagen_doc.find('./video/item')
  106. if item is not None and item.get('type') == 'text':
  107. message = '%s returned error: ' % self.IE_NAME
  108. if item.get('code') is not None:
  109. message += '%s - ' % item.get('code')
  110. message += item.text
  111. raise ExtractorError(message, expected=True)
  112. description_node = itemdoc.find('description')
  113. if description_node is not None:
  114. description = description_node.text.strip()
  115. else:
  116. description = None
  117. title_el = None
  118. if title_el is None:
  119. title_el = find_xpath_attr(
  120. itemdoc, './/{http://search.yahoo.com/mrss/}category',
  121. 'scheme', 'urn:mtvn:video_title')
  122. if title_el is None:
  123. title_el = itemdoc.find('.//{http://search.yahoo.com/mrss/}title')
  124. if title_el is None:
  125. title_el = itemdoc.find('.//title')
  126. if title_el.text is None:
  127. title_el = None
  128. title = title_el.text
  129. if title is None:
  130. raise ExtractorError('Could not find video title')
  131. title = title.strip()
  132. # This a short id that's used in the webpage urls
  133. mtvn_id = None
  134. mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
  135. 'scheme', 'urn:mtvn:id')
  136. if mtvn_id_node is not None:
  137. mtvn_id = mtvn_id_node.text
  138. return {
  139. 'title': title,
  140. 'formats': self._extract_video_formats(mediagen_doc, mtvn_id),
  141. 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
  142. 'id': video_id,
  143. 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
  144. 'description': description,
  145. }
  146. def _get_videos_info(self, uri):
  147. video_id = self._id_from_uri(uri)
  148. feed_url = self._get_feed_url(uri)
  149. data = compat_urllib_parse.urlencode({'uri': uri})
  150. info_url = feed_url + '?'
  151. if self._LANG:
  152. info_url += 'lang=%s&' % self._LANG
  153. info_url += data
  154. idoc = self._download_xml(
  155. info_url, video_id,
  156. 'Downloading info', transform_source=fix_xml_ampersands)
  157. return self.playlist_result(
  158. [self._get_video_info(item) for item in idoc.findall('.//item')])
  159. def _real_extract(self, url):
  160. title = url_basename(url)
  161. webpage = self._download_webpage(url, title)
  162. try:
  163. # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
  164. # or http://media.mtvnservices.com/{mgid}
  165. og_url = self._og_search_video_url(webpage)
  166. mgid = url_basename(og_url)
  167. if mgid.endswith('.swf'):
  168. mgid = mgid[:-4]
  169. except RegexNotFoundError:
  170. mgid = None
  171. if mgid is None or ':' not in mgid:
  172. mgid = self._search_regex(
  173. [r'data-mgid="(.*?)"', r'swfobject.embedSWF\(".*?(mgid:.*?)"'],
  174. webpage, 'mgid')
  175. videos_info = self._get_videos_info(mgid)
  176. return videos_info
  177. class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
  178. IE_NAME = 'mtvservices:embedded'
  179. _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
  180. _TEST = {
  181. # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
  182. 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
  183. 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
  184. 'info_dict': {
  185. 'id': '1043906',
  186. 'ext': 'mp4',
  187. 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
  188. 'description': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage as he tries summarizing "Game of Thrones" in under a minute.',
  189. },
  190. }
  191. def _get_feed_url(self, uri):
  192. video_id = self._id_from_uri(uri)
  193. site_id = uri.replace(video_id, '')
  194. config_url = ('http://media.mtvnservices.com/pmt/e1/players/{0}/'
  195. 'context4/context5/config.xml'.format(site_id))
  196. config_doc = self._download_xml(config_url, video_id)
  197. feed_node = config_doc.find('.//feed')
  198. feed_url = feed_node.text.strip().split('?')[0]
  199. return feed_url
  200. def _real_extract(self, url):
  201. mobj = re.match(self._VALID_URL, url)
  202. mgid = mobj.group('mgid')
  203. return self._get_videos_info(mgid)
  204. class MTVIE(MTVServicesInfoExtractor):
  205. _VALID_URL = r'''(?x)^https?://
  206. (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
  207. m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
  208. _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
  209. _TESTS = [
  210. {
  211. 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
  212. 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
  213. 'info_dict': {
  214. 'id': '853555',
  215. 'ext': 'mp4',
  216. 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
  217. 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
  218. },
  219. },
  220. ]
  221. def _get_thumbnail_url(self, uri, itemdoc):
  222. return 'http://mtv.mtvnimages.com/uri/' + uri
  223. def _real_extract(self, url):
  224. mobj = re.match(self._VALID_URL, url)
  225. video_id = mobj.group('videoid')
  226. uri = mobj.groupdict().get('mgid')
  227. if uri is None:
  228. webpage = self._download_webpage(url, video_id)
  229. # Some videos come from Vevo.com
  230. m_vevo = re.search(
  231. r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
  232. if m_vevo:
  233. vevo_id = m_vevo.group(1)
  234. self.to_screen('Vevo video detected: %s' % vevo_id)
  235. return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
  236. uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
  237. return self._get_videos_info(uri)
  238. class MTVIggyIE(MTVServicesInfoExtractor):
  239. IE_NAME = 'mtviggy.com'
  240. _VALID_URL = r'https?://www\.mtviggy\.com/videos/.+'
  241. _TEST = {
  242. 'url': 'http://www.mtviggy.com/videos/arcade-fire-behind-the-scenes-at-the-biggest-music-experiment-yet/',
  243. 'info_dict': {
  244. 'id': '984696',
  245. 'ext': 'mp4',
  246. 'title': 'Arcade Fire: Behind the Scenes at the Biggest Music Experiment Yet',
  247. }
  248. }
  249. _FEED_URL = 'http://all.mtvworldverticals.com/feed-xml/'