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.

370 lines
14 KiB

12 years ago
12 years ago
12 years ago
12 years ago
  1. from __future__ import unicode_literals
  2. import re
  3. import json
  4. from .common import InfoExtractor
  5. from ..compat import (
  6. compat_str,
  7. compat_urlparse,
  8. compat_HTTPError,
  9. )
  10. from ..utils import (
  11. ExtractorError,
  12. int_or_none,
  13. parse_iso8601,
  14. )
  15. class VevoBaseIE(InfoExtractor):
  16. def _extract_json(self, webpage, video_id):
  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)
  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', 'Unable to download info'],
  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', 'Unable to download info'],
  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', 'Unable to download info'],
  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 ft. T.I. - 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': 'Hip-Hop',
  95. },
  96. 'expected_warnings': ['Unable to download SMIL file', 'Unable to download info'],
  97. }, {
  98. 'note': 'Featured test',
  99. 'url': 'https://www.vevo.com/watch/lemaitre/Wait/USUV71402190',
  100. 'md5': 'd28675e5e8805035d949dc5cf161071d',
  101. 'info_dict': {
  102. 'id': 'USUV71402190',
  103. 'ext': 'mp4',
  104. 'title': 'Lemaitre ft. LoLo - Wait',
  105. 'age_limit': 0,
  106. 'timestamp': 1413432000,
  107. 'upload_date': '20141016',
  108. 'uploader': 'Lemaitre',
  109. 'track': 'Wait',
  110. 'artist': 'Lemaitre',
  111. 'genre': 'Electronic',
  112. },
  113. 'expected_warnings': ['Unable to download SMIL file', 'Unable to download info'],
  114. }, {
  115. 'note': 'Only available via webpage',
  116. 'url': 'http://www.vevo.com/watch/GBUV71600656',
  117. 'md5': '67e79210613865b66a47c33baa5e37fe',
  118. 'info_dict': {
  119. 'id': 'GBUV71600656',
  120. 'ext': 'mp4',
  121. 'title': 'ABC - Viva Love',
  122. 'age_limit': 0,
  123. 'timestamp': 1461830400,
  124. 'upload_date': '20160428',
  125. 'uploader': 'ABC',
  126. 'track': 'Viva Love',
  127. 'artist': 'ABC',
  128. 'genre': 'Pop',
  129. },
  130. 'expected_warnings': ['Failed to download video versions info'],
  131. }, {
  132. # no genres available
  133. 'url': 'http://www.vevo.com/watch/INS171400764',
  134. 'only_matching': True,
  135. }, {
  136. # Another case available only via the webpage; using streams/streamsV3 formats
  137. # Geo-restricted to Netherlands/Germany
  138. 'url': 'http://www.vevo.com/watch/boostee/pop-corn-clip-officiel/FR1A91600909',
  139. 'only_matching': True,
  140. }]
  141. _VERSIONS = {
  142. 0: 'youtube', # only in AuthenticateVideo videoVersions
  143. 1: 'level3',
  144. 2: 'akamai',
  145. 3: 'level3',
  146. 4: 'amazon',
  147. }
  148. def _initialize_api(self, video_id):
  149. webpage = self._download_webpage(
  150. 'https://accounts.vevo.com/token', None,
  151. note='Retrieving oauth token',
  152. errnote='Unable to retrieve oauth token',
  153. data=json.dumps({
  154. 'client_id': 'SPupX1tvqFEopQ1YS6SS',
  155. 'grant_type': 'urn:vevo:params:oauth:grant-type:anonymous',
  156. }).encode('utf-8'),
  157. headers={
  158. 'Content-Type': 'application/json',
  159. })
  160. if re.search(r'(?i)THIS PAGE IS CURRENTLY UNAVAILABLE IN YOUR REGION', webpage):
  161. self.raise_geo_restricted(
  162. '%s said: This page is currently unavailable in your region' % self.IE_NAME)
  163. auth_info = self._parse_json(webpage, video_id)
  164. self._api_url_template = self.http_scheme() + '//apiv2.vevo.com/%s?token=' + auth_info['legacy_token']
  165. def _call_api(self, path, *args, **kwargs):
  166. try:
  167. data = self._download_json(self._api_url_template % path, *args, **kwargs)
  168. except ExtractorError as e:
  169. if isinstance(e.cause, compat_HTTPError):
  170. errors = self._parse_json(e.cause.read().decode(), None)['errors']
  171. error_message = ', '.join([error['message'] for error in errors])
  172. raise ExtractorError('%s said: %s' % (self.IE_NAME, error_message), expected=True)
  173. raise
  174. return data
  175. def _real_extract(self, url):
  176. video_id = self._match_id(url)
  177. self._initialize_api(video_id)
  178. video_info = self._call_api(
  179. 'video/%s' % video_id, video_id, 'Downloading api video info',
  180. 'Failed to download video info')
  181. video_versions = self._call_api(
  182. 'video/%s/streams' % video_id, video_id,
  183. 'Downloading video versions info',
  184. 'Failed to download video versions info',
  185. fatal=False)
  186. # Some videos are only available via webpage (e.g.
  187. # https://github.com/ytdl-org/youtube-dl/issues/9366)
  188. if not video_versions:
  189. webpage = self._download_webpage(url, video_id)
  190. json_data = self._extract_json(webpage, video_id)
  191. if 'streams' in json_data.get('default', {}):
  192. video_versions = json_data['default']['streams'][video_id][0]
  193. else:
  194. video_versions = [
  195. value
  196. for key, value in json_data['apollo']['data'].items()
  197. if key.startswith('%s.streams' % video_id)]
  198. uploader = None
  199. artist = None
  200. featured_artist = None
  201. artists = video_info.get('artists')
  202. for curr_artist in artists:
  203. if curr_artist.get('role') == 'Featured':
  204. featured_artist = curr_artist['name']
  205. else:
  206. artist = uploader = curr_artist['name']
  207. formats = []
  208. for video_version in video_versions:
  209. version = self._VERSIONS.get(video_version.get('version'), 'generic')
  210. version_url = video_version.get('url')
  211. if not version_url:
  212. continue
  213. if '.ism' in version_url:
  214. continue
  215. elif '.mpd' in version_url:
  216. formats.extend(self._extract_mpd_formats(
  217. version_url, video_id, mpd_id='dash-%s' % version,
  218. note='Downloading %s MPD information' % version,
  219. errnote='Failed to download %s MPD information' % version,
  220. fatal=False))
  221. elif '.m3u8' in version_url:
  222. formats.extend(self._extract_m3u8_formats(
  223. version_url, video_id, 'mp4', 'm3u8_native',
  224. m3u8_id='hls-%s' % version,
  225. note='Downloading %s m3u8 information' % version,
  226. errnote='Failed to download %s m3u8 information' % version,
  227. fatal=False))
  228. else:
  229. m = re.search(r'''(?xi)
  230. _(?P<width>[0-9]+)x(?P<height>[0-9]+)
  231. _(?P<vcodec>[a-z0-9]+)
  232. _(?P<vbr>[0-9]+)
  233. _(?P<acodec>[a-z0-9]+)
  234. _(?P<abr>[0-9]+)
  235. \.(?P<ext>[a-z0-9]+)''', version_url)
  236. if not m:
  237. continue
  238. formats.append({
  239. 'url': version_url,
  240. 'format_id': 'http-%s-%s' % (version, video_version['quality']),
  241. 'vcodec': m.group('vcodec'),
  242. 'acodec': m.group('acodec'),
  243. 'vbr': int(m.group('vbr')),
  244. 'abr': int(m.group('abr')),
  245. 'ext': m.group('ext'),
  246. 'width': int(m.group('width')),
  247. 'height': int(m.group('height')),
  248. })
  249. self._sort_formats(formats)
  250. track = video_info['title']
  251. if featured_artist:
  252. artist = '%s ft. %s' % (artist, featured_artist)
  253. title = '%s - %s' % (artist, track) if artist else track
  254. genres = video_info.get('genres')
  255. genre = (
  256. genres[0] if genres and isinstance(genres, list) and
  257. isinstance(genres[0], compat_str) else None)
  258. is_explicit = video_info.get('isExplicit')
  259. if is_explicit is True:
  260. age_limit = 18
  261. elif is_explicit is False:
  262. age_limit = 0
  263. else:
  264. age_limit = None
  265. return {
  266. 'id': video_id,
  267. 'title': title,
  268. 'formats': formats,
  269. 'thumbnail': video_info.get('imageUrl') or video_info.get('thumbnailUrl'),
  270. 'timestamp': parse_iso8601(video_info.get('releaseDate')),
  271. 'uploader': uploader,
  272. 'duration': int_or_none(video_info.get('duration')),
  273. 'view_count': int_or_none(video_info.get('views', {}).get('total')),
  274. 'age_limit': age_limit,
  275. 'track': track,
  276. 'artist': uploader,
  277. 'genre': genre,
  278. }
  279. class VevoPlaylistIE(VevoBaseIE):
  280. _VALID_URL = r'https?://(?:www\.)?vevo\.com/watch/(?P<kind>playlist|genre)/(?P<id>[^/?#&]+)'
  281. _TESTS = [{
  282. 'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29',
  283. 'info_dict': {
  284. 'id': 'dadbf4e7-b99f-4184-9670-6f0e547b6a29',
  285. 'title': 'Best-Of: Birdman',
  286. },
  287. 'playlist_count': 10,
  288. }, {
  289. 'url': 'http://www.vevo.com/watch/genre/rock',
  290. 'info_dict': {
  291. 'id': 'rock',
  292. 'title': 'Rock',
  293. },
  294. 'playlist_count': 20,
  295. }, {
  296. 'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29?index=0',
  297. 'md5': '32dcdfddddf9ec6917fc88ca26d36282',
  298. 'info_dict': {
  299. 'id': 'USCMV1100073',
  300. 'ext': 'mp4',
  301. 'title': 'Birdman - Y.U. MAD',
  302. 'timestamp': 1323417600,
  303. 'upload_date': '20111209',
  304. 'uploader': 'Birdman',
  305. 'track': 'Y.U. MAD',
  306. 'artist': 'Birdman',
  307. 'genre': 'Rap/Hip-Hop',
  308. },
  309. 'expected_warnings': ['Unable to download SMIL file'],
  310. }, {
  311. 'url': 'http://www.vevo.com/watch/genre/rock?index=0',
  312. 'only_matching': True,
  313. }]
  314. def _real_extract(self, url):
  315. mobj = re.match(self._VALID_URL, url)
  316. playlist_id = mobj.group('id')
  317. playlist_kind = mobj.group('kind')
  318. webpage = self._download_webpage(url, playlist_id)
  319. qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  320. index = qs.get('index', [None])[0]
  321. if index:
  322. video_id = self._search_regex(
  323. r'<meta[^>]+content=(["\'])vevo://video/(?P<id>.+?)\1[^>]*>',
  324. webpage, 'video id', default=None, group='id')
  325. if video_id:
  326. return self.url_result('vevo:%s' % video_id, VevoIE.ie_key())
  327. playlists = self._extract_json(webpage, playlist_id)['default']['%ss' % playlist_kind]
  328. playlist = (list(playlists.values())[0]
  329. if playlist_kind == 'playlist' else playlists[playlist_id])
  330. entries = [
  331. self.url_result('vevo:%s' % src, VevoIE.ie_key())
  332. for src in playlist['isrcs']]
  333. return self.playlist_result(
  334. entries, playlist.get('playlistId') or playlist_id,
  335. playlist.get('name'), playlist.get('description'))