vevo.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. from __future__ import unicode_literals
  2. import re
  3. from .common import InfoExtractor
  4. from ..compat import (
  5. compat_etree_fromstring,
  6. compat_urlparse,
  7. )
  8. from ..utils import (
  9. ExtractorError,
  10. int_or_none,
  11. sanitized_Request,
  12. parse_iso8601,
  13. )
  14. class VevoIE(InfoExtractor):
  15. '''
  16. Accepts urls from vevo.com or in the format 'vevo:{id}'
  17. (currently used by MTVIE and MySpaceIE)
  18. '''
  19. _VALID_URL = r'''(?x)
  20. (?:https?://www\.vevo\.com/watch/(?!playlist|genre)(?:[^/]+/(?:[^/]+/)?)?|
  21. https?://cache\.vevo\.com/m/html/embed\.html\?video=|
  22. https?://videoplayer\.vevo\.com/embed/embedded\?videoId=|
  23. vevo:)
  24. (?P<id>[^&?#]+)'''
  25. _TESTS = [{
  26. 'url': 'http://www.vevo.com/watch/hurts/somebody-to-die-for/GB1101300280',
  27. 'md5': '95ee28ee45e70130e3ab02b0f579ae23',
  28. 'info_dict': {
  29. 'id': 'GB1101300280',
  30. 'ext': 'mp4',
  31. 'title': 'Somebody to Die For',
  32. 'upload_date': '20130624',
  33. 'uploader': 'Hurts',
  34. 'timestamp': 1372057200,
  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. 'title': 'I Wish I Could Break Your Heart',
  44. 'upload_date': '20140219',
  45. 'uploader': 'Cassadee Pope',
  46. 'timestamp': 1392796919,
  47. },
  48. }, {
  49. 'note': 'Age-limited video',
  50. 'url': 'https://www.vevo.com/watch/justin-timberlake/tunnel-vision-explicit/USRV81300282',
  51. 'info_dict': {
  52. 'id': 'USRV81300282',
  53. 'ext': 'mp4',
  54. 'title': 'Tunnel Vision (Explicit)',
  55. 'upload_date': '20130703',
  56. 'age_limit': 18,
  57. 'uploader': 'Justin Timberlake',
  58. 'timestamp': 1372888800,
  59. },
  60. }, {
  61. 'note': 'No video_info',
  62. 'url': 'http://www.vevo.com/watch/k-camp-1/Till-I-Die/USUV71503000',
  63. 'md5': '8b83cc492d72fc9cf74a02acee7dc1b0',
  64. 'info_dict': {
  65. 'id': 'USUV71503000',
  66. 'ext': 'mp4',
  67. 'title': 'Till I Die',
  68. 'upload_date': '20151207',
  69. 'age_limit': 18,
  70. 'uploader': 'K Camp',
  71. 'timestamp': 1449468000,
  72. },
  73. }]
  74. _SMIL_BASE_URL = 'http://smil.lvl3.vevo.com'
  75. _SOURCE_TYPES = {
  76. 0: 'youtube',
  77. 1: 'brightcove',
  78. 2: 'http',
  79. 3: 'hls_ios',
  80. 4: 'hls',
  81. 5: 'smil', # http
  82. 7: 'f4m_cc',
  83. 8: 'f4m_ak',
  84. 9: 'f4m_l3',
  85. 10: 'ism',
  86. 13: 'smil', # rtmp
  87. 18: 'dash',
  88. }
  89. _VERSIONS = {
  90. 0: 'youtube', # only in AuthenticateVideo videoVersions
  91. 1: 'level3',
  92. 2: 'akamai',
  93. 3: 'level3',
  94. 4: 'amazon',
  95. }
  96. def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  97. formats = []
  98. els = smil.findall('.//{http://www.w3.org/2001/SMIL20/Language}video')
  99. for el in els:
  100. src = el.attrib['src']
  101. m = re.match(r'''(?xi)
  102. (?P<ext>[a-z0-9]+):
  103. (?P<path>
  104. [/a-z0-9]+ # The directory and main part of the URL
  105. _(?P<tbr>[0-9]+)k
  106. _(?P<width>[0-9]+)x(?P<height>[0-9]+)
  107. _(?P<vcodec>[a-z0-9]+)
  108. _(?P<vbr>[0-9]+)
  109. _(?P<acodec>[a-z0-9]+)
  110. _(?P<abr>[0-9]+)
  111. \.[a-z0-9]+ # File extension
  112. )''', src)
  113. if not m:
  114. continue
  115. format_url = self._SMIL_BASE_URL + m.group('path')
  116. formats.append({
  117. 'url': format_url,
  118. 'format_id': 'smil_' + m.group('tbr'),
  119. 'vcodec': m.group('vcodec'),
  120. 'acodec': m.group('acodec'),
  121. 'tbr': int(m.group('tbr')),
  122. 'vbr': int(m.group('vbr')),
  123. 'abr': int(m.group('abr')),
  124. 'ext': m.group('ext'),
  125. 'width': int(m.group('width')),
  126. 'height': int(m.group('height')),
  127. })
  128. return formats
  129. def _initialize_api(self, video_id):
  130. req = sanitized_Request(
  131. 'http://www.vevo.com/auth', data=b'')
  132. webpage = self._download_webpage(
  133. req, None,
  134. note='Retrieving oauth token',
  135. errnote='Unable to retrieve oauth token')
  136. if 'THIS PAGE IS CURRENTLY UNAVAILABLE IN YOUR REGION' in webpage:
  137. raise ExtractorError(
  138. '%s said: This page is currently unavailable in your region.' % self.IE_NAME, expected=True)
  139. auth_info = self._parse_json(webpage, video_id)
  140. self._api_url_template = self.http_scheme() + '//apiv2.vevo.com/%s?token=' + auth_info['access_token']
  141. def _call_api(self, path, *args, **kwargs):
  142. return self._download_json(self._api_url_template % path, *args, **kwargs)
  143. def _real_extract(self, url):
  144. video_id = self._match_id(url)
  145. json_url = 'http://api.vevo.com/VideoService/AuthenticateVideo?isrc=%s' % video_id
  146. response = self._download_json(
  147. json_url, video_id, 'Downloading video info', 'Unable to download info')
  148. video_info = response.get('video') or {}
  149. video_versions = video_info.get('videoVersions')
  150. uploader = None
  151. timestamp = None
  152. view_count = None
  153. formats = []
  154. if not video_info:
  155. if response.get('statusCode') != 909:
  156. ytid = response.get('errorInfo', {}).get('ytid')
  157. if ytid:
  158. self.report_warning(
  159. 'Video is geoblocked, trying with the YouTube video %s' % ytid)
  160. return self.url_result(ytid, 'Youtube', ytid)
  161. if 'statusMessage' in response:
  162. raise ExtractorError('%s said: %s' % (
  163. self.IE_NAME, response['statusMessage']), expected=True)
  164. raise ExtractorError('Unable to extract videos')
  165. self._initialize_api(video_id)
  166. video_info = self._call_api(
  167. 'video/%s' % video_id, video_id, 'Downloading api video info',
  168. 'Failed to download video info')
  169. video_versions = self._call_api(
  170. 'video/%s/streams' % video_id, video_id,
  171. 'Downloading video versions info',
  172. 'Failed to download video versions info')
  173. timestamp = parse_iso8601(video_info.get('releaseDate'))
  174. artists = video_info.get('artists')
  175. if artists:
  176. uploader = artists[0]['name']
  177. view_count = int_or_none(video_info.get('views', {}).get('total'))
  178. for video_version in video_versions:
  179. version = self._VERSIONS.get(video_version['version'])
  180. version_url = video_version.get('url')
  181. if not version_url:
  182. continue
  183. if '.ism' in version_url:
  184. continue
  185. elif '.mpd' in version_url:
  186. formats.extend(self._extract_mpd_formats(
  187. version_url, video_id, mpd_id='dash-%s' % version,
  188. note='Downloading %s MPD information' % version,
  189. errnote='Failed to download %s MPD information' % version,
  190. fatal=False))
  191. elif '.m3u8' in version_url:
  192. formats.extend(self._extract_m3u8_formats(
  193. version_url, video_id, 'mp4', 'm3u8_native',
  194. m3u8_id='hls-%s' % version,
  195. note='Downloading %s m3u8 information' % version,
  196. errnote='Failed to download %s m3u8 information' % version,
  197. fatal=False))
  198. else:
  199. m = re.search(r'''(?xi)
  200. _(?P<width>[0-9]+)x(?P<height>[0-9]+)
  201. _(?P<vcodec>[a-z0-9]+)
  202. _(?P<vbr>[0-9]+)
  203. _(?P<acodec>[a-z0-9]+)
  204. _(?P<abr>[0-9]+)
  205. \.(?P<ext>[a-z0-9]+)''', version_url)
  206. if not m:
  207. continue
  208. formats.append({
  209. 'url': version_url,
  210. 'format_id': 'http-%s-%s' % (version, video_version['quality']),
  211. 'vcodec': m.group('vcodec'),
  212. 'acodec': m.group('acodec'),
  213. 'vbr': int(m.group('vbr')),
  214. 'abr': int(m.group('abr')),
  215. 'ext': m.group('ext'),
  216. 'width': int(m.group('width')),
  217. 'height': int(m.group('height')),
  218. })
  219. else:
  220. timestamp = int_or_none(self._search_regex(
  221. r'/Date\((\d+)\)/',
  222. video_info['releaseDate'], 'release date', fatal=False),
  223. scale=1000)
  224. artists = video_info.get('mainArtists')
  225. if artists:
  226. uploader = artists[0]['artistName']
  227. smil_parsed = False
  228. for video_version in video_info['videoVersions']:
  229. version = self._VERSIONS.get(video_version['version'])
  230. if version == 'youtube':
  231. continue
  232. else:
  233. source_type = self._SOURCE_TYPES.get(video_version['sourceType'])
  234. renditions = compat_etree_fromstring(video_version['data'])
  235. if source_type == 'http':
  236. for rend in renditions.findall('rendition'):
  237. attr = rend.attrib
  238. formats.append({
  239. 'url': attr['url'],
  240. 'format_id': 'http-%s-%s' % (version, attr['name']),
  241. 'height': int_or_none(attr.get('frameheight')),
  242. 'width': int_or_none(attr.get('frameWidth')),
  243. 'tbr': int_or_none(attr.get('totalBitrate')),
  244. 'vbr': int_or_none(attr.get('videoBitrate')),
  245. 'abr': int_or_none(attr.get('audioBitrate')),
  246. 'vcodec': attr.get('videoCodec'),
  247. 'acodec': attr.get('audioCodec'),
  248. })
  249. elif source_type == 'hls':
  250. formats.extend(self._extract_m3u8_formats(
  251. renditions.find('rendition').attrib['url'], video_id,
  252. 'mp4', 'm3u8_native', m3u8_id='hls-%s' % version,
  253. note='Downloading %s m3u8 information' % version,
  254. errnote='Failed to download %s m3u8 information' % version,
  255. fatal=False))
  256. elif source_type == 'smil' and version == 'level3' and not smil_parsed:
  257. formats.extend(self._extract_smil_formats(
  258. renditions.find('rendition').attrib['url'], video_id, False))
  259. smil_parsed = True
  260. self._sort_formats(formats)
  261. title = video_info['title']
  262. is_explicit = video_info.get('isExplicit')
  263. if is_explicit is True:
  264. age_limit = 18
  265. elif is_explicit is False:
  266. age_limit = 0
  267. else:
  268. age_limit = None
  269. duration = video_info.get('duration')
  270. return {
  271. 'id': video_id,
  272. 'title': title,
  273. 'formats': formats,
  274. 'thumbnail': video_info.get('imageUrl') or video_info.get('thumbnailUrl'),
  275. 'timestamp': timestamp,
  276. 'uploader': uploader,
  277. 'duration': duration,
  278. 'view_count': view_count,
  279. 'age_limit': age_limit,
  280. }
  281. class VevoPlaylistIE(InfoExtractor):
  282. _VALID_URL = r'https?://www\.vevo\.com/watch/(?P<kind>playlist|genre)/(?P<id>[^/?#&]+)'
  283. _TESTS = [{
  284. 'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29',
  285. 'info_dict': {
  286. 'id': 'dadbf4e7-b99f-4184-9670-6f0e547b6a29',
  287. 'title': 'Best-Of: Birdman',
  288. },
  289. 'playlist_count': 10,
  290. }, {
  291. 'url': 'http://www.vevo.com/watch/genre/rock',
  292. 'info_dict': {
  293. 'id': 'rock',
  294. 'title': 'Rock',
  295. },
  296. 'playlist_count': 20,
  297. }, {
  298. 'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29?index=0',
  299. 'md5': '32dcdfddddf9ec6917fc88ca26d36282',
  300. 'info_dict': {
  301. 'id': 'USCMV1100073',
  302. 'ext': 'mp4',
  303. 'title': 'Y.U. MAD',
  304. 'timestamp': 1323417600,
  305. 'upload_date': '20111209',
  306. 'uploader': 'Birdman',
  307. },
  308. 'expected_warnings': ['Unable to download SMIL file'],
  309. }, {
  310. 'url': 'http://www.vevo.com/watch/genre/rock?index=0',
  311. 'only_matching': True,
  312. }]
  313. def _real_extract(self, url):
  314. mobj = re.match(self._VALID_URL, url)
  315. playlist_id = mobj.group('id')
  316. playlist_kind = mobj.group('kind')
  317. webpage = self._download_webpage(url, playlist_id)
  318. qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  319. index = qs.get('index', [None])[0]
  320. if index:
  321. video_id = self._search_regex(
  322. r'<meta[^>]+content=(["\'])vevo://video/(?P<id>.+?)\1[^>]*>',
  323. webpage, 'video id', default=None, group='id')
  324. if video_id:
  325. return self.url_result('vevo:%s' % video_id, VevoIE.ie_key())
  326. playlists = self._parse_json(
  327. self._search_regex(
  328. r'window\.__INITIAL_STORE__\s*=\s*({.+?});\s*</script>',
  329. webpage, 'initial store'),
  330. playlist_id)['default']['%ss' % playlist_kind]
  331. playlist = (list(playlists.values())[0]
  332. if playlist_kind == 'playlist' else playlists[playlist_id])
  333. entries = [
  334. self.url_result('vevo:%s' % src, VevoIE.ie_key())
  335. for src in playlist['isrcs']]
  336. return self.playlist_result(
  337. entries, playlist.get('playlistId'),
  338. playlist.get('name'), playlist.get('description'))