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.

171 lines
6.2 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import re
  4. import hashlib
  5. from .common import InfoExtractor
  6. from ..compat import (
  7. compat_str,
  8. compat_urllib_parse,
  9. compat_urllib_request,
  10. )
  11. from ..utils import (
  12. int_or_none,
  13. float_or_none,
  14. )
  15. class YandexMusicTrackIE(InfoExtractor):
  16. IE_NAME = 'yandexmusic:track'
  17. IE_DESC = 'Яндекс.Музыка - Трек'
  18. _VALID_URL = r'https?://music\.yandex\.(?:ru|kz|ua|by)/album/(?P<album_id>\d+)/track/(?P<id>\d+)'
  19. _TEST = {
  20. 'url': 'http://music.yandex.ru/album/540508/track/4878838',
  21. 'md5': 'f496818aa2f60b6c0062980d2e00dc20',
  22. 'info_dict': {
  23. 'id': '4878838',
  24. 'ext': 'mp3',
  25. 'title': 'Carlo Ambrosio - Gypsy Eyes 1',
  26. 'filesize': 4628061,
  27. 'duration': 193.04,
  28. }
  29. }
  30. def _get_track_url(self, storage_dir, track_id):
  31. data = self._download_json(
  32. 'http://music.yandex.ru/api/v1.5/handlers/api-jsonp.jsx?action=getTrackSrc&p=download-info/%s'
  33. % storage_dir,
  34. track_id, 'Downloading track location JSON')
  35. key = hashlib.md5(('XGRlBW9FXlekgbPrRHuSiA' + data['path'][1:] + data['s']).encode('utf-8')).hexdigest()
  36. storage = storage_dir.split('.')
  37. return ('http://%s/get-mp3/%s/%s?track-id=%s&from=service-10-track&similarities-experiment=default'
  38. % (data['host'], key, data['ts'] + data['path'], storage[1]))
  39. def _get_track_info(self, track):
  40. return {
  41. 'id': track['id'],
  42. 'ext': 'mp3',
  43. 'url': self._get_track_url(track['storageDir'], track['id']),
  44. 'title': '%s - %s' % (track['artists'][0]['name'], track['title']),
  45. 'filesize': int_or_none(track.get('fileSize')),
  46. 'duration': float_or_none(track.get('durationMs'), 1000),
  47. }
  48. def _real_extract(self, url):
  49. mobj = re.match(self._VALID_URL, url)
  50. album_id, track_id = mobj.group('album_id'), mobj.group('id')
  51. track = self._download_json(
  52. 'http://music.yandex.ru/handlers/track.jsx?track=%s:%s' % (track_id, album_id),
  53. track_id, 'Downloading track JSON')['track']
  54. return self._get_track_info(track)
  55. class YandexMusicPlaylistBaseIE(InfoExtractor):
  56. def _build_playlist(self, tracks):
  57. return [
  58. self.url_result(
  59. 'http://music.yandex.ru/album/%s/track/%s' % (track['albums'][0]['id'], track['id']))
  60. for track in tracks if track.get('albums') and isinstance(track.get('albums'), list)]
  61. class YandexMusicAlbumIE(YandexMusicPlaylistBaseIE):
  62. IE_NAME = 'yandexmusic:album'
  63. IE_DESC = 'Яндекс.Музыка - Альбом'
  64. _VALID_URL = r'https?://music\.yandex\.(?:ru|kz|ua|by)/album/(?P<id>\d+)/?(\?|$)'
  65. _TEST = {
  66. 'url': 'http://music.yandex.ru/album/540508',
  67. 'info_dict': {
  68. 'id': '540508',
  69. 'title': 'Carlo Ambrosio - Gypsy Soul (2009)',
  70. },
  71. 'playlist_count': 50,
  72. }
  73. def _real_extract(self, url):
  74. album_id = self._match_id(url)
  75. album = self._download_json(
  76. 'http://music.yandex.ru/handlers/album.jsx?album=%s' % album_id,
  77. album_id, 'Downloading album JSON')
  78. entries = self._build_playlist(album['volumes'][0])
  79. title = '%s - %s' % (album['artists'][0]['name'], album['title'])
  80. year = album.get('year')
  81. if year:
  82. title += ' (%s)' % year
  83. return self.playlist_result(entries, compat_str(album['id']), title)
  84. class YandexMusicPlaylistIE(YandexMusicPlaylistBaseIE):
  85. IE_NAME = 'yandexmusic:playlist'
  86. IE_DESC = 'Яндекс.Музыка - Плейлист'
  87. _VALID_URL = r'https?://music\.yandex\.(?:ru|kz|ua|by)/users/[^/]+/playlists/(?P<id>\d+)'
  88. _TESTS = [{
  89. 'url': 'http://music.yandex.ru/users/music.partners/playlists/1245',
  90. 'info_dict': {
  91. 'id': '1245',
  92. 'title': 'Что слушают Enter Shikari',
  93. 'description': 'md5:3b9f27b0efbe53f2ee1e844d07155cc9',
  94. },
  95. 'playlist_count': 6,
  96. }, {
  97. # playlist exceeding the limit of 150 tracks shipped with webpage (see
  98. # https://github.com/rg3/youtube-dl/issues/6666)
  99. 'url': 'https://music.yandex.ru/users/ya.playlist/playlists/1036',
  100. 'info_dict': {
  101. 'id': '1036',
  102. 'title': 'Музыка 90-х',
  103. },
  104. 'playlist_count': 310,
  105. }]
  106. def _real_extract(self, url):
  107. playlist_id = self._match_id(url)
  108. webpage = self._download_webpage(url, playlist_id)
  109. mu = self._parse_json(
  110. self._search_regex(
  111. r'var\s+Mu\s*=\s*({.+?});\s*</script>', webpage, 'player'),
  112. playlist_id)
  113. playlist = mu['pageData']['playlist']
  114. tracks, track_ids = playlist['tracks'], playlist['trackIds']
  115. # tracks dictionary shipped with webpage is limited to 150 tracks,
  116. # missing tracks should be retrieved manually.
  117. if len(tracks) < len(track_ids):
  118. present_track_ids = set([compat_str(track['id']) for track in tracks if track.get('id')])
  119. missing_track_ids = set(map(compat_str, track_ids)) - set(present_track_ids)
  120. request = compat_urllib_request.Request(
  121. 'https://music.yandex.ru/handlers/track-entries.jsx',
  122. compat_urllib_parse.urlencode({
  123. 'entries': ','.join(missing_track_ids),
  124. 'lang': mu.get('settings', {}).get('lang', 'en'),
  125. 'external-domain': 'music.yandex.ru',
  126. 'overembed': 'false',
  127. 'sign': mu.get('authData', {}).get('user', {}).get('sign'),
  128. 'strict': 'true',
  129. }).encode('utf-8'))
  130. request.add_header('Referer', url)
  131. request.add_header('X-Requested-With', 'XMLHttpRequest')
  132. missing_tracks = self._download_json(
  133. request, playlist_id, 'Downloading missing tracks JSON', fatal=False)
  134. if missing_tracks:
  135. tracks.extend(missing_tracks)
  136. return self.playlist_result(
  137. self._build_playlist(tracks),
  138. compat_str(playlist_id),
  139. playlist['title'], playlist.get('description'))