vevo.py 13 KB

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