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.

441 lines
17 KiB

11 years ago
11 years ago
11 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'],
  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://api.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. try:
  201. self._initialize_api(video_id)
  202. except ExtractorError:
  203. ytid = response.get('errorInfo', {}).get('ytid')
  204. if ytid:
  205. self.report_warning(
  206. 'Video is geoblocked, trying with the YouTube video %s' % ytid)
  207. return self.url_result(ytid, 'Youtube', ytid)
  208. raise
  209. video_info = self._call_api(
  210. 'video/%s' % video_id, video_id, 'Downloading api video info',
  211. 'Failed to download video info')
  212. video_versions = self._call_api(
  213. 'video/%s/streams' % video_id, video_id,
  214. 'Downloading video versions info',
  215. 'Failed to download video versions info',
  216. fatal=False)
  217. # Some videos are only available via webpage (e.g.
  218. # https://github.com/rg3/youtube-dl/issues/9366)
  219. if not video_versions:
  220. webpage = self._download_webpage(url, video_id)
  221. video_versions = self._extract_json(webpage, video_id, 'streams')[video_id][0]
  222. timestamp = parse_iso8601(video_info.get('releaseDate'))
  223. artists = video_info.get('artists')
  224. if artists:
  225. artist = uploader = artists[0]['name']
  226. view_count = int_or_none(video_info.get('views', {}).get('total'))
  227. for video_version in video_versions:
  228. version = self._VERSIONS.get(video_version['version'])
  229. version_url = video_version.get('url')
  230. if not version_url:
  231. continue
  232. if '.ism' in version_url:
  233. continue
  234. elif '.mpd' in version_url:
  235. formats.extend(self._extract_mpd_formats(
  236. version_url, video_id, mpd_id='dash-%s' % version,
  237. note='Downloading %s MPD information' % version,
  238. errnote='Failed to download %s MPD information' % version,
  239. fatal=False))
  240. elif '.m3u8' in version_url:
  241. formats.extend(self._extract_m3u8_formats(
  242. version_url, video_id, 'mp4', 'm3u8_native',
  243. m3u8_id='hls-%s' % version,
  244. note='Downloading %s m3u8 information' % version,
  245. errnote='Failed to download %s m3u8 information' % version,
  246. fatal=False))
  247. else:
  248. m = re.search(r'''(?xi)
  249. _(?P<width>[0-9]+)x(?P<height>[0-9]+)
  250. _(?P<vcodec>[a-z0-9]+)
  251. _(?P<vbr>[0-9]+)
  252. _(?P<acodec>[a-z0-9]+)
  253. _(?P<abr>[0-9]+)
  254. \.(?P<ext>[a-z0-9]+)''', version_url)
  255. if not m:
  256. continue
  257. formats.append({
  258. 'url': version_url,
  259. 'format_id': 'http-%s-%s' % (version, video_version['quality']),
  260. 'vcodec': m.group('vcodec'),
  261. 'acodec': m.group('acodec'),
  262. 'vbr': int(m.group('vbr')),
  263. 'abr': int(m.group('abr')),
  264. 'ext': m.group('ext'),
  265. 'width': int(m.group('width')),
  266. 'height': int(m.group('height')),
  267. })
  268. else:
  269. timestamp = int_or_none(self._search_regex(
  270. r'/Date\((\d+)\)/',
  271. video_info['releaseDate'], 'release date', fatal=False),
  272. scale=1000)
  273. artists = video_info.get('mainArtists')
  274. if artists:
  275. artist = uploader = artists[0]['artistName']
  276. featured_artists = video_info.get('featuredArtists')
  277. if featured_artists:
  278. featured_artist = featured_artists[0]['artistName']
  279. smil_parsed = False
  280. for video_version in video_info['videoVersions']:
  281. version = self._VERSIONS.get(video_version['version'])
  282. if version == 'youtube':
  283. continue
  284. else:
  285. source_type = self._SOURCE_TYPES.get(video_version['sourceType'])
  286. renditions = compat_etree_fromstring(video_version['data'])
  287. if source_type == 'http':
  288. for rend in renditions.findall('rendition'):
  289. attr = rend.attrib
  290. formats.append({
  291. 'url': attr['url'],
  292. 'format_id': 'http-%s-%s' % (version, attr['name']),
  293. 'height': int_or_none(attr.get('frameheight')),
  294. 'width': int_or_none(attr.get('frameWidth')),
  295. 'tbr': int_or_none(attr.get('totalBitrate')),
  296. 'vbr': int_or_none(attr.get('videoBitrate')),
  297. 'abr': int_or_none(attr.get('audioBitrate')),
  298. 'vcodec': attr.get('videoCodec'),
  299. 'acodec': attr.get('audioCodec'),
  300. })
  301. elif source_type == 'hls':
  302. formats.extend(self._extract_m3u8_formats(
  303. renditions.find('rendition').attrib['url'], video_id,
  304. 'mp4', 'm3u8_native', m3u8_id='hls-%s' % version,
  305. note='Downloading %s m3u8 information' % version,
  306. errnote='Failed to download %s m3u8 information' % version,
  307. fatal=False))
  308. elif source_type == 'smil' and version == 'level3' and not smil_parsed:
  309. formats.extend(self._extract_smil_formats(
  310. renditions.find('rendition').attrib['url'], video_id, False))
  311. smil_parsed = True
  312. self._sort_formats(formats)
  313. track = video_info['title']
  314. if featured_artist:
  315. artist = '%s ft. %s' % (artist, featured_artist)
  316. title = '%s - %s' % (artist, track) if artist else track
  317. genres = video_info.get('genres')
  318. genre = (
  319. genres[0] if genres and isinstance(genres, list) and
  320. isinstance(genres[0], compat_str) else None)
  321. is_explicit = video_info.get('isExplicit')
  322. if is_explicit is True:
  323. age_limit = 18
  324. elif is_explicit is False:
  325. age_limit = 0
  326. else:
  327. age_limit = None
  328. duration = video_info.get('duration')
  329. return {
  330. 'id': video_id,
  331. 'title': title,
  332. 'formats': formats,
  333. 'thumbnail': video_info.get('imageUrl') or video_info.get('thumbnailUrl'),
  334. 'timestamp': timestamp,
  335. 'uploader': uploader,
  336. 'duration': duration,
  337. 'view_count': view_count,
  338. 'age_limit': age_limit,
  339. 'track': track,
  340. 'artist': uploader,
  341. 'genre': genre,
  342. }
  343. class VevoPlaylistIE(VevoBaseIE):
  344. _VALID_URL = r'https?://(?:www\.)?vevo\.com/watch/(?P<kind>playlist|genre)/(?P<id>[^/?#&]+)'
  345. _TESTS = [{
  346. 'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29',
  347. 'info_dict': {
  348. 'id': 'dadbf4e7-b99f-4184-9670-6f0e547b6a29',
  349. 'title': 'Best-Of: Birdman',
  350. },
  351. 'playlist_count': 10,
  352. }, {
  353. 'url': 'http://www.vevo.com/watch/genre/rock',
  354. 'info_dict': {
  355. 'id': 'rock',
  356. 'title': 'Rock',
  357. },
  358. 'playlist_count': 20,
  359. }, {
  360. 'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29?index=0',
  361. 'md5': '32dcdfddddf9ec6917fc88ca26d36282',
  362. 'info_dict': {
  363. 'id': 'USCMV1100073',
  364. 'ext': 'mp4',
  365. 'title': 'Birdman - Y.U. MAD',
  366. 'timestamp': 1323417600,
  367. 'upload_date': '20111209',
  368. 'uploader': 'Birdman',
  369. 'track': 'Y.U. MAD',
  370. 'artist': 'Birdman',
  371. 'genre': 'Rap/Hip-Hop',
  372. },
  373. 'expected_warnings': ['Unable to download SMIL file'],
  374. }, {
  375. 'url': 'http://www.vevo.com/watch/genre/rock?index=0',
  376. 'only_matching': True,
  377. }]
  378. def _real_extract(self, url):
  379. mobj = re.match(self._VALID_URL, url)
  380. playlist_id = mobj.group('id')
  381. playlist_kind = mobj.group('kind')
  382. webpage = self._download_webpage(url, playlist_id)
  383. qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  384. index = qs.get('index', [None])[0]
  385. if index:
  386. video_id = self._search_regex(
  387. r'<meta[^>]+content=(["\'])vevo://video/(?P<id>.+?)\1[^>]*>',
  388. webpage, 'video id', default=None, group='id')
  389. if video_id:
  390. return self.url_result('vevo:%s' % video_id, VevoIE.ie_key())
  391. playlists = self._extract_json(webpage, playlist_id, '%ss' % playlist_kind)
  392. playlist = (list(playlists.values())[0]
  393. if playlist_kind == 'playlist' else playlists[playlist_id])
  394. entries = [
  395. self.url_result('vevo:%s' % src, VevoIE.ie_key())
  396. for src in playlist['isrcs']]
  397. return self.playlist_result(
  398. entries, playlist.get('playlistId') or playlist_id,
  399. playlist.get('name'), playlist.get('description'))