vevo.py 15 KB

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