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