vevo.py 17 KB

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