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.

289 lines
11 KiB

10 years ago
10 years ago
10 years ago
  1. from __future__ import unicode_literals
  2. import re
  3. from .subtitles import SubtitlesInfoExtractor
  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(SubtitlesInfoExtractor):
  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. FORMATS = {
  85. 'scc': 'cea-608',
  86. 'eia-608': 'cea-608',
  87. 'xml': 'ttml',
  88. }
  89. subtitles_format = FORMATS.get(
  90. self._downloader.params.get('subtitlesformat'), 'ttml')
  91. for transcript in mdoc.findall('.//transcript'):
  92. if transcript.get('kind') != 'captions':
  93. continue
  94. lang = transcript.get('srclang')
  95. for typographic in transcript.findall('./typographic'):
  96. captions_format = typographic.get('format')
  97. if captions_format == subtitles_format:
  98. subtitles[lang] = compat_str(typographic.get('src'))
  99. break
  100. if self._downloader.params.get('listsubtitles', False):
  101. self._list_available_subtitles(mtvn_id, subtitles)
  102. return self.extract_subtitles(mtvn_id, subtitles)
  103. def _get_video_info(self, itemdoc):
  104. uri = itemdoc.find('guid').text
  105. video_id = self._id_from_uri(uri)
  106. self.report_extraction(video_id)
  107. mediagen_url = itemdoc.find('%s/%s' % (_media_xml_tag('group'), _media_xml_tag('content'))).attrib['url']
  108. # Remove the templates, like &device={device}
  109. mediagen_url = re.sub(r'&[^=]*?={.*?}(?=(&|$))', '', mediagen_url)
  110. if 'acceptMethods' not in mediagen_url:
  111. mediagen_url += '&acceptMethods=fms'
  112. mediagen_doc = self._download_xml(mediagen_url, video_id,
  113. 'Downloading video urls')
  114. description_node = itemdoc.find('description')
  115. if description_node is not None:
  116. description = description_node.text.strip()
  117. else:
  118. description = None
  119. title_el = None
  120. if title_el is None:
  121. title_el = find_xpath_attr(
  122. itemdoc, './/{http://search.yahoo.com/mrss/}category',
  123. 'scheme', 'urn:mtvn:video_title')
  124. if title_el is None:
  125. title_el = itemdoc.find('.//{http://search.yahoo.com/mrss/}title')
  126. if title_el is None:
  127. title_el = itemdoc.find('.//title')
  128. if title_el.text is None:
  129. title_el = None
  130. title = title_el.text
  131. if title is None:
  132. raise ExtractorError('Could not find video title')
  133. title = title.strip()
  134. # This a short id that's used in the webpage urls
  135. mtvn_id = None
  136. mtvn_id_node = find_xpath_attr(itemdoc, './/{http://search.yahoo.com/mrss/}category',
  137. 'scheme', 'urn:mtvn:id')
  138. if mtvn_id_node is not None:
  139. mtvn_id = mtvn_id_node.text
  140. return {
  141. 'title': title,
  142. 'formats': self._extract_video_formats(mediagen_doc, mtvn_id),
  143. 'subtitles': self._extract_subtitles(mediagen_doc, mtvn_id),
  144. 'id': video_id,
  145. 'thumbnail': self._get_thumbnail_url(uri, itemdoc),
  146. 'description': description,
  147. }
  148. def _get_videos_info(self, uri):
  149. video_id = self._id_from_uri(uri)
  150. feed_url = self._get_feed_url(uri)
  151. data = compat_urllib_parse.urlencode({'uri': uri})
  152. idoc = self._download_xml(
  153. feed_url + '?' + data, video_id,
  154. 'Downloading info', transform_source=fix_xml_ampersands)
  155. return self.playlist_result(
  156. [self._get_video_info(item) for item in idoc.findall('.//item')])
  157. def _real_extract(self, url):
  158. title = url_basename(url)
  159. webpage = self._download_webpage(url, title)
  160. try:
  161. # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
  162. # or http://media.mtvnservices.com/{mgid}
  163. og_url = self._og_search_video_url(webpage)
  164. mgid = url_basename(og_url)
  165. if mgid.endswith('.swf'):
  166. mgid = mgid[:-4]
  167. except RegexNotFoundError:
  168. mgid = None
  169. if mgid is None or ':' not in mgid:
  170. mgid = self._search_regex(
  171. [r'data-mgid="(.*?)"', r'swfobject.embedSWF\(".*?(mgid:.*?)"'],
  172. webpage, 'mgid')
  173. videos_info = self._get_videos_info(mgid)
  174. if self._downloader.params.get('listsubtitles', False):
  175. return
  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/'