vevo.py 18 KB

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