vevo.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. from __future__ import unicode_literals
  2. import re
  3. from .common import InfoExtractor
  4. from ..compat import compat_etree_fromstring
  5. from ..utils import (
  6. ExtractorError,
  7. int_or_none,
  8. sanitized_Request,
  9. )
  10. class VevoIE(InfoExtractor):
  11. """
  12. Accepts urls from vevo.com or in the format 'vevo:{id}'
  13. (currently used by MTVIE and MySpaceIE)
  14. """
  15. _VALID_URL = r'''(?x)
  16. (?:https?://www\.vevo\.com/watch/(?:[^/]+/(?:[^/]+/)?)?|
  17. https?://cache\.vevo\.com/m/html/embed\.html\?video=|
  18. https?://videoplayer\.vevo\.com/embed/embedded\?videoId=|
  19. vevo:)
  20. (?P<id>[^&?#]+)'''
  21. _TESTS = [{
  22. 'url': 'http://www.vevo.com/watch/hurts/somebody-to-die-for/GB1101300280',
  23. "md5": "95ee28ee45e70130e3ab02b0f579ae23",
  24. 'info_dict': {
  25. 'id': 'GB1101300280',
  26. 'ext': 'mp4',
  27. "upload_date": "20130624",
  28. "uploader": "Hurts",
  29. "title": "Somebody to Die For",
  30. "duration": 230.12,
  31. "width": 1920,
  32. "height": 1080,
  33. # timestamp and upload_date are often incorrect; seem to change randomly
  34. 'timestamp': int,
  35. }
  36. }, {
  37. 'note': 'v3 SMIL format',
  38. 'url': 'http://www.vevo.com/watch/cassadee-pope/i-wish-i-could-break-your-heart/USUV71302923',
  39. 'md5': 'f6ab09b034f8c22969020b042e5ac7fc',
  40. 'info_dict': {
  41. 'id': 'USUV71302923',
  42. 'ext': 'mp4',
  43. 'upload_date': '20140219',
  44. 'uploader': 'Cassadee Pope',
  45. 'title': 'I Wish I Could Break Your Heart',
  46. 'duration': 226.101,
  47. 'age_limit': 0,
  48. 'timestamp': int,
  49. }
  50. }, {
  51. 'note': 'Age-limited video',
  52. 'url': 'https://www.vevo.com/watch/justin-timberlake/tunnel-vision-explicit/USRV81300282',
  53. 'info_dict': {
  54. 'id': 'USRV81300282',
  55. 'ext': 'mp4',
  56. 'age_limit': 18,
  57. 'title': 'Tunnel Vision (Explicit)',
  58. 'uploader': 'Justin Timberlake',
  59. 'upload_date': 're:2013070[34]',
  60. 'timestamp': int,
  61. },
  62. 'params': {
  63. 'skip_download': 'true',
  64. }
  65. }, {
  66. 'note': 'No video_info',
  67. 'url': 'http://www.vevo.com/watch/k-camp-1/Till-I-Die/USUV71503000',
  68. 'md5': '8b83cc492d72fc9cf74a02acee7dc1b0',
  69. 'info_dict': {
  70. 'id': 'USUV71503000',
  71. 'ext': 'mp4',
  72. 'title': 'Till I Die - K Camp ft. T.I.',
  73. 'duration': 193,
  74. },
  75. 'expected_warnings': ['HTTP Error 404'],
  76. }]
  77. _SMIL_BASE_URL = 'http://smil.lvl3.vevo.com/'
  78. def _real_initialize(self):
  79. req = sanitized_Request(
  80. 'http://www.vevo.com/auth', data=b'')
  81. webpage = self._download_webpage(
  82. req, None,
  83. note='Retrieving oauth token',
  84. errnote='Unable to retrieve oauth token',
  85. fatal=False)
  86. if webpage is False:
  87. self._oauth_token = None
  88. else:
  89. if 'THIS PAGE IS CURRENTLY UNAVAILABLE IN YOUR REGION' in webpage:
  90. raise ExtractorError('%s said: This page is currently unavailable in your region.' % self.IE_NAME, expected=True)
  91. self._oauth_token = self._search_regex(
  92. r'access_token":\s*"([^"]+)"',
  93. webpage, 'access token', fatal=False)
  94. def _formats_from_json(self, video_info):
  95. if not video_info:
  96. return []
  97. last_version = {'version': -1}
  98. for version in video_info['videoVersions']:
  99. # These are the HTTP downloads, other types are for different manifests
  100. if version['sourceType'] == 2:
  101. if version['version'] > last_version['version']:
  102. last_version = version
  103. if last_version['version'] == -1:
  104. raise ExtractorError('Unable to extract last version of the video')
  105. renditions = compat_etree_fromstring(last_version['data'])
  106. formats = []
  107. # Already sorted from worst to best quality
  108. for rend in renditions.findall('rendition'):
  109. attr = rend.attrib
  110. format_note = '%(videoCodec)s@%(videoBitrate)4sk, %(audioCodec)s@%(audioBitrate)3sk' % attr
  111. formats.append({
  112. 'url': attr['url'],
  113. 'format_id': attr['name'],
  114. 'format_note': format_note,
  115. 'height': int(attr['frameheight']),
  116. 'width': int(attr['frameWidth']),
  117. })
  118. return formats
  119. def _formats_from_smil(self, smil_xml):
  120. formats = []
  121. smil_doc = compat_etree_fromstring(smil_xml.encode('utf-8'))
  122. els = smil_doc.findall('.//{http://www.w3.org/2001/SMIL20/Language}video')
  123. for el in els:
  124. src = el.attrib['src']
  125. m = re.match(r'''(?xi)
  126. (?P<ext>[a-z0-9]+):
  127. (?P<path>
  128. [/a-z0-9]+ # The directory and main part of the URL
  129. _(?P<cbr>[0-9]+)k
  130. _(?P<width>[0-9]+)x(?P<height>[0-9]+)
  131. _(?P<vcodec>[a-z0-9]+)
  132. _(?P<vbr>[0-9]+)
  133. _(?P<acodec>[a-z0-9]+)
  134. _(?P<abr>[0-9]+)
  135. \.[a-z0-9]+ # File extension
  136. )''', src)
  137. if not m:
  138. continue
  139. format_url = self._SMIL_BASE_URL + m.group('path')
  140. formats.append({
  141. 'url': format_url,
  142. 'format_id': 'SMIL_' + m.group('cbr'),
  143. 'vcodec': m.group('vcodec'),
  144. 'acodec': m.group('acodec'),
  145. 'vbr': int(m.group('vbr')),
  146. 'abr': int(m.group('abr')),
  147. 'ext': m.group('ext'),
  148. 'width': int(m.group('width')),
  149. 'height': int(m.group('height')),
  150. })
  151. return formats
  152. def _download_api_formats(self, video_id):
  153. if not self._oauth_token:
  154. self._downloader.report_warning(
  155. 'No oauth token available, skipping API HLS download')
  156. return []
  157. api_url = 'https://apiv2.vevo.com/video/%s/streams/hls?token=%s' % (
  158. video_id, self._oauth_token)
  159. api_data = self._download_json(
  160. api_url, video_id,
  161. note='Downloading HLS formats',
  162. errnote='Failed to download HLS format list', fatal=False)
  163. if api_data is None:
  164. return []
  165. m3u8_url = api_data[0]['url']
  166. return self._extract_m3u8_formats(
  167. m3u8_url, video_id, entry_protocol='m3u8_native', ext='mp4',
  168. preference=0)
  169. def _real_extract(self, url):
  170. video_id = self._match_id(url)
  171. webpage = None
  172. json_url = 'http://videoplayer.vevo.com/VideoService/AuthenticateVideo?isrc=%s' % video_id
  173. response = self._download_json(json_url, video_id)
  174. video_info = response['video'] or {}
  175. if not video_info and response.get('statusCode') != 909:
  176. if 'statusMessage' in response:
  177. raise ExtractorError('%s said: %s' % (self.IE_NAME, response['statusMessage']), expected=True)
  178. raise ExtractorError('Unable to extract videos')
  179. if not video_info:
  180. if url.startswith('vevo:'):
  181. raise ExtractorError('Please specify full Vevo URL for downloading', expected=True)
  182. webpage = self._download_webpage(url, video_id)
  183. title = video_info.get('title') or self._og_search_title(webpage)
  184. formats = self._formats_from_json(video_info)
  185. is_explicit = video_info.get('isExplicit')
  186. if is_explicit is True:
  187. age_limit = 18
  188. elif is_explicit is False:
  189. age_limit = 0
  190. else:
  191. age_limit = None
  192. # Download via HLS API
  193. formats.extend(self._download_api_formats(video_id))
  194. # Download SMIL
  195. smil_blocks = sorted((
  196. f for f in video_info.get('videoVersions', [])
  197. if f['sourceType'] == 13),
  198. key=lambda f: f['version'])
  199. smil_url = '%s/Video/V2/VFILE/%s/%sr.smil' % (
  200. self._SMIL_BASE_URL, video_id, video_id.lower())
  201. if smil_blocks:
  202. smil_url_m = self._search_regex(
  203. r'url="([^"]+)"', smil_blocks[-1]['data'], 'SMIL URL',
  204. default=None)
  205. if smil_url_m is not None:
  206. smil_url = smil_url_m
  207. if smil_url:
  208. smil_xml = self._download_webpage(
  209. smil_url, video_id, 'Downloading SMIL info', fatal=False)
  210. if smil_xml:
  211. formats.extend(self._formats_from_smil(smil_xml))
  212. self._sort_formats(formats)
  213. timestamp = int_or_none(self._search_regex(
  214. r'/Date\((\d+)\)/',
  215. video_info['launchDate'], 'launch date', fatal=False),
  216. scale=1000) if video_info else None
  217. duration = video_info.get('duration') or int_or_none(
  218. self._html_search_meta('video:duration', webpage))
  219. return {
  220. 'id': video_id,
  221. 'title': title,
  222. 'formats': formats,
  223. 'thumbnail': video_info.get('imageUrl'),
  224. 'timestamp': timestamp,
  225. 'uploader': video_info['mainArtists'][0]['artistName'] if video_info else None,
  226. 'duration': duration,
  227. 'age_limit': age_limit,
  228. }