vevo.py 15 KB

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