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