2 from __future__
import unicode_literals
7 from .common
import InfoExtractor
8 from ..compat
import compat_str
18 class YandexMusicBaseIE(InfoExtractor
):
20 def _handle_error(response
):
21 if isinstance(response
, dict):
22 error
= response
.get('error')
24 raise ExtractorError(error
, expected
=True)
26 def _download_webpage(self
, *args
, **kwargs
):
27 webpage
= super(YandexMusicBaseIE
, self
)._download
_webpage
(*args
, **kwargs
)
28 if 'Нам очень жаль, но запросы, поступившие с вашего IP-адреса, похожи на автоматические.' in webpage
:
30 'YandexMusic has considered youtube-dl requests automated and '
31 'asks you to solve a CAPTCHA. You can either wait for some '
32 'time until unblocked and optionally use --sleep-interval '
33 'in future or alternatively you can go to https://music.yandex.ru/ '
34 'solve CAPTCHA, then export cookies and pass cookie file to '
35 'youtube-dl with --cookies',
39 def _download_json(self
, *args
, **kwargs
):
40 response
= super(YandexMusicBaseIE
, self
)._download
_json
(*args
, **kwargs
)
41 self
._handle
_error
(response
)
45 class YandexMusicTrackIE(YandexMusicBaseIE
):
46 IE_NAME
= 'yandexmusic:track'
47 IE_DESC
= 'Яндекс.Музыка - Трек'
48 _VALID_URL
= r
'https?://music\.yandex\.(?:ru|kz|ua|by)/album/(?P<album_id>\d+)/track/(?P<id>\d+)'
51 'url': 'http://music.yandex.ru/album/540508/track/4878838',
52 'md5': 'f496818aa2f60b6c0062980d2e00dc20',
56 'title': 'Carlo Ambrosio & Fabio Di Bari, Carlo Ambrosio - Gypsy Eyes 1',
59 'track': 'Gypsy Eyes 1',
60 'album': 'Gypsy Soul',
61 'album_artist': 'Carlo Ambrosio',
62 'artist': 'Carlo Ambrosio & Fabio Di Bari, Carlo Ambrosio',
63 'release_year': '2009',
65 'skip': 'Travis CI servers blocked by YandexMusic',
68 def _get_track_url(self
, storage_dir
, track_id
):
69 data
= self
._download
_json
(
70 'http://music.yandex.ru/api/v1.5/handlers/api-jsonp.jsx?action=getTrackSrc&p=download-info/%s'
72 track_id
, 'Downloading track location JSON')
74 key
= hashlib
.md5(('XGRlBW9FXlekgbPrRHuSiA' + data
['path'][1:] + data
['s']).encode('utf-8')).hexdigest()
75 storage
= storage_dir
.split('.')
77 return ('http://%s/get-mp3/%s/%s?track-id=%s&from=service-10-track&similarities-experiment=default'
78 % (data
['host'], key
, data
['ts'] + data
['path'], storage
[1]))
80 def _get_track_info(self
, track
):
82 cover_uri
= track
.get('albums', [{}])[0].get('coverUri')
84 thumbnail
= cover_uri
.replace('%%', 'orig')
85 if not thumbnail
.startswith('http'):
86 thumbnail
= 'http://' + thumbnail
88 track_title
= track
['title']
92 'url': self
._get
_track
_url
(track
['storageDir'], track
['id']),
93 'filesize': int_or_none(track
.get('fileSize')),
94 'duration': float_or_none(track
.get('durationMs'), 1000),
95 'thumbnail': thumbnail
,
99 def extract_artist(artist_list
):
100 if artist_list
and isinstance(artist_list
, list):
101 artists_names
= [a
['name'] for a
in artist_list
if a
.get('name')]
103 return ', '.join(artists_names
)
105 albums
= track
.get('albums')
106 if albums
and isinstance(albums
, list):
108 if isinstance(album
, dict):
109 year
= album
.get('year')
111 'album': album
.get('title'),
112 'album_artist': extract_artist(album
.get('artists')),
113 'release_year': compat_str(year
) if year
else None,
116 track_artist
= extract_artist(track
.get('artists'))
119 'artist': track_artist
,
120 'title': '%s - %s' % (track_artist
, track_title
),
123 track_info
['title'] = track_title
126 def _real_extract(self
, url
):
127 mobj
= re
.match(self
._VALID
_URL
, url
)
128 album_id
, track_id
= mobj
.group('album_id'), mobj
.group('id')
130 track
= self
._download
_json
(
131 'http://music.yandex.ru/handlers/track.jsx?track=%s:%s' % (track_id
, album_id
),
132 track_id
, 'Downloading track JSON')['track']
134 return self
._get
_track
_info
(track
)
137 class YandexMusicPlaylistBaseIE(YandexMusicBaseIE
):
138 def _build_playlist(self
, tracks
):
141 'http://music.yandex.ru/album/%s/track/%s' % (track
['albums'][0]['id'], track
['id']))
142 for track
in tracks
if track
.get('albums') and isinstance(track
.get('albums'), list)]
145 class YandexMusicAlbumIE(YandexMusicPlaylistBaseIE
):
146 IE_NAME
= 'yandexmusic:album'
147 IE_DESC
= 'Яндекс.Музыка - Альбом'
148 _VALID_URL
= r
'https?://music\.yandex\.(?:ru|kz|ua|by)/album/(?P<id>\d+)/?(\?|$)'
151 'url': 'http://music.yandex.ru/album/540508',
154 'title': 'Carlo Ambrosio - Gypsy Soul (2009)',
156 'playlist_count': 50,
157 'skip': 'Travis CI servers blocked by YandexMusic',
160 def _real_extract(self
, url
):
161 album_id
= self
._match
_id
(url
)
163 album
= self
._download
_json
(
164 'http://music.yandex.ru/handlers/album.jsx?album=%s' % album_id
,
165 album_id
, 'Downloading album JSON')
167 entries
= self
._build
_playlist
(album
['volumes'][0])
169 title
= '%s - %s' % (album
['artists'][0]['name'], album
['title'])
170 year
= album
.get('year')
172 title
+= ' (%s)' % year
174 return self
.playlist_result(entries
, compat_str(album
['id']), title
)
177 class YandexMusicPlaylistIE(YandexMusicPlaylistBaseIE
):
178 IE_NAME
= 'yandexmusic:playlist'
179 IE_DESC
= 'Яндекс.Музыка - Плейлист'
180 _VALID_URL
= r
'https?://music\.yandex\.(?:ru|kz|ua|by)/users/[^/]+/playlists/(?P<id>\d+)'
183 'url': 'http://music.yandex.ru/users/music.partners/playlists/1245',
186 'title': 'Что слушают Enter Shikari',
187 'description': 'md5:3b9f27b0efbe53f2ee1e844d07155cc9',
190 'skip': 'Travis CI servers blocked by YandexMusic',
192 # playlist exceeding the limit of 150 tracks shipped with webpage (see
193 # https://github.com/rg3/youtube-dl/issues/6666)
194 'url': 'https://music.yandex.ru/users/ya.playlist/playlists/1036',
197 'title': 'Музыка 90-х',
199 'playlist_count': 310,
200 'skip': 'Travis CI servers blocked by YandexMusic',
203 def _real_extract(self
, url
):
204 playlist_id
= self
._match
_id
(url
)
206 webpage
= self
._download
_webpage
(url
, playlist_id
)
208 mu
= self
._parse
_json
(
210 r
'var\s+Mu\s*=\s*({.+?});\s*</script>', webpage
, 'player'),
213 playlist
= mu
['pageData']['playlist']
214 tracks
, track_ids
= playlist
['tracks'], playlist
['trackIds']
216 # tracks dictionary shipped with webpage is limited to 150 tracks,
217 # missing tracks should be retrieved manually.
218 if len(tracks
) < len(track_ids
):
219 present_track_ids
= set([compat_str(track
['id']) for track
in tracks
if track
.get('id')])
220 missing_track_ids
= set(map(compat_str
, track_ids
)) - set(present_track_ids
)
221 request
= sanitized_Request(
222 'https://music.yandex.ru/handlers/track-entries.jsx',
224 'entries': ','.join(missing_track_ids
),
225 'lang': mu
.get('settings', {}).get('lang', 'en'),
226 'external-domain': 'music.yandex.ru',
227 'overembed': 'false',
228 'sign': mu
.get('authData', {}).get('user', {}
).get('sign'),
231 request
.add_header('Referer', url
)
232 request
.add_header('X-Requested-With', 'XMLHttpRequest')
234 missing_tracks
= self
._download
_json
(
235 request
, playlist_id
, 'Downloading missing tracks JSON', fatal
=False)
237 tracks
.extend(missing_tracks
)
239 return self
.playlist_result(
240 self
._build
_playlist
(tracks
),
241 compat_str(playlist_id
),
242 playlist
['title'], playlist
.get('description'))