2 from __future__ import unicode_literals
4 from hashlib import md5
5 from base64 import b64encode
6 from datetime import datetime
9 from .common import InfoExtractor
10 from ..compat import (
11 compat_urllib_request,
14 compat_itertools_count,
18 class NetEaseMusicBaseIE(InfoExtractor):
19 _FORMATS = ['bMusic', 'mMusic', 'hMusic']
20 _NETEASE_SALT = '3go8&$8*3*3h0k(2)2'
21 _API_BASE = 'http://music.163.com/api/'
24 def _encrypt(cls, dfsid):
25 salt_bytes = bytearray(cls._NETEASE_SALT.encode('utf-8'))
26 string_bytes = bytearray(compat_str(dfsid).encode('ascii'))
27 salt_len = len(salt_bytes)
28 for i in range(len(string_bytes)):
29 string_bytes[i] = string_bytes[i] ^ salt_bytes[i % salt_len]
31 m.update(bytes(string_bytes))
32 result = b64encode(m.digest()).decode('ascii')
33 return result.replace('/', '_').replace('+', '-')
36 def extract_formats(cls, info):
38 for song_format in cls._FORMATS:
39 details = info.get(song_format)
43 'url': 'http://m1.music.126.net/%s/%s.%s' %
44 (cls._encrypt(details['dfsId']), details['dfsId'],
45 details['extension']),
46 'ext': details.get('extension'),
47 'abr': details.get('bitrate', 0) / 1000,
48 'format_id': song_format,
49 'filesize': details.get('size'),
50 'asr': details.get('sr')
55 def convert_milliseconds(cls, ms):
56 return int(round(ms / 1000.0))
58 def query_api(self, endpoint, video_id, note):
59 req = compat_urllib_request.Request('%s%s' % (self._API_BASE, endpoint))
60 req.add_header('Referer', self._API_BASE)
61 return self._download_json(req, video_id, note)
64 class NetEaseMusicIE(NetEaseMusicBaseIE):
65 IE_NAME = 'netease:song'
67 _VALID_URL = r'https?://music\.163\.com/(#/)?song\?id=(?P<id>[0-9]+)'
69 'url': 'http://music.163.com/#/song?id=32102397',
70 'md5': 'f2e97280e6345c74ba9d5677dd5dcb45',
74 'title': 'Bad Blood (feat. Kendrick Lamar)',
75 'creator': 'Taylor Swift / Kendrick Lamar',
76 'upload_date': '20150517',
77 'timestamp': 1431878400,
78 'description': 'md5:a10a54589c2860300d02e1de821eb2ef',
81 'note': 'No lyrics translation.',
82 'url': 'http://music.163.com/#/song?id=29822014',
88 'upload_date': '20141225',
89 'timestamp': 1419523200,
90 'description': 'md5:a4d8d89f44656af206b7b2555c0bce6c',
94 'url': 'http://music.163.com/song?id=17241424',
99 'creator': 'Dustin O\'Halloran',
100 'upload_date': '20080211',
101 'timestamp': 1202745600,
104 'note': 'Has translated name.',
105 'url': 'http://music.163.com/#/song?id=22735043',
109 'title': '소원을 말해봐 (Genie)',
111 'description': 'md5:79d99cc560e4ca97e0c4d86800ee4184',
112 'upload_date': '20100127',
113 'timestamp': 1264608000,
114 'alt_title': '说出愿望吧(Genie)',
118 def _process_lyrics(self, lyrics_info):
119 original = lyrics_info.get('lrc', {}).get('lyric')
120 translated = lyrics_info.get('tlyric', {}).get('lyric')
125 lyrics_expr = r'(\[[0-9]{2}:[0-9]{2}\.[0-9]{2,}\])([^\n]+)'
126 original_ts_texts = re.findall(lyrics_expr, original)
127 translation_ts_dict = dict(
128 (time_stamp, text) for time_stamp, text in re.findall(lyrics_expr, translated)
131 '%s%s / %s' % (time_stamp, text, translation_ts_dict.get(time_stamp, ''))
132 for time_stamp, text in original_ts_texts
136 def _real_extract(self, url):
137 song_id = self._match_id(url)
141 'ids': '[%s]' % song_id
143 info = self.query_api(
144 'song/detail?' + compat_urllib_parse.urlencode(params),
145 song_id, 'Downloading song info')['songs'][0]
147 formats = self.extract_formats(info)
148 self._sort_formats(formats)
150 lyrics_info = self.query_api(
151 'song/lyric?id=%s&lv=-1&tv=-1' % song_id,
152 song_id, 'Downloading lyrics data')
153 lyrics = self._process_lyrics(lyrics_info)
156 if info.get('transNames'):
157 alt_title = '/'.join(info.get('transNames'))
161 'title': info['name'],
162 'alt_title': alt_title,
163 'creator': ' / '.join([artist['name'] for artist in info.get('artists', [])]),
164 'timestamp': self.convert_milliseconds(info.get('album', {}).get('publishTime')),
165 'thumbnail': info.get('album', {}).get('picUrl'),
166 'duration': self.convert_milliseconds(info.get('duration', 0)),
167 'description': lyrics,
172 class NetEaseMusicAlbumIE(NetEaseMusicBaseIE):
173 IE_NAME = 'netease:album'
174 _VALID_URL = r'https?://music\.163\.com/(#/)?album\?id=(?P<id>[0-9]+)'
176 'url': 'http://music.163.com/#/album?id=220780',
181 'playlist_count': 23,
184 def _real_extract(self, url):
185 album_id = self._match_id(url)
187 info = self.query_api(
188 'album/%s?id=%s' % (album_id, album_id),
189 album_id, 'Downloading album data')['album']
192 desc = info.get('description')
194 self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
195 'NetEaseMusic', song['id'])
196 for song in info['songs']
198 return self.playlist_result(entries, album_id, name, desc)
201 class NetEaseMusicSingerIE(NetEaseMusicBaseIE):
202 IE_NAME = 'netease:singer'
203 _VALID_URL = r'https?://music\.163\.com/(#/)?artist\?id=(?P<id>[0-9]+)'
205 'note': 'Singer has aliases.',
206 'url': 'http://music.163.com/#/artist?id=10559',
209 'title': '张惠妹 - aMEI;阿密特',
211 'playlist_count': 50,
213 'note': 'Singer has translated name.',
214 'url': 'http://music.163.com/#/artist?id=124098',
217 'title': '李昇基 - 이승기',
219 'playlist_count': 50,
222 def _real_extract(self, url):
223 singer_id = self._match_id(url)
225 info = self.query_api(
226 'artist/%s?id=%s' % (singer_id, singer_id),
227 singer_id, 'Downloading singer data')
229 name = info['artist']['name']
230 if info['artist']['trans']:
231 name = '%s - %s' % (name, info['artist']['trans'])
232 if info['artist']['alias']:
233 name = '%s - %s' % (name, ';'.join(info['artist']['alias']))
236 self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
237 'NetEaseMusic', song['id'])
238 for song in info['hotSongs']
240 return self.playlist_result(entries, singer_id, name)
243 class NetEaseMusicListIE(NetEaseMusicBaseIE):
244 IE_NAME = 'netease:playlist'
245 _VALID_URL = r'https?://music\.163\.com/(#/)?(playlist|discover/toplist)\?id=(?P<id>[0-9]+)'
247 'url': 'http://music.163.com/#/playlist?id=79177352',
250 'title': 'Billboard 2007 Top 100',
251 'description': 'md5:12fd0819cab2965b9583ace0f8b7b022'
253 'playlist_count': 99,
255 'note': 'Toplist/Charts sample',
256 'url': 'http://music.163.com/#/discover/toplist?id=3733003',
259 'title': 're:韩国Melon排行榜周榜 [0-9]{4}-[0-9]{2}-[0-9]{2}',
260 'description': 'md5:73ec782a612711cadc7872d9c1e134fc',
262 'playlist_count': 50,
265 def _real_extract(self, url):
266 list_id = self._match_id(url)
268 info = self.query_api(
269 'playlist/detail?id=%s&lv=-1&tv=-1' % list_id,
270 list_id, 'Downloading playlist data')['result']
273 desc = info.get('description')
275 if info.get('specialType') == 10: # is a chart/toplist
276 datestamp = datetime.fromtimestamp(
277 self.convert_milliseconds(info['updateTime'])).strftime('%Y-%m-%d')
278 name = '%s %s' % (name, datestamp)
281 self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
282 'NetEaseMusic', song['id'])
283 for song in info['tracks']
285 return self.playlist_result(entries, list_id, name, desc)
288 class NetEaseMusicMvIE(NetEaseMusicBaseIE):
289 IE_NAME = 'netease:mv'
290 _VALID_URL = r'https?://music\.163\.com/(#/)?mv\?id=(?P<id>[0-9]+)'
292 'url': 'http://music.163.com/#/mv?id=415350',
296 'title': '이럴거면 그러지말지',
297 'description': '白雅言自作曲唱甜蜜爱情',
299 'upload_date': '20150520',
303 def _real_extract(self, url):
304 mv_id = self._match_id(url)
306 info = self.query_api(
307 'mv/detail?id=%s&type=mp4' % mv_id,
308 mv_id, 'Downloading mv info')['data']
311 {'url': mv_url, 'ext': 'mp4', 'format_id': '%sp' % brs, 'height': int(brs)}
312 for brs, mv_url in info['brs'].items()
314 self._sort_formats(formats)
318 'title': info['name'],
319 'description': info.get('desc') or info.get('briefDesc'),
320 'creator': info['artistName'],
321 'upload_date': info['publishTime'].replace('-', ''),
323 'thumbnail': info.get('cover'),
324 'duration': self.convert_milliseconds(info.get('duration', 0)),
328 class NetEaseMusicProgramIE(NetEaseMusicBaseIE):
329 IE_NAME = 'netease:program'
330 _VALID_URL = r'https?://music\.163\.com/(#/?)program\?id=(?P<id>[0-9]+)'
332 'url': 'http://music.163.com/#/program?id=10109055',
336 'title': '不丹足球背后的故事',
337 'description': '喜马拉雅人的足球梦 ...',
339 'timestamp': 1434179342,
340 'upload_date': '20150613',
344 'note': 'This program has accompanying songs.',
345 'url': 'http://music.163.com/#/program?id=10141022',
348 'title': '25岁,你是自在如风的少年<27°C>',
349 'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
353 'note': 'This program has accompanying songs.',
354 'url': 'http://music.163.com/#/program?id=10141022',
358 'title': '25岁,你是自在如风的少年<27°C>',
359 'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
360 'timestamp': 1434450841,
361 'upload_date': '20150616',
368 def _real_extract(self, url):
369 program_id = self._match_id(url)
371 info = self.query_api(
372 'dj/program/detail?id=%s' % program_id,
373 program_id, 'Downloading program info')['program']
376 description = info['description']
378 if not info['songs'] or self._downloader.params.get('noplaylist'):
381 'Downloading just the main audio %s because of --no-playlist'
382 % info['mainSong']['id'])
384 formats = self.extract_formats(info['mainSong'])
385 self._sort_formats(formats)
390 'description': description,
391 'creator': info['dj']['brand'],
392 'timestamp': self.convert_milliseconds(info['createTime']),
393 'thumbnail': info['coverUrl'],
394 'duration': self.convert_milliseconds(info.get('duration', 0)),
399 'Downloading playlist %s - add --no-playlist to just download the main audio %s'
400 % (program_id, info['mainSong']['id']))
402 song_ids = [info['mainSong']['id']]
403 song_ids.extend([song['id'] for song in info['songs']])
405 self.url_result('http://music.163.com/#/song?id=%s' % song_id,
406 'NetEaseMusic', song_id)
407 for song_id in song_ids
409 return self.playlist_result(entries, program_id, name, description)
412 class NetEaseMusicDjRadioIE(NetEaseMusicBaseIE):
413 IE_NAME = 'netease:djradio'
414 _VALID_URL = r'https?://music\.163\.com/(#/)?djradio\?id=(?P<id>[0-9]+)'
416 'url': 'http://music.163.com/#/djradio?id=42',
420 'description': 'md5:766220985cbd16fdd552f64c578a6b15'
422 'playlist_mincount': 40,
426 def _real_extract(self, url):
427 dj_id = self._match_id(url)
432 for offset in compat_itertools_count(start=0, step=self._PAGE_SIZE):
433 info = self.query_api(
434 'dj/program/byradio?asc=false&limit=%d&radioId=%s&offset=%d'
435 % (self._PAGE_SIZE, dj_id, offset),
436 dj_id, 'Downloading dj programs - %d' % offset)
440 'http://music.163.com/#/program?id=%s' % program['id'],
441 'NetEaseMusicProgram', program['id'])
442 for program in info['programs']
446 radio = info['programs'][0]['radio']
453 return self.playlist_result(entries, dj_id, name, desc)