You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

462 lines
18 KiB

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