2 from __future__ import unicode_literals
4 from hashlib import md5
5 from datetime import datetime
9 from .common import InfoExtractor
10 from ..compat import (
11 compat_urllib_request,
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/'
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]
29 m.update(string_bytes)
30 result = m.digest().encode('base64')[:-1]
31 return result.replace('/', '_').replace('+', '-')
34 def extract_formats(cls, info):
36 for song_format in cls._FORMATS:
37 details = info.get(song_format)
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'],
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)
59 class NetEaseMusicIE(NetEaseMusicBaseIE):
60 IE_NAME = 'netease:song'
61 _VALID_URL = r'https?://music\.163\.com/(#/)?song\?id=(?P<id>[0-9]+)'
63 'url': 'http://music.163.com/#/song?id=32102397',
64 'md5': 'f2e97280e6345c74ba9d5677dd5dcb45',
68 'title': 'Bad Blood (feat. Kendrick Lamar)',
69 'creator': 'Taylor Swift / Kendrick Lamar',
70 'upload_date': '20150517',
71 'timestamp': 1431878400,
72 'description': 'md5:a10a54589c2860300d02e1de821eb2ef',
75 'note': 'No lyrics translation.',
76 'url': 'http://music.163.com/#/song?id=29822014',
82 'upload_date': '20141225',
83 'timestamp': 1419523200,
84 'description': 'md5:a4d8d89f44656af206b7b2555c0bce6c',
88 'url': 'http://music.163.com/song?id=17241424',
93 'creator': 'Dustin O\'Halloran',
94 'upload_date': '20080211',
95 'timestamp': 1202745600,
99 def _process_lyrics(self, lyrics_info):
100 original = lyrics_info.get('lrc', {}).get('lyric')
101 translated = lyrics_info.get('tlyric', {}).get('lyric')
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)
113 '%s%s / %s' % (time_stamp, text, translation_ts_dict.get(time_stamp, ''))
114 for time_stamp, text in original_ts_texts
118 def _real_extract(self, url):
119 song_id = self._match_id(url)
123 'ids': '[%s]' % song_id
125 info = self.query_api(
126 'song/detail?' + compat_urllib_parse.urlencode(params),
127 song_id, 'Downloading song info')['songs'][0]
129 formats = self.extract_formats(info)
130 self._sort_formats(formats)
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)
138 if info.get('alias'):
139 alt_title = '/'.join(info.get('alias'))
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,
154 class NetEaseMusicAlbumIE(NetEaseMusicBaseIE):
155 IE_NAME = 'netease:album'
156 _VALID_URL = r'https?://music\.163\.com/(#/)?album\?id=(?P<id>[0-9]+)'
158 'url': 'http://music.163.com/#/album?id=220780',
163 'playlist_count': 23,
166 def _real_extract(self, url):
167 album_id = self._match_id(url)
169 info = self.query_api(
170 'album/%s?id=%s' % (album_id, album_id),
171 album_id, 'Downloading album data')['album']
174 desc = info.get('description')
176 self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
177 'NetEaseMusic', song['id'])
178 for song in info['songs']
180 return self.playlist_result(entries, album_id, name, desc)
183 class NetEaseMusicSingerIE(NetEaseMusicBaseIE):
184 IE_NAME = 'netease:singer'
185 _VALID_URL = r'https?://music\.163\.com/(#/)?artist\?id=(?P<id>[0-9]+)'
187 'note': 'Singer has aliases.',
188 'url': 'http://music.163.com/#/artist?id=10559',
191 'title': '张惠妹 - aMEI;阿密特',
193 'playlist_count': 50,
195 'note': 'Singer has translated name.',
196 'url': 'http://music.163.com/#/artist?id=124098',
199 'title': '李昇基 - 이승기',
201 'playlist_count': 50,
204 def _real_extract(self, url):
205 singer_id = self._match_id(url)
207 info = self.query_api(
208 'artist/%s?id=%s' % (singer_id, singer_id),
209 singer_id, 'Downloading singer data')
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']))
218 self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
219 'NetEaseMusic', song['id'])
220 for song in info['hotSongs']
222 return self.playlist_result(entries, singer_id, name)
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]+)'
229 'url': 'http://music.163.com/#/playlist?id=79177352',
232 'title': 'Billboard 2007 Top 100',
233 'description': 'md5:12fd0819cab2965b9583ace0f8b7b022'
235 'playlist_count': 99,
237 'note': 'Toplist/Charts sample',
238 'url': 'http://music.163.com/#/discover/toplist?id=3733003',
241 'title': 're:韩国Melon排行榜周榜 [0-9]{4}-[0-9]{2}-[0-9]{2}',
242 'description': 'md5:73ec782a612711cadc7872d9c1e134fc',
244 'playlist_count': 50,
247 def _real_extract(self, url):
248 list_id = self._match_id(url)
250 info = self.query_api(
251 'playlist/detail?id=%s&lv=-1&tv=-1' % list_id,
252 list_id, 'Downloading playlist data')['result']
255 desc = info.get('description')
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)
262 self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
263 'NetEaseMusic', song['id'])
264 for song in info['tracks']
266 return self.playlist_result(entries, list_id, name, desc)
269 class NetEaseMusicMvIE(NetEaseMusicBaseIE):
270 IE_NAME = 'netease:mv'
271 _VALID_URL = r'https?://music\.163\.com/(#/)?mv\?id=(?P<id>[0-9]+)'
273 'url': 'http://music.163.com/#/mv?id=415350',
277 'title': '이럴거면 그러지말지',
278 'description': '白雅言自作曲唱甜蜜爱情',
280 'upload_date': '20150520',
284 def _real_extract(self, url):
285 mv_id = self._match_id(url)
287 info = self.query_api(
288 'mv/detail?id=%s&type=mp4' % mv_id,
289 mv_id, 'Downloading mv info')['data']
292 {'url': mv_url, 'ext': 'mp4', 'format_id': '%sp' % brs, 'preference': int(brs)}
293 for brs, mv_url in info['brs'].items()
295 self._sort_formats(formats)
299 'title': info['name'],
300 'description': info.get('desc') or info.get('briefDesc'),
301 'creator': info['artistName'],
302 'upload_date': info['publishTime'].replace('-', ''),
304 'thumbnail': info.get('cover'),
305 'duration': int(info.get('duration', 0)/1000),
309 class NetEaseMusicProgramIE(NetEaseMusicBaseIE):
310 IE_NAME = 'netease:program'
311 _VALID_URL = r'https?://music\.163\.com/(#/?)program\?id=(?P<id>[0-9]+)'
313 'url': 'http://music.163.com/#/program?id=10109055',
317 'title': '不丹足球背后的故事',
318 'description': '喜马拉雅人的足球梦 ...',
320 'timestamp': 1434179341,
321 'upload_date': '20150613',
325 'note': 'This program has accompanying songs.',
326 'url': 'http://music.163.com/#/program?id=10141022',
329 'title': '25岁,你是自在如风的少年<27°C>',
330 'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
334 'note': 'This program has accompanying songs.',
335 'url': 'http://music.163.com/#/program?id=10141022',
339 'title': '25岁,你是自在如风的少年<27°C>',
340 'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
341 'timestamp': 1434450840,
342 'upload_date': '20150616',
349 def _real_extract(self, url):
350 program_id = self._match_id(url)
352 info = self.query_api(
353 'dj/program/detail?id=%s' % program_id,
354 program_id, 'Downloading program info')['program']
357 description = info['description']
359 if not info['songs'] or self._downloader.params.get('noplaylist'):
362 'Downloading just the main audio %s because of --no-playlist'
363 % info['mainSong']['id'])
365 formats = self.extract_formats(info['mainSong'])
366 self._sort_formats(formats)
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),
380 'Downloading playlist %s - add --no-playlist to just download the main audio %s'
381 % (program_id, info['mainSong']['id']))
383 song_ids = [info['mainSong']['id']]
384 song_ids.extend([song['id'] for song in info['songs']])
386 self.url_result('http://music.163.com/#/song?id=%s' % song_id,
387 'NetEaseMusic', song_id)
388 for song_id in song_ids
390 return self.playlist_result(entries, program_id, name, description)
393 class NetEaseMusicDjRadioIE(NetEaseMusicBaseIE):
394 IE_NAME = 'netease:djradio'
395 _VALID_URL = r'https?://music\.163\.com/(#/)?djradio\?id=(?P<id>[0-9]+)'
397 'url': 'http://music.163.com/#/djradio?id=42',
401 'description': 'md5:766220985cbd16fdd552f64c578a6b15'
403 'playlist_mincount': 40,
407 def _real_extract(self, url):
408 dj_id = self._match_id(url)
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)
421 'http://music.163.com/#/program?id=%s' % program['id'],
422 'NetEaseMusicProgram', program['id'])
423 for program in info['programs']
427 radio = info['programs'][0]['radio']
434 return self.playlist_result(entries, dj_id, name, desc)