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.

277 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. @staticmethod
  23. def _id_from_uri(uri):
  24. return uri.split(':')[-1]
  25. # This was originally implemented for ComedyCentral, but it also works here
  26. @staticmethod
  27. def _transform_rtmp_url(rtmp_video_url):
  28. m = re.match(r'^rtmpe?://.*?/(?P<finalid>gsp\..+?/.*)$', rtmp_video_url)
  29. if not m:
  30. return rtmp_video_url
  31. base = 'http://viacommtvstrmfs.fplive.net/'
  32. return base + m.group('finalid')
  33. def _get_feed_url(self, uri):
  34. return self._FEED_URL
  35. def _get_thumbnail_url(self, uri, itemdoc):
  36. search_path = '%s/%s' % (_media_xml_tag('group'), _media_xml_tag('thumbnail'))
  37. thumb_node = itemdoc.find(search_path)
  38. if thumb_node is None:
  39. return None
  40. else:
  41. return thumb_node.attrib['url']
  42. def _extract_mobile_video_formats(self, mtvn_id):
  43. webpage_url = self._MOBILE_TEMPLATE % mtvn_id
  44. req = compat_urllib_request.Request(webpage_url)
  45. # Otherwise we get a webpage that would execute some javascript
  46. req.add_header('User-Agent', 'curl/7')
  47. webpage = self._download_webpage(req, mtvn_id,
  48. 'Downloading mobile page')
  49. metrics_url = unescapeHTML(self._search_regex(r'<a href="(http://metrics.+?)"', webpage, 'url'))
  50. req = HEADRequest(metrics_url)
  51. response = self._request_webpage(req, mtvn_id, 'Resolving url')
  52. url = response.geturl()
  53. # Transform the url to get the best quality:
  54. url = re.sub(r'.+pxE=mp4', 'http://mtvnmobile.vo.llnwd.net/kip0/_pxn=0+_pxK=18639+_pxE=mp4', url, 1)
  55. return [{'url': url, 'ext': 'mp4'}]
  56. def _extract_video_formats(self, mdoc, mtvn_id):
  57. if re.match(r'.*/(error_country_block\.swf|geoblock\.mp4)$', mdoc.find('.//src').text) is not None:
  58. if mtvn_id is not None and self._MOBILE_TEMPLATE is not None:
  59. self.to_screen('The normal version is not available from your '
  60. 'country, trying with the mobile version')
  61. return self._extract_mobile_video_formats(mtvn_id)
  62. raise ExtractorError('This video is not available from your country.',
  63. expected=True)
  64. formats = []
  65. for rendition in mdoc.findall('.//rendition'):
  66. try:
  67. _, _, ext = rendition.attrib['type'].partition('/')
  68. rtmp_video_url = rendition.find('./src').text
  69. if rtmp_video_url.endswith('siteunavail.png'):
  70. continue
  71. formats.append({
  72. 'ext': ext,
  73. 'url': self._transform_rtmp_url(rtmp_video_url),
  74. 'format_id': rendition.get('bitrate'),
  75. 'width': int(rendition.get('width')),
  76. 'height': int(rendition.get('height')),
  77. })
  78. except (KeyError, TypeError):
  79. raise ExtractorError('Invalid rendition field.')
  80. self._sort_formats(formats)
  81. return formats
  82. def _extract_subtitles(self, mdoc, mtvn_id):
  83. subtitles = {}
  84. for transcript in mdoc.findall('.//transcript'):
  85. if transcript.get('kind') != 'captions':
  86. continue
  87. lang = transcript.get('srclang')
  88. subtitles[lang] = [{
  89. 'url': compat_str(typographic.get('src')),
  90. 'ext': typographic.get('format')
  91. } for typographic in transcript.findall('./typographic')]
  92. return subtitles
  93. def _get_video_info(self, itemdoc):
  94. uri = itemdoc.find('guid').text
  95. video_id = self._id_from_uri(uri)
  96. self.report_extraction(video_id)
  97. mediagen_url = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content'))).attrib['url']
  98. # Remove the templates, like &device={device}
  99. mediagen_url = re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', mediagen_url)
  100. if 'acceptMethods' not in mediagen_url:
  101. mediagen_url += '&acceptMethods=fms'
  102. mediagen_doc = self._download_xml(mediagen_url, video_id,
  103. 'Downloading video urls')
  104. description_node = itemdoc.find('description')
  105. if description_node is not None:
  106. description = description_node.text.strip()
  107. else:
  108. description = None
  109. title_el = None
  110. if title_el is None:
  111. title_el = find_xpath_attr(
  112. itemdoc, './/{http://search.yahoo.com/mrss/}category',
  113. 'scheme', 'urn:mtvn:video_title')
  114. if title_el is None:
  115. title_el = itemdoc.find('.//{http://search.yahoo.com/mrss/}title')
  116. if title_el is None:
  117. title_el = itemdoc.find('.//title')
  118. if title_el.text is None:
  119. title_el = None
  120. title = title_el.text
  121. if title is None:
  122. raise ExtractorError('Could not find video title')
  123. title = title.strip()
  124. # This a short id that's used in the webpage urls
  125. mtvn_id = None
  126. mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
  127. 'scheme', 'urn:mtvn:id')
  128. if mtvn_id_node is not None:
  129. mtvn_id = mtvn_id_node.text
  130. return {
  131. 'title': title,
  132. 'formats': self._extract_video_formats(mediagen_doc, mtvn_id),
  133. 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
  134. 'id': video_id,
  135. 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
  136. 'description': description,
  137. }
  138. def _get_videos_info(self, uri):
  139. video_id = self._id_from_uri(uri)
  140. feed_url = self._get_feed_url(uri)
  141. data = compat_urllib_parse.urlencode({'uri': uri})
  142. idoc = self._download_xml(
  143. feed_url + '?' + data, video_id,
  144. 'Downloading info', transform_source=fix_xml_ampersands)
  145. return self.playlist_result(
  146. [self._get_video_info(item) for item in idoc.findall('.//item')])
  147. def _real_extract(self, url):
  148. title = url_basename(url)
  149. webpage = self._download_webpage(url, title)
  150. try:
  151. # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
  152. # or http://media.mtvnservices.com/{mgid}
  153. og_url = self._og_search_video_url(webpage)
  154. mgid = url_basename(og_url)
  155. if mgid.endswith('.swf'):
  156. mgid = mgid[:-4]
  157. except RegexNotFoundError:
  158. mgid = None
  159. if mgid is None or ':' not in mgid:
  160. mgid = self._search_regex(
  161. [r'data-mgid="(.*?)"', r'swfobject.embedSWF\(".*?(mgid:.*?)"'],
  162. webpage, 'mgid')
  163. videos_info = self._get_videos_info(mgid)
  164. return videos_info
  165. class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
  166. IE_NAME = 'mtvservices:embedded'
  167. _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
  168. _TEST = {
  169. # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
  170. 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
  171. 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
  172. 'info_dict': {
  173. 'id': '1043906',
  174. 'ext': 'mp4',
  175. 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
  176. 'description': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage as he tries summarizing "Game of Thrones" in under a minute.',
  177. },
  178. }
  179. def _get_feed_url(self, uri):
  180. video_id = self._id_from_uri(uri)
  181. site_id = uri.replace(video_id, '')
  182. config_url = ('http://media.mtvnservices.com/pmt/e1/players/{0}/'
  183. 'context4/context5/config.xml'.format(site_id))
  184. config_doc = self._download_xml(config_url, video_id)
  185. feed_node = config_doc.find('.//feed')
  186. feed_url = feed_node.text.strip().split('?')[0]
  187. return feed_url
  188. def _real_extract(self, url):
  189. mobj = re.match(self._VALID_URL, url)
  190. mgid = mobj.group('mgid')
  191. return self._get_videos_info(mgid)
  192. class MTVIE(MTVServicesInfoExtractor):
  193. _VALID_URL = r'''(?x)^https?://
  194. (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
  195. m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
  196. _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
  197. _TESTS = [
  198. {
  199. 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
  200. 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
  201. 'info_dict': {
  202. 'id': '853555',
  203. 'ext': 'mp4',
  204. 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
  205. 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
  206. },
  207. },
  208. ]
  209. def _get_thumbnail_url(self, uri, itemdoc):
  210. return 'http://mtv.mtvnimages.com/uri/' + uri
  211. def _real_extract(self, url):
  212. mobj = re.match(self._VALID_URL, url)
  213. video_id = mobj.group('videoid')
  214. uri = mobj.groupdict().get('mgid')
  215. if uri is None:
  216. webpage = self._download_webpage(url, video_id)
  217. # Some videos come from Vevo.com
  218. m_vevo = re.search(
  219. r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
  220. if m_vevo:
  221. vevo_id = m_vevo.group(1)
  222. self.to_screen('Vevo video detected: %s' % vevo_id)
  223. return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
  224. uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
  225. return self._get_videos_info(uri)
  226. class MTVIggyIE(MTVServicesInfoExtractor):
  227. IE_NAME = 'mtviggy.com'
  228. _VALID_URL = r'https?://www\.mtviggy\.com/videos/.+'
  229. _TEST = {
  230. 'url': 'http://www.mtviggy.com/videos/arcade-fire-behind-the-scenes-at-the-biggest-music-experiment-yet/',
  231. 'info_dict': {
  232. 'id': '984696',
  233. 'ext': 'mp4',
  234. 'title': 'Arcade Fire: Behind the Scenes at the Biggest Music Experiment Yet',
  235. }
  236. }
  237. _FEED_URL = 'http://all.mtvworldverticals.com/feed-xml/'