8 from .common
import InfoExtractor
9 from ..aes
import aes_ecb_encrypt
, pkcs7_padding
24 class NetEaseMusicBaseIE(InfoExtractor
):
25 # XXX: _extract_formats logic depends on the order of the levels in each tier
27 'standard', # free tier; 标准; 128kbps mp3 or aac
28 'higher', # free tier; 192kbps mp3 or aac
29 'exhigh', # free tier; 极高 (HQ); 320kbps mp3 or aac
30 'lossless', # VIP tier; 无损 (SQ); 48kHz/16bit flac
31 'hires', # VIP tier; 高解析度无损 (Hi-Res); 192kHz/24bit flac
32 'jyeffect', # VIP tier; 高清臻音 (Spatial Audio); 96kHz/24bit flac
33 'jymaster', # SVIP tier; 超清母带 (Master); 192kHz/24bit flac
34 'sky', # SVIP tier; 沉浸环绕声 (Surround Audio); flac
36 _API_BASE
= 'http://music.163.com/api/'
40 def _kilo_or_none(value
):
41 return int_or_none(value
, scale
=1000)
43 def _create_eapi_cipher(self
, api_path
, query_body
, cookies
):
44 request_text
= json
.dumps({**query_body
, 'header': cookies
}, separators
=(',', ':'))
46 message
= f
'nobody{api_path}use{request_text}md5forencrypt'.encode('latin1')
47 msg_digest
= hashlib
.md5(message
).hexdigest()
49 data
= pkcs7_padding(list(str.encode(
50 f
'{api_path}-36cd479b6b5-{request_text}-36cd479b6b5-{msg_digest}')))
51 encrypted
= bytes(aes_ecb_encrypt(data
, list(b
'e82ckenh8dichen8')))
52 return f
'params={encrypted.hex().upper()}'.encode()
54 def _download_eapi_json(self
, path
, video_id
, query_body
, headers
={}, **kwargs
):
57 'deviceId': 'undefined',
60 'mobilename': 'undefined',
61 'buildver': '1623435496',
62 'resolution': '1920x1080',
65 'channel': 'undefined',
66 'requestId': f
'{int(time.time() * 1000)}_{random.randint(0, 1000):04}',
67 **traverse_obj(self
._get
_cookies
(self
._API
_BASE
), {
68 'MUSIC_U': ('MUSIC_U', {lambda i
: i
.value
}),
71 return self
._download
_json
(
72 urljoin('https://interface3.music.163.com/', f
'/eapi{path}'), video_id
,
73 data
=self
._create
_eapi
_cipher
(f
'/api{path}', query_body
, cookies
), headers
={
74 'Referer': 'https://music.163.com',
75 'Cookie': '; '.join([f
'{k}={v}' for k
, v
in cookies
.items()]),
79 def _call_player_api(self
, song_id
, level
):
80 return self
._download
_eapi
_json
(
81 '/song/enhance/player/url/v1', song_id
,
82 {'ids': f
'[{song_id}]', 'level': level
, 'encodeType': 'flac'},
83 note
=f
'Downloading song URL info: level {level}')
85 def _extract_formats(self
, info
):
88 for level
in self
._LEVELS
:
90 self
._call
_player
_api
(song_id
, level
), ('data', lambda _
, v
: url_or_none(v
['url']), any
))
92 break # Media is not available due to removal or geo-restriction
93 actual_level
= song
.get('level')
94 if actual_level
and actual_level
!= level
:
95 if level
in ('lossless', 'jymaster'):
96 break # We've already extracted the highest level of the user's account tier
102 **traverse_obj(song
, {
103 'ext': ('type', {str}
),
104 'abr': ('br', {self
._kilo
_or
_none
}),
105 'filesize': ('size', {int_or_none}
),
109 break # Only 1 level is available if API does not return a value (netease:program)
111 self
.raise_geo_restricted(
112 'No media links found; possibly due to geo restriction', countries
=['CN'])
115 def _query_api(self
, endpoint
, video_id
, note
):
116 result
= self
._download
_json
(
117 f
'{self._API_BASE}{endpoint}', video_id
, note
, headers
={'Referer': self
._API
_BASE
})
118 code
= traverse_obj(result
, ('code', {int}
))
119 message
= traverse_obj(result
, ('message', {str}
)) or ''
121 self
.raise_login_required(f
'Login required to download: {message}')
123 raise ExtractorError(f
'Failed to get meta info: {code} {message}')
126 def _get_entries(self
, songs_data
, entry_keys
=None, id_key
='id', name_key
='name'):
127 for song
in traverse_obj(songs_data
, (
128 *variadic(entry_keys
, (str, bytes
, dict, set)),
129 lambda _
, v
: int_or_none(v
[id_key
]) is not None)):
130 song_id
= str(song
[id_key
])
131 yield self
.url_result(
132 f
'http://music.163.com/#/song?id={song_id}', NetEaseMusicIE
,
133 song_id
, traverse_obj(song
, (name_key
, {str}
)))
136 class NetEaseMusicIE(NetEaseMusicBaseIE
):
137 IE_NAME
= 'netease:song'
139 _VALID_URL
= r
'https?://(?:y\.)?music\.163\.com/(?:[#m]/)?song\?.*?\bid=(?P<id>[0-9]+)'
141 'url': 'https://music.163.com/#/song?id=550136151',
145 'title': 'It\'s Ok (Live)',
146 'creators': 'count:10',
147 'timestamp': 1522944000,
148 'upload_date': '20180405',
149 'description': 'md5:9fd07059c2ccee3950dc8363429a3135',
151 'thumbnail': r
're:^http.*\.jpg',
152 'album': '偶像练习生 表演曲目合集',
153 'average_rating': int,
154 'album_artists': ['偶像练习生'],
157 'url': 'http://music.163.com/song?id=17241424',
162 'upload_date': '20080211',
163 'timestamp': 1202745600,
165 'thumbnail': r
're:^http.*\.jpg',
166 'album': 'Piano Solos Vol. 2',
167 'album_artist': 'Dustin O\'Halloran',
168 'average_rating': int,
169 'description': '[00:05.00]纯音乐,请欣赏\n',
170 'album_artists': ['Dustin O\'Halloran'],
171 'creators': ['Dustin O\'Halloran'],
172 'subtitles': {'lyrics': [{'ext': 'lrc'}]},
175 'url': 'https://y.music.163.com/m/song?app_version=8.8.45&id=95670&uct2=sKnvS4+0YStsWkqsPhFijw%3D%3D&dlt=0846',
176 'md5': 'b896be78d8d34bd7bb665b26710913ff',
181 'upload_date': '19911130',
182 'timestamp': 691516800,
183 'description': 'md5:1ba2f911a2b0aa398479f595224f2141',
184 'subtitles': {'lyrics': [{'ext': 'lrc'}]},
186 'alt_title': '伴唱:现代人乐队 合唱:总政歌舞团',
187 'thumbnail': r
're:^http.*\.jpg',
188 'average_rating': int,
190 'album_artist': '侯牧人',
192 'album_artists': ['侯牧人'],
195 'url': 'http://music.163.com/#/song?id=32102397',
196 'md5': '3e909614ce09b1ccef4a3eb205441190',
200 'title': 'Bad Blood',
201 'creators': ['Taylor Swift', 'Kendrick Lamar'],
202 'upload_date': '20150516',
203 'timestamp': 1431792000,
204 'description': 'md5:21535156efb73d6d1c355f95616e285a',
205 'subtitles': {'lyrics': [{'ext': 'lrc'}]},
207 'thumbnail': r
're:^http.*\.jpg',
208 'album': 'Bad Blood',
209 'average_rating': int,
210 'album_artist': 'Taylor Swift',
212 'skip': 'Blocked outside Mainland China',
214 'note': 'Has translated name.',
215 'url': 'http://music.163.com/#/song?id=22735043',
219 'title': '소원을 말해봐 (Genie)',
220 'creators': ['少女时代'],
221 'upload_date': '20100127',
222 'timestamp': 1264608000,
223 'description': 'md5:03d1ffebec3139aa4bafe302369269c5',
224 'subtitles': {'lyrics': [{'ext': 'lrc'}]},
226 'alt_title': '说出愿望吧(Genie)',
227 'thumbnail': r
're:^http.*\.jpg',
228 'average_rating': int,
230 'album_artist': '少女时代',
232 'skip': 'Blocked outside Mainland China',
235 def _process_lyrics(self
, lyrics_info
):
236 original
= traverse_obj(lyrics_info
, ('lrc', 'lyric', {str}
))
237 translated
= traverse_obj(lyrics_info
, ('tlyric', 'lyric', {str}
))
239 if not original
or original
== '[99:00.00]纯音乐,请欣赏\n':
244 'lyrics': [{'data': original
, 'ext': 'lrc'}],
247 lyrics_expr
= r
'(\[[0-9]{2}:[0-9]{2}\.[0-9]{2,}\])([^\n]+)'
248 original_ts_texts
= re
.findall(lyrics_expr
, original
)
249 translation_ts_dict
= dict(re
.findall(lyrics_expr
, translated
))
252 join_nonempty(f
'{timestamp}{text}', translation_ts_dict
.get(timestamp
, ''), delim
=' / ')
253 for timestamp
, text
in original_ts_texts
)
256 'lyrics_merged': [{'data': merged
, 'ext': 'lrc'}],
257 'lyrics': [{'data': original
, 'ext': 'lrc'}],
258 'lyrics_translated': [{'data': translated
, 'ext': 'lrc'}],
261 def _real_extract(self
, url
):
262 song_id
= self
._match
_id
(url
)
264 info
= self
._query
_api
(
265 f
'song/detail?id={song_id}&ids=%5B{song_id}%5D', song_id
, 'Downloading song info')['songs'][0]
267 formats
= self
._extract
_formats
(info
)
269 lyrics
= self
._process
_lyrics
(self
._query
_api
(
270 f
'song/lyric?id={song_id}&lv=-1&tv=-1', song_id
, 'Downloading lyrics data'))
272 'description': traverse_obj(lyrics
, (('lyrics_merged', 'lyrics'), 0, 'data'), get_all
=False),
279 'alt_title': '/'.join(traverse_obj(info
, (('transNames', 'alias'), ...))) or None,
280 'creators': traverse_obj(info
, ('artists', ..., 'name')) or None,
281 'album_artists': traverse_obj(info
, ('album', 'artists', ..., 'name')) or None,
283 **traverse_obj(info
, {
284 'title': ('name', {str}
),
285 'timestamp': ('album', 'publishTime', {self
._kilo
_or
_none
}),
286 'thumbnail': ('album', 'picUrl', {url_or_none}
),
287 'duration': ('duration', {self
._kilo
_or
_none
}),
288 'album': ('album', 'name', {str}
),
289 'average_rating': ('score', {int_or_none}
),
294 class NetEaseMusicAlbumIE(NetEaseMusicBaseIE
):
295 IE_NAME
= 'netease:album'
296 IE_DESC
= '网易云音乐 - 专辑'
297 _VALID_URL
= r
'https?://music\.163\.com/(?:#/)?album\?id=(?P<id>[0-9]+)'
299 'url': 'https://music.163.com/#/album?id=133153666',
303 'upload_date': '20210913',
304 'description': '桃几2021年翻唱合集',
305 'thumbnail': r
're:^http.*\.jpg',
307 'playlist_mincount': 12,
309 'url': 'http://music.163.com/#/album?id=220780',
313 'upload_date': '20060904',
314 'description': 'md5:71a74e1d8f392d88cf1bbe48879ad0b0',
315 'thumbnail': r
're:^http.*\.jpg',
317 'playlist_count': 23,
320 def _real_extract(self
, url
):
321 album_id
= self
._match
_id
(url
)
322 webpage
= self
._download
_webpage
(f
'https://music.163.com/album?id={album_id}', album_id
)
324 songs
= self
._search
_json
(
325 r
'<textarea[^>]+\bid="song-list-pre-data"[^>]*>', webpage
, 'metainfo', album_id
,
326 end_pattern
=r
'</textarea>', contains_pattern
=r
'\[(?s:.+)\]')
328 'title': self
._og
_search
_property
('title', webpage
, 'title', fatal
=False),
329 'description': self
._html
_search
_regex
(
330 (rf
'<div[^>]+\bid="album-desc-{suffix}"[^>]*>(.*?)</div>' for suffix
in ('more', 'dot')),
331 webpage
, 'description', flags
=re
.S
, fatal
=False),
332 'thumbnail': self
._og
_search
_property
('image', webpage
, 'thumbnail', fatal
=False),
333 'upload_date': unified_strdate(self
._html
_search
_meta
('music:release_date', webpage
, 'date', fatal
=False)),
335 return self
.playlist_result(self
._get
_entries
(songs
), album_id
, **metainfo
)
338 class NetEaseMusicSingerIE(NetEaseMusicBaseIE
):
339 IE_NAME
= 'netease:singer'
340 IE_DESC
= '网易云音乐 - 歌手'
341 _VALID_URL
= r
'https?://music\.163\.com/(?:#/)?artist\?id=(?P<id>[0-9]+)'
343 'note': 'Singer has aliases.',
344 'url': 'http://music.163.com/#/artist?id=10559',
347 'title': '张惠妹 - aMEI;阿妹;阿密特',
349 'playlist_count': 50,
351 'note': 'Singer has translated name.',
352 'url': 'http://music.163.com/#/artist?id=124098',
355 'title': '李昇基 - 이승기',
357 'playlist_count': 50,
359 'note': 'Singer with both translated and alias',
360 'url': 'https://music.163.com/#/artist?id=159692',
363 'title': '初音ミク - 初音未来;Hatsune Miku',
365 'playlist_count': 50,
368 def _real_extract(self
, url
):
369 singer_id
= self
._match
_id
(url
)
371 info
= self
._query
_api
(
372 f
'artist/{singer_id}?id={singer_id}', singer_id
, note
='Downloading singer data')
374 name
= join_nonempty(
375 traverse_obj(info
, ('artist', 'name', {str}
)),
376 join_nonempty(*traverse_obj(info
, ('artist', ('trans', ('alias', ...)), {str}
)), delim
=';'),
379 return self
.playlist_result(self
._get
_entries
(info
, 'hotSongs'), singer_id
, name
)
382 class NetEaseMusicListIE(NetEaseMusicBaseIE
):
383 IE_NAME
= 'netease:playlist'
384 IE_DESC
= '网易云音乐 - 歌单'
385 _VALID_URL
= r
'https?://music\.163\.com/(?:#/)?(?:playlist|discover/toplist)\?id=(?P<id>[0-9]+)'
387 'url': 'http://music.163.com/#/playlist?id=79177352',
390 'title': 'Billboard 2007 Top 100',
391 'description': 'md5:12fd0819cab2965b9583ace0f8b7b022',
394 'uploader_id': '67549805',
396 'upload_date': r
're:\d{8}',
398 'playlist_mincount': 95,
400 'note': 'Toplist/Charts sample',
401 'url': 'https://music.163.com/#/discover/toplist?id=60198',
404 'title': 're:美国Billboard榜 [0-9]{4}-[0-9]{2}-[0-9]{2}',
405 'description': '美国Billboard排行榜',
406 'tags': ['流行', '欧美', '榜单'],
407 'uploader': 'Billboard公告牌',
408 'uploader_id': '48171',
410 'upload_date': r
're:\d{8}',
412 'playlist_count': 100,
414 'note': 'Toplist/Charts sample',
415 'url': 'http://music.163.com/#/discover/toplist?id=3733003',
418 'title': 're:韩国Melon排行榜周榜(?: [0-9]{4}-[0-9]{2}-[0-9]{2})?',
419 'description': 'md5:73ec782a612711cadc7872d9c1e134fc',
420 'upload_date': '20200109',
421 'uploader_id': '2937386',
422 'tags': ['韩语', '榜单'],
423 'uploader': 'Melon榜单',
424 'timestamp': 1578569373,
426 'playlist_count': 50,
429 def _real_extract(self
, url
):
430 list_id
= self
._match
_id
(url
)
432 info
= self
._download
_eapi
_json
(
433 '/v3/playlist/detail', list_id
,
434 {'id': list_id
, 't': '-1', 'n': '500', 's': '0'},
435 note
='Downloading playlist info')
437 metainfo
= traverse_obj(info
, ('playlist', {
438 'title': ('name', {str}
),
439 'description': ('description', {str}
),
440 'tags': ('tags', ..., {str}
),
441 'uploader': ('creator', 'nickname', {str}
),
442 'uploader_id': ('creator', 'userId', {str_or_none}
),
443 'timestamp': ('updateTime', {self
._kilo
_or
_none
}),
445 if traverse_obj(info
, ('playlist', 'specialType')) == 10:
446 metainfo
['title'] = f
'{metainfo.get("title")} {strftime_or_none(metainfo.get("timestamp"), "%Y-%m-%d")}'
448 return self
.playlist_result(self
._get
_entries
(info
, ('playlist', 'tracks')), list_id
, **metainfo
)
451 class NetEaseMusicMvIE(NetEaseMusicBaseIE
):
452 IE_NAME
= 'netease:mv'
453 IE_DESC
= '网易云音乐 - MV'
454 _VALID_URL
= r
'https?://music\.163\.com/(?:#/)?mv\?id=(?P<id>[0-9]+)'
456 'url': 'https://music.163.com/#/mv?id=10958064',
461 'description': 'md5:e845872cff28820642a2b02eda428fea',
463 'upload_date': '20200916',
464 'thumbnail': r
're:http.*\.jpg',
468 'comment_count': int,
471 'url': 'http://music.163.com/#/mv?id=415350',
475 'title': '이럴거면 그러지말지',
476 'description': '白雅言自作曲唱甜蜜爱情',
478 'upload_date': '20150520',
479 'thumbnail': r
're:http.*\.jpg',
483 'comment_count': int,
485 'skip': 'Blocked outside Mainland China',
487 'note': 'This MV has multiple creators.',
488 'url': 'https://music.163.com/#/mv?id=22593543',
493 'creators': ['秃子2z', '辉子', 'Saber梁维嘉'],
495 'upload_date': '20240618',
497 'comment_count': int,
498 'thumbnail': r
're:http.*\.jpg',
503 def _real_extract(self
, url
):
504 mv_id
= self
._match
_id
(url
)
506 info
= self
._query
_api
(
507 f
'mv/detail?id={mv_id}&type=mp4', mv_id
, 'Downloading mv info')['data']
510 {'url': mv_url
, 'ext': 'mp4', 'format_id': f
'{brs}p', 'height': int_or_none(brs
)}
511 for brs
, mv_url
in info
['brs'].items()
517 'creators': traverse_obj(info
, ('artists', ..., 'name')) or [info
.get('artistName')],
518 **traverse_obj(info
, {
519 'title': ('name', {str}
),
520 'description': (('desc', 'briefDesc'), {str}
, {lambda x
: x
or None}),
521 'upload_date': ('publishTime', {unified_strdate}
),
522 'thumbnail': ('cover', {url_or_none}
),
523 'duration': ('duration', {self
._kilo
_or
_none
}),
524 'view_count': ('playCount', {int_or_none}
),
525 'like_count': ('likeCount', {int_or_none}
),
526 'comment_count': ('commentCount', {int_or_none}
),
531 class NetEaseMusicProgramIE(NetEaseMusicBaseIE
):
532 IE_NAME
= 'netease:program'
533 IE_DESC
= '网易云音乐 - 电台节目'
534 _VALID_URL
= r
'https?://music\.163\.com/(?:#/)?program\?id=(?P<id>[0-9]+)'
536 'url': 'http://music.163.com/#/program?id=10109055',
540 'title': '不丹足球背后的故事',
541 'description': '喜马拉雅人的足球梦 ...',
542 'creators': ['大话西藏'],
543 'timestamp': 1434179287,
544 'upload_date': '20150613',
545 'thumbnail': r
're:http.*\.jpg',
549 'note': 'This program has accompanying songs.',
550 'url': 'http://music.163.com/#/program?id=10141022',
553 'title': '滚滚电台的有声节目',
554 'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
555 'creators': ['滚滚电台ORZ'],
556 'timestamp': 1434450733,
557 'upload_date': '20150616',
558 'thumbnail': r
're:http.*\.jpg',
562 'note': 'This program has accompanying songs.',
563 'url': 'http://music.163.com/#/program?id=10141022',
567 'title': '滚滚电台的有声节目',
568 'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
569 'creators': ['滚滚电台ORZ'],
570 'timestamp': 1434450733,
571 'upload_date': '20150616',
572 'thumbnail': r
're:http.*\.jpg',
580 def _real_extract(self
, url
):
581 program_id
= self
._match
_id
(url
)
583 info
= self
._query
_api
(
584 f
'dj/program/detail?id={program_id}', program_id
, note
='Downloading program info')['program']
586 metainfo
= traverse_obj(info
, {
587 'title': ('name', {str}
),
588 'description': ('description', {str}
),
589 'creator': ('dj', 'brand', {str}
),
590 'thumbnail': ('coverUrl', {url_or_none}
),
591 'timestamp': ('createTime', {self
._kilo
_or
_none
}),
594 if not self
._yes
_playlist
(
595 info
['songs'] and program_id
, info
['mainSong']['id'], playlist_label
='program', video_label
='song'):
596 formats
= self
._extract
_formats
(info
['mainSong'])
599 'id': str(info
['mainSong']['id']),
601 'duration': traverse_obj(info
, ('mainSong', 'duration', {self
._kilo
_or
_none
})),
605 songs
= traverse_obj(info
, (('mainSong', ('songs', ...)),))
606 return self
.playlist_result(self
._get
_entries
(songs
), program_id
, **metainfo
)
609 class NetEaseMusicDjRadioIE(NetEaseMusicBaseIE
):
610 IE_NAME
= 'netease:djradio'
611 IE_DESC
= '网易云音乐 - 电台'
612 _VALID_URL
= r
'https?://music\.163\.com/(?:#/)?djradio\?id=(?P<id>[0-9]+)'
614 'url': 'http://music.163.com/#/djradio?id=42',
618 'description': 'md5:c7381ebd7989f9f367668a5aee7d5f08',
620 'playlist_mincount': 40,
624 def _real_extract(self
, url
):
625 dj_id
= self
._match
_id
(url
)
629 for offset
in itertools
.count(start
=0, step
=self
._PAGE
_SIZE
):
630 info
= self
._query
_api
(
631 f
'dj/program/byradio?asc=false&limit={self._PAGE_SIZE}&radioId={dj_id}&offset={offset}',
632 dj_id
, note
=f
'Downloading dj programs - {offset}')
634 entries
.extend(self
.url_result(
635 f
'http://music.163.com/#/program?id={program["id"]}', NetEaseMusicProgramIE
,
636 program
['id'], program
.get('name')) for program
in info
['programs'])
638 metainfo
= traverse_obj(info
, ('programs', 0, 'radio', {
639 'title': ('name', {str}
),
640 'description': ('desc', {str}
),
646 return self
.playlist_result(entries
, dj_id
, **metainfo
)