[neteasemusic] Add new extractor for music.163.com
[youtube-dl] / youtube_dl / extractor / neteasemusic.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 from hashlib import md5
5 from datetime import datetime
6 import itertools
7 import re
8
9 from .common import InfoExtractor
10 from ..compat import (
11     compat_urllib_request,
12     compat_urllib_parse,
13 )
14
15
16 class NetEaseMusicBaseIE(InfoExtractor):
17     _FORMATS = ['bMusic', 'mMusic', 'hMusic']
18     _NETEASE_SALT = '3go8&$8*3*3h0k(2)2'
19     _API_BASE = 'http://music.163.com/api/'
20
21     @classmethod
22     def _encrypt(cls, dfsid):
23         salt_bytes = bytearray(str(cls._NETEASE_SALT))
24         string_bytes = bytearray(str(dfsid))
25         salt_len = len(salt_bytes)
26         for i in xrange(len(string_bytes)):
27             string_bytes[i] = string_bytes[i] ^ salt_bytes[i % salt_len]
28         m = md5()
29         m.update(string_bytes)
30         result = m.digest().encode('base64')[:-1]
31         return result.replace('/', '_').replace('+', '-')
32
33     @classmethod
34     def extract_formats(cls, info):
35         formats = []
36         for song_format in cls._FORMATS:
37             details = info.get(song_format)
38             if not details:
39                 continue
40             formats.append({
41                 'url': 'http://m1.music.126.net/%s/%s.%s' %
42                        (cls._encrypt(details['dfsId']), details['dfsId'],
43                         details['extension']),
44                 'ext': details['extension'],
45                 'abr': details['bitrate'] / 1000,
46                 'preference': details['bitrate'],
47                 'format_id': song_format,
48                 'filesize': details['size'],
49                 'asr': details['sr']
50             })
51         return formats
52
53     def query_api(self, endpoint, video_id, note):
54         req = compat_urllib_request.Request('%s%s' % (self._API_BASE, endpoint))
55         req.add_header('Referer', self._API_BASE)
56         return self._download_json(req, video_id, note)
57
58
59 class NetEaseMusicIE(NetEaseMusicBaseIE):
60     IE_NAME = 'netease:song'
61     _VALID_URL = r'https?://music\.163\.com/(#/)?song\?id=(?P<id>[0-9]+)'
62     _TESTS = [{
63         'url': 'http://music.163.com/#/song?id=32102397',
64         'md5': 'f2e97280e6345c74ba9d5677dd5dcb45',
65         'info_dict': {
66             'id': '32102397',
67             'ext': 'mp3',
68             'title': 'Bad Blood (feat. Kendrick Lamar)',
69             'creator': 'Taylor Swift / Kendrick Lamar',
70             'upload_date': '20150517',
71             'timestamp': 1431878400,
72             'description': 'md5:a10a54589c2860300d02e1de821eb2ef',
73         },
74     }, {
75         'note': 'No lyrics translation.',
76         'url': 'http://music.163.com/#/song?id=29822014',
77         'info_dict': {
78             'id': '29822014',
79             'ext': 'mp3',
80             'title': '听见下雨的声音',
81             'creator': '周杰伦',
82             'upload_date': '20141225',
83             'timestamp': 1419523200,
84             'description': 'md5:a4d8d89f44656af206b7b2555c0bce6c',
85         },
86     }, {
87         'note': 'No lyrics.',
88         'url': 'http://music.163.com/song?id=17241424',
89         'info_dict': {
90             'id': '17241424',
91             'ext': 'mp3',
92             'title': 'Opus 28',
93             'creator': 'Dustin O\'Halloran',
94             'upload_date': '20080211',
95             'timestamp': 1202745600,
96         },
97     }]
98
99     def _process_lyrics(self, lyrics_info):
100         original = lyrics_info.get('lrc', {}).get('lyric')
101         translated = lyrics_info.get('tlyric', {}).get('lyric')
102
103         if not translated:
104             return original
105
106         lyrics_expr = r'(\[[0-9]{2}:[0-9]{2}\.[0-9]{2,}\])([^\n]+)'
107         original_ts_texts = re.findall(lyrics_expr, original)
108         translation_ts_dict = {
109             time_stamp: text for time_stamp, text in re.findall(lyrics_expr, translated)
110         }
111
112         lyrics = '\n'.join([
113             '%s%s / %s' % (time_stamp, text, translation_ts_dict.get(time_stamp, ''))
114             for time_stamp, text in original_ts_texts
115         ])
116         return lyrics
117
118     def _real_extract(self, url):
119         song_id = self._match_id(url)
120
121         params = {
122             'id': song_id,
123             'ids': '[%s]' % song_id
124         }
125         info = self.query_api(
126             'song/detail?' + compat_urllib_parse.urlencode(params),
127             song_id, 'Downloading song info')['songs'][0]
128
129         formats = self.extract_formats(info)
130         self._sort_formats(formats)
131
132         lyrics_info = self.query_api(
133             'song/lyric?id=%s&lv=-1&tv=-1' % song_id, 
134             song_id, 'Downloading lyrics data')
135         lyrics = self._process_lyrics(lyrics_info)
136
137         alt_title = None
138         if info.get('alias'):
139             alt_title = '/'.join(info.get('alias'))
140
141         return {
142             'id': song_id,
143             'title': info['name'],
144             'alt_title': alt_title,
145             'creator': ' / '.join([artist['name'] for artist in info.get('artists', [])]),
146             'timestamp': int(info.get('album', {}).get('publishTime')/1000),
147             'thumbnail': info.get('album', {}).get('picUrl'),
148             'duration': int(info.get('duration', 0)/1000),
149             'description': lyrics,
150             'formats': formats,
151         }
152
153
154 class NetEaseMusicAlbumIE(NetEaseMusicBaseIE):
155     IE_NAME = 'netease:album'
156     _VALID_URL = r'https?://music\.163\.com/(#/)?album\?id=(?P<id>[0-9]+)'
157     _TEST = {
158         'url': 'http://music.163.com/#/album?id=220780',
159         'info_dict': {
160             'id': '220780',
161             'title': 'B\'day',
162         },
163         'playlist_count': 23,
164     }
165
166     def _real_extract(self, url):
167         album_id = self._match_id(url)
168
169         info = self.query_api(
170             'album/%s?id=%s' % (album_id, album_id), 
171             album_id, 'Downloading album data')['album']
172
173         name = info['name']
174         desc = info.get('description')
175         entries = [
176             self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
177                             'NetEaseMusic', song['id'])
178             for song in info['songs']
179         ]
180         return self.playlist_result(entries, album_id, name, desc)
181
182
183 class NetEaseMusicSingerIE(NetEaseMusicBaseIE):
184     IE_NAME = 'netease:singer'
185     _VALID_URL = r'https?://music\.163\.com/(#/)?artist\?id=(?P<id>[0-9]+)'
186     _TESTS = [{
187         'note': 'Singer has aliases.',
188         'url': 'http://music.163.com/#/artist?id=10559',
189         'info_dict': {
190             'id': '10559',
191             'title': '张惠妹 - aMEI;阿密特',
192         },
193         'playlist_count': 50,
194     }, {
195         'note': 'Singer has translated name.',
196         'url': 'http://music.163.com/#/artist?id=124098',
197         'info_dict': {
198             'id': '124098',
199             'title': '李昇基 - 이승기',
200         },
201         'playlist_count': 50,
202     }]
203
204     def _real_extract(self, url):
205         singer_id = self._match_id(url)
206
207         info = self.query_api(
208             'artist/%s?id=%s' % (singer_id, singer_id), 
209             singer_id, 'Downloading singer data')
210
211         name = info['artist']['name']
212         if info['artist']['trans']:
213             name = '%s - %s' % (name, info['artist']['trans'])
214         if info['artist']['alias']:
215             name = '%s - %s' % (name, ";".join(info['artist']['alias']))
216
217         entries = [
218             self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
219                             'NetEaseMusic', song['id'])
220             for song in info['hotSongs']
221         ]
222         return self.playlist_result(entries, singer_id, name)
223
224
225 class NetEaseMusicListIE(NetEaseMusicBaseIE):
226     IE_NAME = 'netease:playlist'
227     _VALID_URL = r'https?://music\.163\.com/(#/)?(playlist|discover/toplist)\?id=(?P<id>[0-9]+)'
228     _TESTS = [{
229         'url': 'http://music.163.com/#/playlist?id=79177352',
230         'info_dict': {
231             'id': '79177352',
232             'title': 'Billboard 2007 Top 100',
233             'description': 'md5:12fd0819cab2965b9583ace0f8b7b022'
234         },
235         'playlist_count': 99,
236     }, {
237         'note': 'Toplist/Charts sample',
238         'url': 'http://music.163.com/#/discover/toplist?id=3733003',
239         'info_dict': {
240             'id': '3733003',
241             'title': 're:韩国Melon排行榜周榜 [0-9]{4}-[0-9]{2}-[0-9]{2}',
242             'description': 'md5:73ec782a612711cadc7872d9c1e134fc',
243         },
244         'playlist_count': 50,
245     }]
246
247     def _real_extract(self, url):
248         list_id = self._match_id(url)
249
250         info = self.query_api(
251             'playlist/detail?id=%s&lv=-1&tv=-1' % list_id, 
252             list_id, 'Downloading playlist data')['result']
253
254         name = info['name']
255         desc = info.get('description')
256
257         if info.get('specialType') == 10:  # is a chart/toplist
258             datestamp = datetime.fromtimestamp(info['updateTime']/1000).strftime('%Y-%m-%d')
259             name = '%s %s' % (name, datestamp)
260
261         entries = [
262             self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
263                             'NetEaseMusic', song['id'])
264             for song in info['tracks']
265         ]
266         return self.playlist_result(entries, list_id, name, desc)
267
268
269 class NetEaseMusicMvIE(NetEaseMusicBaseIE):
270     IE_NAME = 'netease:mv'
271     _VALID_URL = r'https?://music\.163\.com/(#/)?mv\?id=(?P<id>[0-9]+)'
272     _TEST = {
273         'url': 'http://music.163.com/#/mv?id=415350',
274         'info_dict': {
275             'id': '415350',
276             'ext': 'mp4',
277             'title': '이럴거면 그러지말지',
278             'description': '白雅言自作曲唱甜蜜爱情',
279             'creator': '白雅言',
280             'upload_date': '20150520',
281         },
282     }
283
284     def _real_extract(self, url):
285         mv_id = self._match_id(url)
286
287         info = self.query_api(
288             'mv/detail?id=%s&type=mp4' % mv_id,
289             mv_id, 'Downloading mv info')['data']
290
291         formats = [
292             {'url': mv_url, 'ext': 'mp4', 'format_id': '%sp' % brs, 'preference': int(brs)}
293             for brs, mv_url in info['brs'].items()
294         ]
295         self._sort_formats(formats)
296
297         return {
298             'id': mv_id,
299             'title': info['name'],
300             'description': info.get('desc') or info.get('briefDesc'),
301             'creator': info['artistName'],
302             'upload_date': info['publishTime'].replace('-', ''),
303             'formats': formats,
304             'thumbnail': info.get('cover'),
305             'duration': int(info.get('duration', 0)/1000),
306         }
307
308
309 class NetEaseMusicProgramIE(NetEaseMusicBaseIE):
310     IE_NAME = 'netease:program'
311     _VALID_URL = r'https?://music\.163\.com/(#/?)program\?id=(?P<id>[0-9]+)'
312     _TESTS = [{
313         'url': 'http://music.163.com/#/program?id=10109055',
314         'info_dict': {
315             'id': '10109055',
316             'ext': 'mp3',
317             'title': '不丹足球背后的故事',
318             'description': '喜马拉雅人的足球梦 ...',
319             'creator': '大话西藏',
320             'timestamp': 1434179341,
321             'upload_date': '20150613',
322             'duration': 900,
323         },
324     }, {
325         'note': 'This program has accompanying songs.',
326         'url': 'http://music.163.com/#/program?id=10141022',
327         'info_dict': {
328             'id': '10141022',
329             'title': '25岁,你是自在如风的少年<27°C>',
330             'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
331         },
332         'playlist_count': 4,
333     }, {
334         'note': 'This program has accompanying songs.',
335         'url': 'http://music.163.com/#/program?id=10141022',
336         'info_dict': {
337             'id': '10141022',
338             'ext': 'mp3',
339             'title': '25岁,你是自在如风的少年<27°C>',
340             'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
341             'timestamp': 1434450840,
342             'upload_date': '20150616',
343         },
344         'params': {
345             'noplaylist': True
346         }
347     }]
348
349     def _real_extract(self, url):
350         program_id = self._match_id(url)
351
352         info = self.query_api(
353             'dj/program/detail?id=%s' % program_id,
354             program_id, 'Downloading program info')['program']
355
356         name = info['name']
357         description = info['description']
358
359         if not info['songs'] or self._downloader.params.get('noplaylist'):
360             if info['songs']:
361                 self.to_screen(
362                     'Downloading just the main audio %s because of --no-playlist'
363                     % info['mainSong']['id'])
364             
365             formats = self.extract_formats(info['mainSong'])
366             self._sort_formats(formats)
367
368             return {
369                 'id': program_id,
370                 'title': name,
371                 'description': description,
372                 'creator': info['dj']['brand'],
373                 'timestamp': int(info['createTime']/1000),
374                 'thumbnail': info['coverUrl'],
375                 'duration': int(info.get('duration', 0)/1000),
376                 'formats': formats,
377             }
378
379         self.to_screen(
380             'Downloading playlist %s - add --no-playlist to just download the main audio %s'
381             % (program_id, info['mainSong']['id']))
382
383         song_ids = [info['mainSong']['id']]
384         song_ids.extend([song['id'] for song in info['songs']])
385         entries = [
386             self.url_result('http://music.163.com/#/song?id=%s' % song_id,
387                             'NetEaseMusic', song_id)
388             for song_id in song_ids
389         ]
390         return self.playlist_result(entries, program_id, name, description)
391
392
393 class NetEaseMusicDjRadioIE(NetEaseMusicBaseIE):
394     IE_NAME = 'netease:djradio'
395     _VALID_URL = r'https?://music\.163\.com/(#/)?djradio\?id=(?P<id>[0-9]+)'
396     _TEST = {
397         'url': 'http://music.163.com/#/djradio?id=42',
398         'info_dict': {
399             'id': '42',
400             'title': '声音蔓延',
401             'description': 'md5:766220985cbd16fdd552f64c578a6b15'
402         },
403         'playlist_mincount': 40,
404     }
405     _PAGE_SIZE = 1000
406
407     def _real_extract(self, url):
408         dj_id = self._match_id(url)
409
410         name = None
411         desc = None
412         entries = []
413         for offset in itertools.count(start=0, step=self._PAGE_SIZE):
414             info = self.query_api(
415                 'dj/program/byradio?asc=false&limit=%d&radioId=%s&offset=%d' 
416                 % (self._PAGE_SIZE, dj_id, offset),
417                 dj_id, 'Downloading dj programs - %d' % offset)
418
419             entries.extend([
420                 self.url_result(
421                     'http://music.163.com/#/program?id=%s' % program['id'],
422                     'NetEaseMusicProgram', program['id'])
423                 for program in info['programs']
424             ])
425
426             if name is None:
427                 radio = info['programs'][0]['radio']
428                 name = radio['name']
429                 desc = radio['desc']
430
431             if not info['more']:
432                 break
433
434         return self.playlist_result(entries, dj_id, name, desc)