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