5 from base64
import b64encode
6 from binascii
import hexlify
7 from datetime
import datetime
8 from hashlib
import md5
9 from random
import randint
11 from .common
import InfoExtractor
12 from ..aes
import aes_ecb_encrypt
, pkcs7_padding
13 from ..compat
import compat_urllib_parse_urlencode
14 from ..networking
import Request
26 class NetEaseMusicBaseIE(InfoExtractor
):
27 _FORMATS
= ['bMusic', 'mMusic', 'hMusic']
28 _NETEASE_SALT
= '3go8&$8*3*3h0k(2)2'
29 _API_BASE
= 'http://music.163.com/api/'
32 def _encrypt(cls
, dfsid
):
33 salt_bytes
= bytearray(cls
._NETEASE
_SALT
.encode('utf-8'))
34 string_bytes
= bytearray(str(dfsid
).encode('ascii'))
35 salt_len
= len(salt_bytes
)
36 for i
in range(len(string_bytes
)):
37 string_bytes
[i
] = string_bytes
[i
] ^ salt_bytes
[i
% salt_len
]
39 m
.update(bytes(string_bytes
))
40 result
= b64encode(m
.digest()).decode('ascii')
41 return result
.replace('/', '_').replace('+', '-')
43 def make_player_api_request_data_and_headers(self
, song_id
, bitrate
):
44 KEY
= b
'e82ckenh8dichen8'
45 URL
= '/api/song/enhance/player/url'
46 now
= int(time
.time() * 1000)
47 rand
= randint(0, 1000)
54 'buildver': '1623435496',
55 'resolution': '1920x1080',
59 'requestId': '{0}_{1:04}'.format(now
, rand
),
61 request_text
= json
.dumps(
62 {'ids': '[{0}
]'.format(song_id), 'br
': bitrate, 'header
': cookie},
63 separators=(',', ':'))
64 message = 'nobody{0}use{1}md5forencrypt
'.format(
65 URL, request_text).encode('latin1
')
66 msg_digest = md5(message).hexdigest()
68 data = '{0}
-36cd479b6b5
-{1}
-36cd479b6b5
-{2}
'.format(
69 URL, request_text, msg_digest)
70 data = pkcs7_padding(bytes_to_intlist(data))
71 encrypted = intlist_to_bytes(aes_ecb_encrypt(data, bytes_to_intlist(KEY)))
72 encrypted_params = hexlify(encrypted).decode('ascii
').upper()
75 ['{0}
={1}
'.format(k, v if v is not None else 'undefined
')
76 for [k, v] in cookie.items()])
79 'User
-Agent
': self.extractor.get_param('http_headers
')['User
-Agent
'],
80 'Content
-Type
': 'application
/x
-www
-form
-urlencoded
',
81 'Referer
': 'https
://music
.163.com
',
84 return ('params
={0}
'.format(encrypted_params), headers)
86 def _call_player_api(self, song_id, bitrate):
87 url = 'https
://interface3
.music
.163.com
/eapi
/song
/enhance
/player
/url
'
88 data, headers = self.make_player_api_request_data_and_headers(song_id, bitrate)
91 result = self._download_json(
92 url, song_id, data=data.encode('ascii
'), headers=headers)
95 except ExtractorError as e:
96 if type(e.cause) in (ValueError, TypeError):
99 except Exception as e:
100 msg = error_to_compat_str(e)
101 self.report_warning('%s API
call (%s) failed
: %s' % (
102 song_id, bitrate, msg))
105 def extract_formats(self, info):
109 for song_format in self._FORMATS:
110 details = info.get(song_format)
114 bitrate = int_or_none(details.get('bitrate
')) or 999000
115 data = self._call_player_api(song_id, bitrate)
116 for song in try_get(data, lambda x: x['data
'], list) or []:
117 song_url = try_get(song, lambda x: x['url
'])
120 if self._is_valid_url(song_url, info['id'], 'song
'):
123 'ext
': details.get('extension
'),
124 'abr
': float_or_none(song.get('br
'), scale=1000),
125 'format_id
': song_format,
126 'filesize
': int_or_none(song.get('size
')),
127 'asr
': int_or_none(details.get('sr
')),
130 err = try_get(song, lambda x: x['code
'], int)
133 msg = 'No media links found
'
134 if err != 0 and (err < 200 or err >= 400):
135 raise ExtractorError(
136 '%s (site code
%d)' % (msg, err, ), expected=True)
138 self.raise_geo_restricted(
139 msg + ': probably this video
is not available
from your location due to geo restriction
.',
145 def convert_milliseconds(cls, ms):
146 return int(round(ms / 1000.0))
148 def query_api(self, endpoint, video_id, note):
149 req = Request('%s%s' % (self._API_BASE, endpoint))
150 req.headers['Referer
'] = self._API_BASE
151 return self._download_json(req, video_id, note)
154 class NetEaseMusicIE(NetEaseMusicBaseIE):
155 IE_NAME = 'netease
:song
'
157 _VALID_URL = r'https?
://(y\
.)?music\
.163\
.com
/(?
:[#m]/)?song\?.*?\bid=(?P<id>[0-9]+)'
159 'url': 'http://music.163.com/#/song?id=32102397',
160 'md5': '3e909614ce09b1ccef4a3eb205441190',
164 'title': 'Bad Blood',
165 'creator': 'Taylor Swift / Kendrick Lamar',
166 'upload_date': '20150516',
167 'timestamp': 1431792000,
168 'description': 'md5:25fc5f27e47aad975aa6d36382c7833c',
171 'note': 'No lyrics.',
172 'url': 'http://music.163.com/song?id=17241424',
177 'creator': 'Dustin O\'Halloran',
178 'upload_date': '20080211',
179 'description': 'md5:f12945b0f6e0365e3b73c5032e1b0ff4',
180 'timestamp': 1202745600,
183 'note': 'Has translated name.',
184 'url': 'http://music.163.com/#/song?id=22735043',
188 'title': '소원을 말해봐 (Genie)',
190 'description': 'md5:79d99cc560e4ca97e0c4d86800ee4184',
191 'upload_date': '20100127',
192 'timestamp': 1264608000,
193 'alt_title': '说出愿望吧(Genie)',
196 'url': 'https://y.music.163.com/m/song?app_version=8.8.45&id=95670&uct2=sKnvS4+0YStsWkqsPhFijw%3D%3D&dlt=0846',
197 'md5': '95826c73ea50b1c288b22180ec9e754d',
203 'upload_date': '19911130',
204 'timestamp': 691516800,
205 'description': 'md5:1ba2f911a2b0aa398479f595224f2141',
209 def _process_lyrics(self
, lyrics_info
):
210 original
= lyrics_info
.get('lrc', {}).get('lyric')
211 translated
= lyrics_info
.get('tlyric', {}).get('lyric')
216 lyrics_expr
= r
'(\[[0-9]{2}:[0-9]{2}\.[0-9]{2,}\])([^\n]+)'
217 original_ts_texts
= re
.findall(lyrics_expr
, original
)
218 translation_ts_dict
= dict(
219 (time_stamp
, text
) for time_stamp
, text
in re
.findall(lyrics_expr
, translated
)
222 '%s%s / %s' % (time_stamp
, text
, translation_ts_dict
.get(time_stamp
, ''))
223 for time_stamp
, text
in original_ts_texts
227 def _real_extract(self
, url
):
228 song_id
= self
._match
_id
(url
)
232 'ids': '[%s]' % song_id
234 info
= self
.query_api(
235 'song/detail?' + compat_urllib_parse_urlencode(params
),
236 song_id
, 'Downloading song info')['songs'][0]
238 formats
= self
.extract_formats(info
)
240 lyrics_info
= self
.query_api(
241 'song/lyric?id=%s&lv=-1&tv=-1' % song_id
,
242 song_id
, 'Downloading lyrics data')
243 lyrics
= self
._process
_lyrics
(lyrics_info
)
246 if info
.get('transNames'):
247 alt_title
= '/'.join(info
.get('transNames'))
251 'title': info
['name'],
252 'alt_title': alt_title
,
253 'creator': ' / '.join([artist
['name'] for artist
in info
.get('artists', [])]),
254 'timestamp': self
.convert_milliseconds(info
.get('album', {}).get('publishTime')),
255 'thumbnail': info
.get('album', {}).get('picUrl'),
256 'duration': self
.convert_milliseconds(info
.get('duration', 0)),
257 'description': lyrics
,
262 class NetEaseMusicAlbumIE(NetEaseMusicBaseIE
):
263 IE_NAME
= 'netease:album'
264 IE_DESC
= '网易云音乐 - 专辑'
265 _VALID_URL
= r
'https?://music\.163\.com/(#/)?album\?id=(?P<id>[0-9]+)'
267 'url': 'http://music.163.com/#/album?id=220780',
272 'playlist_count': 23,
273 'skip': 'Blocked outside Mainland China',
276 def _real_extract(self
, url
):
277 album_id
= self
._match
_id
(url
)
279 info
= self
.query_api(
280 'album/%s?id=%s' % (album_id
, album_id
),
281 album_id
, 'Downloading album data')['album']
284 desc
= info
.get('description')
286 self
.url_result('http://music.163.com/#/song?id=%s' % song
['id'],
287 'NetEaseMusic', song
['id'])
288 for song
in info
['songs']
290 return self
.playlist_result(entries
, album_id
, name
, desc
)
293 class NetEaseMusicSingerIE(NetEaseMusicBaseIE
):
294 IE_NAME
= 'netease:singer'
295 IE_DESC
= '网易云音乐 - 歌手'
296 _VALID_URL
= r
'https?://music\.163\.com/(#/)?artist\?id=(?P<id>[0-9]+)'
298 'note': 'Singer has aliases.',
299 'url': 'http://music.163.com/#/artist?id=10559',
302 'title': '张惠妹 - aMEI;阿密特',
304 'playlist_count': 50,
305 'skip': 'Blocked outside Mainland China',
307 'note': 'Singer has translated name.',
308 'url': 'http://music.163.com/#/artist?id=124098',
311 'title': '李昇基 - 이승기',
313 'playlist_count': 50,
314 'skip': 'Blocked outside Mainland China',
317 def _real_extract(self
, url
):
318 singer_id
= self
._match
_id
(url
)
320 info
= self
.query_api(
321 'artist/%s?id=%s' % (singer_id
, singer_id
),
322 singer_id
, 'Downloading singer data')
324 name
= info
['artist']['name']
325 if info
['artist']['trans']:
326 name
= '%s - %s' % (name
, info
['artist']['trans'])
327 if info
['artist']['alias']:
328 name
= '%s - %s' % (name
, ';'.join(info
['artist']['alias']))
331 self
.url_result('http://music.163.com/#/song?id=%s' % song
['id'],
332 'NetEaseMusic', song
['id'])
333 for song
in info
['hotSongs']
335 return self
.playlist_result(entries
, singer_id
, name
)
338 class NetEaseMusicListIE(NetEaseMusicBaseIE
):
339 IE_NAME
= 'netease:playlist'
340 IE_DESC
= '网易云音乐 - 歌单'
341 _VALID_URL
= r
'https?://music\.163\.com/(#/)?(playlist|discover/toplist)\?id=(?P<id>[0-9]+)'
343 'url': 'http://music.163.com/#/playlist?id=79177352',
346 'title': 'Billboard 2007 Top 100',
347 'description': 'md5:12fd0819cab2965b9583ace0f8b7b022'
349 'playlist_count': 99,
350 'skip': 'Blocked outside Mainland China',
352 'note': 'Toplist/Charts sample',
353 'url': 'http://music.163.com/#/discover/toplist?id=3733003',
356 'title': 're:韩国Melon排行榜周榜 [0-9]{4}-[0-9]{2}-[0-9]{2}',
357 'description': 'md5:73ec782a612711cadc7872d9c1e134fc',
359 'playlist_count': 50,
360 'skip': 'Blocked outside Mainland China',
363 def _real_extract(self
, url
):
364 list_id
= self
._match
_id
(url
)
366 info
= self
.query_api(
367 'playlist/detail?id=%s&lv=-1&tv=-1' % list_id
,
368 list_id
, 'Downloading playlist data')['result']
371 desc
= info
.get('description')
373 if info
.get('specialType') == 10: # is a chart/toplist
374 datestamp
= datetime
.fromtimestamp(
375 self
.convert_milliseconds(info
['updateTime'])).strftime('%Y-%m-%d')
376 name
= '%s %s' % (name
, datestamp
)
379 self
.url_result('http://music.163.com/#/song?id=%s' % song
['id'],
380 'NetEaseMusic', song
['id'])
381 for song
in info
['tracks']
383 return self
.playlist_result(entries
, list_id
, name
, desc
)
386 class NetEaseMusicMvIE(NetEaseMusicBaseIE
):
387 IE_NAME
= 'netease:mv'
388 IE_DESC
= '网易云音乐 - MV'
389 _VALID_URL
= r
'https?://music\.163\.com/(#/)?mv\?id=(?P<id>[0-9]+)'
391 'url': 'http://music.163.com/#/mv?id=415350',
395 'title': '이럴거면 그러지말지',
396 'description': '白雅言自作曲唱甜蜜爱情',
398 'upload_date': '20150520',
400 'skip': 'Blocked outside Mainland China',
403 def _real_extract(self
, url
):
404 mv_id
= self
._match
_id
(url
)
406 info
= self
.query_api(
407 'mv/detail?id=%s&type=mp4' % mv_id
,
408 mv_id
, 'Downloading mv info')['data']
411 {'url': mv_url, 'ext': 'mp4', 'format_id': '%sp' % brs, 'height': int(brs)}
412 for brs
, mv_url
in info
['brs'].items()
417 'title': info
['name'],
418 'description': info
.get('desc') or info
.get('briefDesc'),
419 'creator': info
['artistName'],
420 'upload_date': info
['publishTime'].replace('-', ''),
422 'thumbnail': info
.get('cover'),
423 'duration': self
.convert_milliseconds(info
.get('duration', 0)),
427 class NetEaseMusicProgramIE(NetEaseMusicBaseIE
):
428 IE_NAME
= 'netease:program'
429 IE_DESC
= '网易云音乐 - 电台节目'
430 _VALID_URL
= r
'https?://music\.163\.com/(#/?)program\?id=(?P<id>[0-9]+)'
432 'url': 'http://music.163.com/#/program?id=10109055',
436 'title': '不丹足球背后的故事',
437 'description': '喜马拉雅人的足球梦 ...',
439 'timestamp': 1434179342,
440 'upload_date': '20150613',
443 'skip': 'Blocked outside Mainland China',
445 'note': 'This program has accompanying songs.',
446 'url': 'http://music.163.com/#/program?id=10141022',
449 'title': '25岁,你是自在如风的少年<27°C>',
450 'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
453 'skip': 'Blocked outside Mainland China',
455 'note': 'This program has accompanying songs.',
456 'url': 'http://music.163.com/#/program?id=10141022',
460 'title': '25岁,你是自在如风的少年<27°C>',
461 'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
462 'timestamp': 1434450841,
463 'upload_date': '20150616',
468 'skip': 'Blocked outside Mainland China',
471 def _real_extract(self
, url
):
472 program_id
= self
._match
_id
(url
)
474 info
= self
.query_api(
475 'dj/program/detail?id=%s' % program_id
,
476 program_id
, 'Downloading program info')['program']
479 description
= info
['description']
481 if not self
._yes
_playlist
(info
['songs'] and program_id
, info
['mainSong']['id']):
482 formats
= self
.extract_formats(info
['mainSong'])
485 'id': info
['mainSong']['id'],
487 'description': description
,
488 'creator': info
['dj']['brand'],
489 'timestamp': self
.convert_milliseconds(info
['createTime']),
490 'thumbnail': info
['coverUrl'],
491 'duration': self
.convert_milliseconds(info
.get('duration', 0)),
495 song_ids
= [info
['mainSong']['id']]
496 song_ids
.extend([song
['id'] for song
in info
['songs']])
498 self
.url_result('http://music.163.com/#/song?id=%s' % song_id
,
499 'NetEaseMusic', song_id
)
500 for song_id
in song_ids
502 return self
.playlist_result(entries
, program_id
, name
, description
)
505 class NetEaseMusicDjRadioIE(NetEaseMusicBaseIE
):
506 IE_NAME
= 'netease:djradio'
507 IE_DESC
= '网易云音乐 - 电台'
508 _VALID_URL
= r
'https?://music\.163\.com/(#/)?djradio\?id=(?P<id>[0-9]+)'
510 'url': 'http://music.163.com/#/djradio?id=42',
514 'description': 'md5:766220985cbd16fdd552f64c578a6b15'
516 'playlist_mincount': 40,
517 'skip': 'Blocked outside Mainland China',
521 def _real_extract(self
, url
):
522 dj_id
= self
._match
_id
(url
)
527 for offset
in itertools
.count(start
=0, step
=self
._PAGE
_SIZE
):
528 info
= self
.query_api(
529 'dj/program/byradio?asc=false&limit=%d&radioId=%s&offset=%d'
530 % (self
._PAGE
_SIZE
, dj_id
, offset
),
531 dj_id
, 'Downloading dj programs - %d' % offset
)
535 'http://music.163.com/#/program?id=%s' % program
['id'],
536 'NetEaseMusicProgram', program
['id'])
537 for program
in info
['programs']
541 radio
= info
['programs'][0]['radio']
548 return self
.playlist_result(entries
, dj_id
, name
, desc
)