vevo.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. import re
  2. import json
  3. from .common import InfoExtractor
  4. from ..compat import (
  5. compat_str,
  6. compat_HTTPError,
  7. )
  8. from ..utils import (
  9. ExtractorError,
  10. int_or_none,
  11. parse_iso8601,
  12. parse_qs,
  13. )
  14. class VevoBaseIE(InfoExtractor):
  15. def _extract_json(self, webpage, video_id):
  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)
  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. https?://embed\.vevo\.com/.*?[?&]isrc=|
  31. https?://tv\.vevo\.com/watch/artist/(?:[^/]+)/|
  32. vevo:)
  33. (?P<id>[^&?#]+)'''
  34. _EMBED_REGEX = [r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//(?:cache\.)?vevo\.com/.+?)\1']
  35. _TESTS = [{
  36. 'url': 'http://www.vevo.com/watch/hurts/somebody-to-die-for/GB1101300280',
  37. 'md5': '95ee28ee45e70130e3ab02b0f579ae23',
  38. 'info_dict': {
  39. 'id': 'GB1101300280',
  40. 'ext': 'mp4',
  41. 'title': 'Hurts - Somebody to Die For',
  42. 'timestamp': 1372057200,
  43. 'upload_date': '20130624',
  44. 'uploader': 'Hurts',
  45. 'track': 'Somebody to Die For',
  46. 'artist': 'Hurts',
  47. 'genre': 'Pop',
  48. },
  49. 'expected_warnings': ['Unable to download SMIL file', 'Unable to download info'],
  50. }, {
  51. 'note': 'v3 SMIL format',
  52. 'url': 'http://www.vevo.com/watch/cassadee-pope/i-wish-i-could-break-your-heart/USUV71302923',
  53. 'md5': 'f6ab09b034f8c22969020b042e5ac7fc',
  54. 'info_dict': {
  55. 'id': 'USUV71302923',
  56. 'ext': 'mp4',
  57. 'title': 'Cassadee Pope - I Wish I Could Break Your Heart',
  58. 'timestamp': 1392796919,
  59. 'upload_date': '20140219',
  60. 'uploader': 'Cassadee Pope',
  61. 'track': 'I Wish I Could Break Your Heart',
  62. 'artist': 'Cassadee Pope',
  63. 'genre': 'Country',
  64. },
  65. 'expected_warnings': ['Unable to download SMIL file', 'Unable to download info'],
  66. }, {
  67. 'note': 'Age-limited video',
  68. 'url': 'https://www.vevo.com/watch/justin-timberlake/tunnel-vision-explicit/USRV81300282',
  69. 'info_dict': {
  70. 'id': 'USRV81300282',
  71. 'ext': 'mp4',
  72. 'title': 'Justin Timberlake - Tunnel Vision (Explicit)',
  73. 'age_limit': 18,
  74. 'timestamp': 1372888800,
  75. 'upload_date': '20130703',
  76. 'uploader': 'Justin Timberlake',
  77. 'track': 'Tunnel Vision (Explicit)',
  78. 'artist': 'Justin Timberlake',
  79. 'genre': 'Pop',
  80. },
  81. 'expected_warnings': ['Unable to download SMIL file', 'Unable to download info'],
  82. }, {
  83. 'note': 'No video_info',
  84. 'url': 'http://www.vevo.com/watch/k-camp-1/Till-I-Die/USUV71503000',
  85. 'md5': '8b83cc492d72fc9cf74a02acee7dc1b0',
  86. 'info_dict': {
  87. 'id': 'USUV71503000',
  88. 'ext': 'mp4',
  89. 'title': 'K Camp ft. T.I. - Till I Die',
  90. 'age_limit': 18,
  91. 'timestamp': 1449468000,
  92. 'upload_date': '20151207',
  93. 'uploader': 'K Camp',
  94. 'track': 'Till I Die',
  95. 'artist': 'K Camp',
  96. 'genre': 'Hip-Hop',
  97. },
  98. 'expected_warnings': ['Unable to download SMIL file', 'Unable to download info'],
  99. }, {
  100. 'note': 'Featured test',
  101. 'url': 'https://www.vevo.com/watch/lemaitre/Wait/USUV71402190',
  102. 'md5': 'd28675e5e8805035d949dc5cf161071d',
  103. 'info_dict': {
  104. 'id': 'USUV71402190',
  105. 'ext': 'mp4',
  106. 'title': 'Lemaitre ft. LoLo - Wait',
  107. 'age_limit': 0,
  108. 'timestamp': 1413432000,
  109. 'upload_date': '20141016',
  110. 'uploader': 'Lemaitre',
  111. 'track': 'Wait',
  112. 'artist': 'Lemaitre',
  113. 'genre': 'Electronic',
  114. },
  115. 'expected_warnings': ['Unable to download SMIL file', 'Unable to download info'],
  116. }, {
  117. 'note': 'Only available via webpage',
  118. 'url': 'http://www.vevo.com/watch/GBUV71600656',
  119. 'md5': '67e79210613865b66a47c33baa5e37fe',
  120. 'info_dict': {
  121. 'id': 'GBUV71600656',
  122. 'ext': 'mp4',
  123. 'title': 'ABC - Viva Love',
  124. 'age_limit': 0,
  125. 'timestamp': 1461830400,
  126. 'upload_date': '20160428',
  127. 'uploader': 'ABC',
  128. 'track': 'Viva Love',
  129. 'artist': 'ABC',
  130. 'genre': 'Pop',
  131. },
  132. 'expected_warnings': ['Failed to download video versions info'],
  133. }, {
  134. # no genres available
  135. 'url': 'http://www.vevo.com/watch/INS171400764',
  136. 'only_matching': True,
  137. }, {
  138. # Another case available only via the webpage; using streams/streamsV3 formats
  139. # Geo-restricted to Netherlands/Germany
  140. 'url': 'http://www.vevo.com/watch/boostee/pop-corn-clip-officiel/FR1A91600909',
  141. 'only_matching': True,
  142. }, {
  143. 'url': 'https://embed.vevo.com/?isrc=USH5V1923499&partnerId=4d61b777-8023-4191-9ede-497ed6c24647&partnerAdCode=',
  144. 'only_matching': True,
  145. }, {
  146. 'url': 'https://tv.vevo.com/watch/artist/janet-jackson/US0450100550',
  147. 'only_matching': True,
  148. }]
  149. _VERSIONS = {
  150. 0: 'youtube', # only in AuthenticateVideo videoVersions
  151. 1: 'level3',
  152. 2: 'akamai',
  153. 3: 'level3',
  154. 4: 'amazon',
  155. }
  156. def _initialize_api(self, video_id):
  157. webpage = self._download_webpage(
  158. 'https://accounts.vevo.com/token', None,
  159. note='Retrieving oauth token',
  160. errnote='Unable to retrieve oauth token',
  161. data=json.dumps({
  162. 'client_id': 'SPupX1tvqFEopQ1YS6SS',
  163. 'grant_type': 'urn:vevo:params:oauth:grant-type:anonymous',
  164. }).encode('utf-8'),
  165. headers={
  166. 'Content-Type': 'application/json',
  167. })
  168. if re.search(r'(?i)THIS PAGE IS CURRENTLY UNAVAILABLE IN YOUR REGION', webpage):
  169. self.raise_geo_restricted(
  170. '%s said: This page is currently unavailable in your region' % self.IE_NAME)
  171. auth_info = self._parse_json(webpage, video_id)
  172. self._api_url_template = self.http_scheme() + '//apiv2.vevo.com/%s?token=' + auth_info['legacy_token']
  173. def _call_api(self, path, *args, **kwargs):
  174. try:
  175. data = self._download_json(self._api_url_template % path, *args, **kwargs)
  176. except ExtractorError as e:
  177. if isinstance(e.cause, compat_HTTPError):
  178. errors = self._parse_json(e.cause.read().decode(), None)['errors']
  179. error_message = ', '.join([error['message'] for error in errors])
  180. raise ExtractorError('%s said: %s' % (self.IE_NAME, error_message), expected=True)
  181. raise
  182. return data
  183. def _real_extract(self, url):
  184. video_id = self._match_id(url)
  185. self._initialize_api(video_id)
  186. video_info = self._call_api(
  187. 'video/%s' % video_id, video_id, 'Downloading api video info',
  188. 'Failed to download video info')
  189. video_versions = self._call_api(
  190. 'video/%s/streams' % video_id, video_id,
  191. 'Downloading video versions info',
  192. 'Failed to download video versions info',
  193. fatal=False)
  194. # Some videos are only available via webpage (e.g.
  195. # https://github.com/ytdl-org/youtube-dl/issues/9366)
  196. if not video_versions:
  197. webpage = self._download_webpage(url, video_id)
  198. json_data = self._extract_json(webpage, video_id)
  199. if 'streams' in json_data.get('default', {}):
  200. video_versions = json_data['default']['streams'][video_id][0]
  201. else:
  202. video_versions = [
  203. value
  204. for key, value in json_data['apollo']['data'].items()
  205. if key.startswith('%s.streams' % video_id)]
  206. uploader = None
  207. artist = None
  208. featured_artist = None
  209. artists = video_info.get('artists')
  210. for curr_artist in artists:
  211. if curr_artist.get('role') == 'Featured':
  212. featured_artist = curr_artist['name']
  213. else:
  214. artist = uploader = curr_artist['name']
  215. formats = []
  216. for video_version in video_versions:
  217. version = self._VERSIONS.get(video_version.get('version'), 'generic')
  218. version_url = video_version.get('url')
  219. if not version_url:
  220. continue
  221. if '.ism' in version_url:
  222. continue
  223. elif '.mpd' in version_url:
  224. formats.extend(self._extract_mpd_formats(
  225. version_url, video_id, mpd_id='dash-%s' % version,
  226. note='Downloading %s MPD information' % version,
  227. errnote='Failed to download %s MPD information' % version,
  228. fatal=False))
  229. elif '.m3u8' in version_url:
  230. formats.extend(self._extract_m3u8_formats(
  231. version_url, video_id, 'mp4', 'm3u8_native',
  232. m3u8_id='hls-%s' % version,
  233. note='Downloading %s m3u8 information' % version,
  234. errnote='Failed to download %s m3u8 information' % version,
  235. fatal=False))
  236. else:
  237. m = re.search(r'''(?xi)
  238. _(?P<quality>[a-z0-9]+)
  239. _(?P<width>[0-9]+)x(?P<height>[0-9]+)
  240. _(?P<vcodec>[a-z0-9]+)
  241. _(?P<vbr>[0-9]+)
  242. _(?P<acodec>[a-z0-9]+)
  243. _(?P<abr>[0-9]+)
  244. \.(?P<ext>[a-z0-9]+)''', version_url)
  245. if not m:
  246. continue
  247. formats.append({
  248. 'url': version_url,
  249. 'format_id': f'http-{version}-{video_version.get("quality") or m.group("quality")}',
  250. 'vcodec': m.group('vcodec'),
  251. 'acodec': m.group('acodec'),
  252. 'vbr': int(m.group('vbr')),
  253. 'abr': int(m.group('abr')),
  254. 'ext': m.group('ext'),
  255. 'width': int(m.group('width')),
  256. 'height': int(m.group('height')),
  257. })
  258. track = video_info['title']
  259. if featured_artist:
  260. artist = '%s ft. %s' % (artist, featured_artist)
  261. title = '%s - %s' % (artist, track) if artist else track
  262. genres = video_info.get('genres')
  263. genre = (
  264. genres[0] if genres and isinstance(genres, list)
  265. and isinstance(genres[0], compat_str) else None)
  266. is_explicit = video_info.get('isExplicit')
  267. if is_explicit is True:
  268. age_limit = 18
  269. elif is_explicit is False:
  270. age_limit = 0
  271. else:
  272. age_limit = None
  273. return {
  274. 'id': video_id,
  275. 'title': title,
  276. 'formats': formats,
  277. 'thumbnail': video_info.get('imageUrl') or video_info.get('thumbnailUrl'),
  278. 'timestamp': parse_iso8601(video_info.get('releaseDate')),
  279. 'uploader': uploader,
  280. 'duration': int_or_none(video_info.get('duration')),
  281. 'view_count': int_or_none(video_info.get('views', {}).get('total')),
  282. 'age_limit': age_limit,
  283. 'track': track,
  284. 'artist': uploader,
  285. 'genre': genre,
  286. }
  287. class VevoPlaylistIE(VevoBaseIE):
  288. _VALID_URL = r'https?://(?:www\.)?vevo\.com/watch/(?P<kind>playlist|genre)/(?P<id>[^/?#&]+)'
  289. _TESTS = [{
  290. 'url': 'http://www.vevo.com/watch/genre/rock',
  291. 'info_dict': {
  292. 'id': 'rock',
  293. 'title': 'Rock',
  294. },
  295. 'playlist_count': 20,
  296. }, {
  297. 'url': 'http://www.vevo.com/watch/genre/rock?index=0',
  298. 'only_matching': True,
  299. }]
  300. def _real_extract(self, url):
  301. mobj = self._match_valid_url(url)
  302. playlist_id = mobj.group('id')
  303. playlist_kind = mobj.group('kind')
  304. webpage = self._download_webpage(url, playlist_id)
  305. qs = parse_qs(url)
  306. index = qs.get('index', [None])[0]
  307. if index:
  308. video_id = self._search_regex(
  309. r'<meta[^>]+content=(["\'])vevo://video/(?P<id>.+?)\1[^>]*>',
  310. webpage, 'video id', default=None, group='id')
  311. if video_id:
  312. return self.url_result('vevo:%s' % video_id, VevoIE.ie_key())
  313. playlists = self._extract_json(webpage, playlist_id)['default']['%ss' % playlist_kind]
  314. playlist = (list(playlists.values())[0]
  315. if playlist_kind == 'playlist' else playlists[playlist_id])
  316. entries = [
  317. self.url_result('vevo:%s' % src, VevoIE.ie_key())
  318. for src in playlist['isrcs']]
  319. return self.playlist_result(
  320. entries, playlist.get('playlistId') or playlist_id,
  321. playlist.get('name'), playlist.get('description'))