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.

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