mtv.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. return self._get_videos_info_from_url(info_url, video_id)
  155. def _get_videos_info_from_url(self, url, video_id):
  156. idoc = self._download_xml(
  157. url, video_id,
  158. 'Downloading info', transform_source=fix_xml_ampersands)
  159. return self.playlist_result(
  160. [self._get_video_info(item) for item in idoc.findall('.//item')])
  161. def _real_extract(self, url):
  162. title = url_basename(url)
  163. webpage = self._download_webpage(url, title)
  164. try:
  165. # the url can be http://media.mtvnservices.com/fb/{mgid}.swf
  166. # or http://media.mtvnservices.com/{mgid}
  167. og_url = self._og_search_video_url(webpage)
  168. mgid = url_basename(og_url)
  169. if mgid.endswith('.swf'):
  170. mgid = mgid[:-4]
  171. except RegexNotFoundError:
  172. mgid = None
  173. if mgid is None or ':' not in mgid:
  174. mgid = self._search_regex(
  175. [r'data-mgid="(.*?)"', r'swfobject.embedSWF\(".*?(mgid:.*?)"'],
  176. webpage, 'mgid')
  177. videos_info = self._get_videos_info(mgid)
  178. return videos_info
  179. class MTVServicesEmbeddedIE(MTVServicesInfoExtractor):
  180. IE_NAME = 'mtvservices:embedded'
  181. _VALID_URL = r'https?://media\.mtvnservices\.com/embed/(?P<mgid>.+?)(\?|/|$)'
  182. _TEST = {
  183. # From http://www.thewrap.com/peter-dinklage-sums-up-game-of-thrones-in-45-seconds-video/
  184. 'url': 'http://media.mtvnservices.com/embed/mgid:uma:video:mtv.com:1043906/cp~vid%3D1043906%26uri%3Dmgid%3Auma%3Avideo%3Amtv.com%3A1043906',
  185. 'md5': 'cb349b21a7897164cede95bd7bf3fbb9',
  186. 'info_dict': {
  187. 'id': '1043906',
  188. 'ext': 'mp4',
  189. 'title': 'Peter Dinklage Sums Up \'Game Of Thrones\' In 45 Seconds',
  190. 'description': '"Sexy sexy sexy, stabby stabby stabby, beautiful language," says Peter Dinklage as he tries summarizing "Game of Thrones" in under a minute.',
  191. },
  192. }
  193. def _get_feed_url(self, uri):
  194. video_id = self._id_from_uri(uri)
  195. site_id = uri.replace(video_id, '')
  196. config_url = ('http://media.mtvnservices.com/pmt/e1/players/{0}/'
  197. 'context4/context5/config.xml'.format(site_id))
  198. config_doc = self._download_xml(config_url, video_id)
  199. feed_node = config_doc.find('.//feed')
  200. feed_url = feed_node.text.strip().split('?')[0]
  201. return feed_url
  202. def _real_extract(self, url):
  203. mobj = re.match(self._VALID_URL, url)
  204. mgid = mobj.group('mgid')
  205. return self._get_videos_info(mgid)
  206. class MTVIE(MTVServicesInfoExtractor):
  207. _VALID_URL = r'''(?x)^https?://
  208. (?:(?:www\.)?mtv\.com/videos/.+?/(?P<videoid>[0-9]+)/[^/]+$|
  209. m\.mtv\.com/videos/video\.rbml\?.*?id=(?P<mgid>[^&]+))'''
  210. _FEED_URL = 'http://www.mtv.com/player/embed/AS3/rss/'
  211. _TESTS = [
  212. {
  213. 'url': 'http://www.mtv.com/videos/misc/853555/ours-vh1-storytellers.jhtml',
  214. 'md5': '850f3f143316b1e71fa56a4edfd6e0f8',
  215. 'info_dict': {
  216. 'id': '853555',
  217. 'ext': 'mp4',
  218. 'title': 'Taylor Swift - "Ours (VH1 Storytellers)"',
  219. 'description': 'Album: Taylor Swift performs "Ours" for VH1 Storytellers at Harvey Mudd College.',
  220. },
  221. },
  222. ]
  223. def _get_thumbnail_url(self, uri, itemdoc):
  224. return 'http://mtv.mtvnimages.com/uri/' + uri
  225. def _real_extract(self, url):
  226. mobj = re.match(self._VALID_URL, url)
  227. video_id = mobj.group('videoid')
  228. uri = mobj.groupdict().get('mgid')
  229. if uri is None:
  230. webpage = self._download_webpage(url, video_id)
  231. # Some videos come from Vevo.com
  232. m_vevo = re.search(
  233. r'(?s)isVevoVideo = true;.*?vevoVideoId = "(.*?)";', webpage)
  234. if m_vevo:
  235. vevo_id = m_vevo.group(1)
  236. self.to_screen('Vevo video detected: %s' % vevo_id)
  237. return self.url_result('vevo:%s' % vevo_id, ie='Vevo')
  238. uri = self._html_search_regex(r'/uri/(.*?)\?', webpage, 'uri')
  239. return self._get_videos_info(uri)
  240. class MTVIggyIE(MTVServicesInfoExtractor):
  241. IE_NAME = 'mtviggy.com'
  242. _VALID_URL = r'https?://www\.mtviggy\.com/videos/.+'
  243. _TEST = {
  244. 'url': 'http://www.mtviggy.com/videos/arcade-fire-behind-the-scenes-at-the-biggest-music-experiment-yet/',
  245. 'info_dict': {
  246. 'id': '984696',
  247. 'ext': 'mp4',
  248. 'title': 'Arcade Fire: Behind the Scenes at the Biggest Music Experiment Yet',
  249. }
  250. }
  251. _FEED_URL = 'http://all.mtvworldverticals.com/feed-xml/'
  252. class MTVDEIE(MTVServicesInfoExtractor):
  253. IE_NAME = 'mtv.de'
  254. _VALID_URL = r'https?://(?:www\.)?mtv\.de/(?:artists|shows)/(?:[^/]+/)+(?P<id>\d+)-[^/#?]+/*(?:[#?].*)?$'
  255. _TESTS = [{
  256. 'url': 'http://www.mtv.de/artists/10571-cro/videos/61131-traum',
  257. 'info_dict': {
  258. 'id': 'music_video-a50bc5f0b3aa4b3190aa',
  259. 'ext': 'mp4',
  260. 'title': 'MusicVideo_cro-traum',
  261. 'description': 'Cro - Traum',
  262. },
  263. 'params': {
  264. # rtmp download
  265. 'skip_download': True,
  266. },
  267. }]
  268. def _real_extract(self, url):
  269. video_id = self._match_id(url)
  270. webpage = self._download_webpage(url, video_id)
  271. playlist = self._parse_json(
  272. self._search_regex(
  273. r'window\.pagePlaylist\s*=\s*(\[.+?\]);\n', webpage, 'page playlist'),
  274. video_id)
  275. for item in playlist:
  276. item_id = item.get('id')
  277. if item_id and compat_str(item_id) == video_id:
  278. return self._get_videos_info_from_url(item['mrss'], video_id)