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.

257 lines
9.7 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 compat_str
  7. from ..utils import (
  8. ExtractorError,
  9. int_or_none,
  10. float_or_none,
  11. )
  12. class YandexMusicBaseIE(InfoExtractor):
  13. @staticmethod
  14. def _handle_error(response):
  15. if isinstance(response, dict):
  16. error = response.get('error')
  17. if error:
  18. raise ExtractorError(error, expected=True)
  19. def _download_webpage(self, *args, **kwargs):
  20. webpage = super(YandexMusicBaseIE, self)._download_webpage(*args, **kwargs)
  21. if 'Нам очень жаль, но запросы, поступившие с вашего IP-адреса, похожи на автоматические.' in webpage:
  22. raise ExtractorError(
  23. 'YandexMusic has considered youtube-dl requests automated and '
  24. 'asks you to solve a CAPTCHA. You can either wait for some '
  25. 'time until unblocked and optionally use --sleep-interval '
  26. 'in future or alternatively you can go to https://music.yandex.ru/ '
  27. 'solve CAPTCHA, then export cookies and pass cookie file to '
  28. 'youtube-dl with --cookies',
  29. expected=True)
  30. return webpage
  31. def _download_json(self, *args, **kwargs):
  32. response = super(YandexMusicBaseIE, self)._download_json(*args, **kwargs)
  33. self._handle_error(response)
  34. return response
  35. class YandexMusicTrackIE(YandexMusicBaseIE):
  36. IE_NAME = 'yandexmusic:track'
  37. IE_DESC = 'Яндекс.Музыка - Трек'
  38. _VALID_URL = r'https?://music\.yandex\.(?:ru|kz|ua|by)/album/(?P<album_id>\d+)/track/(?P<id>\d+)'
  39. _TEST = {
  40. 'url': 'http://music.yandex.ru/album/540508/track/4878838',
  41. 'md5': 'f496818aa2f60b6c0062980d2e00dc20',
  42. 'info_dict': {
  43. 'id': '4878838',
  44. 'ext': 'mp3',
  45. 'title': 'Carlo Ambrosio & Fabio Di Bari, Carlo Ambrosio - Gypsy Eyes 1',
  46. 'filesize': 4628061,
  47. 'duration': 193.04,
  48. 'track': 'Gypsy Eyes 1',
  49. 'album': 'Gypsy Soul',
  50. 'album_artist': 'Carlo Ambrosio',
  51. 'artist': 'Carlo Ambrosio & Fabio Di Bari, Carlo Ambrosio',
  52. 'release_year': '2009',
  53. },
  54. 'skip': 'Travis CI servers blocked by YandexMusic',
  55. }
  56. def _get_track_url(self, storage_dir, track_id):
  57. data = self._download_json(
  58. 'http://music.yandex.ru/api/v1.5/handlers/api-jsonp.jsx?action=getTrackSrc&p=download-info/%s'
  59. % storage_dir,
  60. track_id, 'Downloading track location JSON')
  61. key = hashlib.md5(('XGRlBW9FXlekgbPrRHuSiA' + data['path'][1:] + data['s']).encode('utf-8')).hexdigest()
  62. storage = storage_dir.split('.')
  63. return ('http://%s/get-mp3/%s/%s?track-id=%s&from=service-10-track&similarities-experiment=default'
  64. % (data['host'], key, data['ts'] + data['path'], storage[1]))
  65. def _get_track_info(self, track):
  66. thumbnail = None
  67. cover_uri = track.get('albums', [{}])[0].get('coverUri')
  68. if cover_uri:
  69. thumbnail = cover_uri.replace('%%', 'orig')
  70. if not thumbnail.startswith('http'):
  71. thumbnail = 'http://' + thumbnail
  72. track_title = track['title']
  73. track_info = {
  74. 'id': track['id'],
  75. 'ext': 'mp3',
  76. 'url': self._get_track_url(track['storageDir'], track['id']),
  77. 'filesize': int_or_none(track.get('fileSize')),
  78. 'duration': float_or_none(track.get('durationMs'), 1000),
  79. 'thumbnail': thumbnail,
  80. 'track': track_title,
  81. }
  82. def extract_artist(artist_list):
  83. if artist_list and isinstance(artist_list, list):
  84. artists_names = [a['name'] for a in artist_list if a.get('name')]
  85. if artists_names:
  86. return ', '.join(artists_names)
  87. albums = track.get('albums')
  88. if albums and isinstance(albums, list):
  89. album = albums[0]
  90. if isinstance(album, dict):
  91. year = album.get('year')
  92. track_info.update({
  93. 'album': album.get('title'),
  94. 'album_artist': extract_artist(album.get('artists')),
  95. 'release_year': compat_str(year) if year else None,
  96. })
  97. track_artist = extract_artist(track.get('artists'))
  98. if track_artist:
  99. track_info.update({
  100. 'artist': track_artist,
  101. 'title': '%s - %s' % (track_artist, track_title),
  102. })
  103. else:
  104. track_info['title'] = track_title
  105. return track_info
  106. def _real_extract(self, url):
  107. mobj = re.match(self._VALID_URL, url)
  108. album_id, track_id = mobj.group('album_id'), mobj.group('id')
  109. track = self._download_json(
  110. 'http://music.yandex.ru/handlers/track.jsx?track=%s:%s' % (track_id, album_id),
  111. track_id, 'Downloading track JSON')['track']
  112. return self._get_track_info(track)
  113. class YandexMusicPlaylistBaseIE(YandexMusicBaseIE):
  114. def _build_playlist(self, tracks):
  115. return [
  116. self.url_result(
  117. 'http://music.yandex.ru/album/%s/track/%s' % (track['albums'][0]['id'], track['id']))
  118. for track in tracks if track.get('albums') and isinstance(track.get('albums'), list)]
  119. class YandexMusicAlbumIE(YandexMusicPlaylistBaseIE):
  120. IE_NAME = 'yandexmusic:album'
  121. IE_DESC = 'Яндекс.Музыка - Альбом'
  122. _VALID_URL = r'https?://music\.yandex\.(?:ru|kz|ua|by)/album/(?P<id>\d+)/?(\?|$)'
  123. _TEST = {
  124. 'url': 'http://music.yandex.ru/album/540508',
  125. 'info_dict': {
  126. 'id': '540508',
  127. 'title': 'Carlo Ambrosio - Gypsy Soul (2009)',
  128. },
  129. 'playlist_count': 50,
  130. 'skip': 'Travis CI servers blocked by YandexMusic',
  131. }
  132. def _real_extract(self, url):
  133. album_id = self._match_id(url)
  134. album = self._download_json(
  135. 'http://music.yandex.ru/handlers/album.jsx?album=%s' % album_id,
  136. album_id, 'Downloading album JSON')
  137. entries = self._build_playlist(album['volumes'][0])
  138. title = '%s - %s' % (album['artists'][0]['name'], album['title'])
  139. year = album.get('year')
  140. if year:
  141. title += ' (%s)' % year
  142. return self.playlist_result(entries, compat_str(album['id']), title)
  143. class YandexMusicPlaylistIE(YandexMusicPlaylistBaseIE):
  144. IE_NAME = 'yandexmusic:playlist'
  145. IE_DESC = 'Яндекс.Музыка - Плейлист'
  146. _VALID_URL = r'https?://music\.yandex\.(?P<tld>ru|kz|ua|by)/users/(?P<user>[^/]+)/playlists/(?P<id>\d+)'
  147. _TESTS = [{
  148. 'url': 'http://music.yandex.ru/users/music.partners/playlists/1245',
  149. 'info_dict': {
  150. 'id': '1245',
  151. 'title': 'Что слушают Enter Shikari',
  152. 'description': 'md5:3b9f27b0efbe53f2ee1e844d07155cc9',
  153. },
  154. 'playlist_count': 6,
  155. 'skip': 'Travis CI servers blocked by YandexMusic',
  156. }, {
  157. # playlist exceeding the limit of 150 tracks shipped with webpage (see
  158. # https://github.com/rg3/youtube-dl/issues/6666)
  159. 'url': 'https://music.yandex.ru/users/ya.playlist/playlists/1036',
  160. 'info_dict': {
  161. 'id': '1036',
  162. 'title': 'Музыка 90-х',
  163. },
  164. 'playlist_mincount': 300,
  165. 'skip': 'Travis CI servers blocked by YandexMusic',
  166. }]
  167. def _real_extract(self, url):
  168. mobj = re.match(self._VALID_URL, url)
  169. tld = mobj.group('tld')
  170. user = mobj.group('user')
  171. playlist_id = mobj.group('id')
  172. playlist = self._download_json(
  173. 'https://music.yandex.%s/handlers/playlist.jsx' % tld,
  174. playlist_id, 'Downloading missing tracks JSON',
  175. fatal=False,
  176. headers={
  177. 'Referer': url,
  178. 'X-Requested-With': 'XMLHttpRequest',
  179. 'X-Retpath-Y': url,
  180. },
  181. query={
  182. 'owner': user,
  183. 'kinds': playlist_id,
  184. 'light': 'true',
  185. 'lang': tld,
  186. 'external-domain': 'music.yandex.%s' % tld,
  187. 'overembed': 'false',
  188. })['playlist']
  189. tracks, track_ids = playlist['tracks'], map(compat_str, playlist['trackIds'])
  190. # tracks dictionary shipped with playlist.jsx API is limited to 150 tracks,
  191. # missing tracks should be retrieved manually.
  192. if len(tracks) < len(track_ids):
  193. present_track_ids = set([
  194. compat_str(track['id'])
  195. for track in tracks if track.get('id')])
  196. missing_track_ids = [
  197. track_id for track_id in track_ids
  198. if track_id not in present_track_ids]
  199. missing_tracks = self._download_json(
  200. 'https://music.yandex.%s/handlers/track-entries.jsx' % tld,
  201. playlist_id, 'Downloading missing tracks JSON',
  202. fatal=False,
  203. headers={
  204. 'Referer': url,
  205. 'X-Requested-With': 'XMLHttpRequest',
  206. },
  207. query={
  208. 'entries': ','.join(missing_track_ids),
  209. 'lang': tld,
  210. 'external-domain': 'music.yandex.%s' % tld,
  211. 'overembed': 'false',
  212. 'strict': 'true',
  213. })
  214. if missing_tracks:
  215. tracks.extend(missing_tracks)
  216. return self.playlist_result(
  217. self._build_playlist(tracks),
  218. compat_str(playlist_id),
  219. playlist.get('title'), playlist.get('description'))