vevo.py 17 KB

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