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.

365 lines
13 KiB

12 years ago
12 years ago
12 years ago
  1. from __future__ import unicode_literals
  2. import re
  3. from .common import InfoExtractor
  4. from ..compat import (
  5. compat_str,
  6. compat_urlparse,
  7. compat_HTTPError,
  8. )
  9. from ..utils import (
  10. ExtractorError,
  11. int_or_none,
  12. sanitized_Request,
  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. req = sanitized_Request(
  150. 'http://www.vevo.com/auth', data=b'')
  151. webpage = self._download_webpage(
  152. req, None,
  153. note='Retrieving oauth token',
  154. errnote='Unable to retrieve oauth token')
  155. if re.search(r'(?i)THIS PAGE IS CURRENTLY UNAVAILABLE IN YOUR REGION', webpage):
  156. self.raise_geo_restricted(
  157. '%s said: This page is currently unavailable in your region' % self.IE_NAME)
  158. auth_info = self._parse_json(webpage, video_id)
  159. self._api_url_template = self.http_scheme() + '//apiv2.vevo.com/%s?token=' + auth_info['access_token']
  160. def _call_api(self, path, *args, **kwargs):
  161. try:
  162. data = self._download_json(self._api_url_template % path, *args, **kwargs)
  163. except ExtractorError as e:
  164. if isinstance(e.cause, compat_HTTPError):
  165. errors = self._parse_json(e.cause.read().decode(), None)['errors']
  166. error_message = ', '.join([error['message'] for error in errors])
  167. raise ExtractorError('%s said: %s' % (self.IE_NAME, error_message), expected=True)
  168. raise
  169. return data
  170. def _real_extract(self, url):
  171. video_id = self._match_id(url)
  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. json_data = self._extract_json(webpage, video_id)
  186. if 'streams' in json_data.get('default', {}):
  187. video_versions = json_data['default']['streams'][video_id][0]
  188. else:
  189. video_versions = [
  190. value
  191. for key, value in json_data['apollo']['data'].items()
  192. if key.startswith('%s.streams' % video_id)]
  193. uploader = None
  194. artist = None
  195. featured_artist = None
  196. artists = video_info.get('artists')
  197. for curr_artist in artists:
  198. if curr_artist.get('role') == 'Featured':
  199. featured_artist = curr_artist['name']
  200. else:
  201. artist = uploader = curr_artist['name']
  202. formats = []
  203. for video_version in video_versions:
  204. version = self._VERSIONS.get(video_version.get('version'), 'generic')
  205. version_url = video_version.get('url')
  206. if not version_url:
  207. continue
  208. if '.ism' in version_url:
  209. continue
  210. elif '.mpd' in version_url:
  211. formats.extend(self._extract_mpd_formats(
  212. version_url, video_id, mpd_id='dash-%s' % version,
  213. note='Downloading %s MPD information' % version,
  214. errnote='Failed to download %s MPD information' % version,
  215. fatal=False))
  216. elif '.m3u8' in version_url:
  217. formats.extend(self._extract_m3u8_formats(
  218. version_url, video_id, 'mp4', 'm3u8_native',
  219. m3u8_id='hls-%s' % version,
  220. note='Downloading %s m3u8 information' % version,
  221. errnote='Failed to download %s m3u8 information' % version,
  222. fatal=False))
  223. else:
  224. m = re.search(r'''(?xi)
  225. _(?P<width>[0-9]+)x(?P<height>[0-9]+)
  226. _(?P<vcodec>[a-z0-9]+)
  227. _(?P<vbr>[0-9]+)
  228. _(?P<acodec>[a-z0-9]+)
  229. _(?P<abr>[0-9]+)
  230. \.(?P<ext>[a-z0-9]+)''', version_url)
  231. if not m:
  232. continue
  233. formats.append({
  234. 'url': version_url,
  235. 'format_id': 'http-%s-%s' % (version, video_version['quality']),
  236. 'vcodec': m.group('vcodec'),
  237. 'acodec': m.group('acodec'),
  238. 'vbr': int(m.group('vbr')),
  239. 'abr': int(m.group('abr')),
  240. 'ext': m.group('ext'),
  241. 'width': int(m.group('width')),
  242. 'height': int(m.group('height')),
  243. })
  244. self._sort_formats(formats)
  245. track = video_info['title']
  246. if featured_artist:
  247. artist = '%s ft. %s' % (artist, featured_artist)
  248. title = '%s - %s' % (artist, track) if artist else track
  249. genres = video_info.get('genres')
  250. genre = (
  251. genres[0] if genres and isinstance(genres, list) and
  252. isinstance(genres[0], compat_str) else None)
  253. is_explicit = video_info.get('isExplicit')
  254. if is_explicit is True:
  255. age_limit = 18
  256. elif is_explicit is False:
  257. age_limit = 0
  258. else:
  259. age_limit = None
  260. return {
  261. 'id': video_id,
  262. 'title': title,
  263. 'formats': formats,
  264. 'thumbnail': video_info.get('imageUrl') or video_info.get('thumbnailUrl'),
  265. 'timestamp': parse_iso8601(video_info.get('releaseDate')),
  266. 'uploader': uploader,
  267. 'duration': int_or_none(video_info.get('duration')),
  268. 'view_count': int_or_none(video_info.get('views', {}).get('total')),
  269. 'age_limit': age_limit,
  270. 'track': track,
  271. 'artist': uploader,
  272. 'genre': genre,
  273. }
  274. class VevoPlaylistIE(VevoBaseIE):
  275. _VALID_URL = r'https?://(?:www\.)?vevo\.com/watch/(?P<kind>playlist|genre)/(?P<id>[^/?#&]+)'
  276. _TESTS = [{
  277. 'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29',
  278. 'info_dict': {
  279. 'id': 'dadbf4e7-b99f-4184-9670-6f0e547b6a29',
  280. 'title': 'Best-Of: Birdman',
  281. },
  282. 'playlist_count': 10,
  283. }, {
  284. 'url': 'http://www.vevo.com/watch/genre/rock',
  285. 'info_dict': {
  286. 'id': 'rock',
  287. 'title': 'Rock',
  288. },
  289. 'playlist_count': 20,
  290. }, {
  291. 'url': 'http://www.vevo.com/watch/playlist/dadbf4e7-b99f-4184-9670-6f0e547b6a29?index=0',
  292. 'md5': '32dcdfddddf9ec6917fc88ca26d36282',
  293. 'info_dict': {
  294. 'id': 'USCMV1100073',
  295. 'ext': 'mp4',
  296. 'title': 'Birdman - Y.U. MAD',
  297. 'timestamp': 1323417600,
  298. 'upload_date': '20111209',
  299. 'uploader': 'Birdman',
  300. 'track': 'Y.U. MAD',
  301. 'artist': 'Birdman',
  302. 'genre': 'Rap/Hip-Hop',
  303. },
  304. 'expected_warnings': ['Unable to download SMIL file'],
  305. }, {
  306. 'url': 'http://www.vevo.com/watch/genre/rock?index=0',
  307. 'only_matching': True,
  308. }]
  309. def _real_extract(self, url):
  310. mobj = re.match(self._VALID_URL, url)
  311. playlist_id = mobj.group('id')
  312. playlist_kind = mobj.group('kind')
  313. webpage = self._download_webpage(url, playlist_id)
  314. qs = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  315. index = qs.get('index', [None])[0]
  316. if index:
  317. video_id = self._search_regex(
  318. r'<meta[^>]+content=(["\'])vevo://video/(?P<id>.+?)\1[^>]*>',
  319. webpage, 'video id', default=None, group='id')
  320. if video_id:
  321. return self.url_result('vevo:%s' % video_id, VevoIE.ie_key())
  322. playlists = self._extract_json(webpage, playlist_id)['default']['%ss' % playlist_kind]
  323. playlist = (list(playlists.values())[0]
  324. if playlist_kind == 'playlist' else playlists[playlist_id])
  325. entries = [
  326. self.url_result('vevo:%s' % src, VevoIE.ie_key())
  327. for src in playlist['isrcs']]
  328. return self.playlist_result(
  329. entries, playlist.get('playlistId') or playlist_id,
  330. playlist.get('name'), playlist.get('description'))