neteasemusic.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. import hashlib
  2. import itertools
  3. import json
  4. import random
  5. import re
  6. import time
  7. from .common import InfoExtractor
  8. from ..aes import aes_ecb_encrypt, pkcs7_padding
  9. from ..utils import (
  10. ExtractorError,
  11. int_or_none,
  12. join_nonempty,
  13. str_or_none,
  14. strftime_or_none,
  15. traverse_obj,
  16. unified_strdate,
  17. url_or_none,
  18. urljoin,
  19. variadic,
  20. )
  21. class NetEaseMusicBaseIE(InfoExtractor):
  22. # XXX: _extract_formats logic depends on the order of the levels in each tier
  23. _LEVELS = (
  24. 'standard', # free tier; 标准; 128kbps mp3 or aac
  25. 'higher', # free tier; 192kbps mp3 or aac
  26. 'exhigh', # free tier; 极高 (HQ); 320kbps mp3 or aac
  27. 'lossless', # VIP tier; 无损 (SQ); 48kHz/16bit flac
  28. 'hires', # VIP tier; 高解析度无损 (Hi-Res); 192kHz/24bit flac
  29. 'jyeffect', # VIP tier; 高清臻音 (Spatial Audio); 96kHz/24bit flac
  30. 'jymaster', # SVIP tier; 超清母带 (Master); 192kHz/24bit flac
  31. 'sky', # SVIP tier; 沉浸环绕声 (Surround Audio); flac
  32. )
  33. _API_BASE = 'http://music.163.com/api/'
  34. _GEO_BYPASS = False
  35. @staticmethod
  36. def _kilo_or_none(value):
  37. return int_or_none(value, scale=1000)
  38. def _create_eapi_cipher(self, api_path, query_body, cookies):
  39. request_text = json.dumps({**query_body, 'header': cookies}, separators=(',', ':'))
  40. message = f'nobody{api_path}use{request_text}md5forencrypt'.encode('latin1')
  41. msg_digest = hashlib.md5(message).hexdigest()
  42. data = pkcs7_padding(list(str.encode(
  43. f'{api_path}-36cd479b6b5-{request_text}-36cd479b6b5-{msg_digest}')))
  44. encrypted = bytes(aes_ecb_encrypt(data, list(b'e82ckenh8dichen8')))
  45. return f'params={encrypted.hex().upper()}'.encode()
  46. def _download_eapi_json(self, path, video_id, query_body, headers={}, **kwargs):
  47. cookies = {
  48. 'osver': 'undefined',
  49. 'deviceId': 'undefined',
  50. 'appver': '8.0.0',
  51. 'versioncode': '140',
  52. 'mobilename': 'undefined',
  53. 'buildver': '1623435496',
  54. 'resolution': '1920x1080',
  55. '__csrf': '',
  56. 'os': 'pc',
  57. 'channel': 'undefined',
  58. 'requestId': f'{int(time.time() * 1000)}_{random.randint(0, 1000):04}',
  59. **traverse_obj(self._get_cookies(self._API_BASE), {
  60. 'MUSIC_U': ('MUSIC_U', {lambda i: i.value}),
  61. }),
  62. }
  63. return self._download_json(
  64. urljoin('https://interface3.music.163.com/', f'/eapi{path}'), video_id,
  65. data=self._create_eapi_cipher(f'/api{path}', query_body, cookies), headers={
  66. 'Referer': 'https://music.163.com',
  67. 'Cookie': '; '.join([f'{k}={v}' for k, v in cookies.items()]),
  68. **headers,
  69. }, **kwargs)
  70. def _call_player_api(self, song_id, level):
  71. return self._download_eapi_json(
  72. '/song/enhance/player/url/v1', song_id,
  73. {'ids': f'[{song_id}]', 'level': level, 'encodeType': 'flac'},
  74. note=f'Downloading song URL info: level {level}')
  75. def _extract_formats(self, info):
  76. formats = []
  77. song_id = info['id']
  78. for level in self._LEVELS:
  79. song = traverse_obj(
  80. self._call_player_api(song_id, level), ('data', lambda _, v: url_or_none(v['url']), any))
  81. if not song:
  82. break # Media is not available due to removal or geo-restriction
  83. actual_level = song.get('level')
  84. if actual_level and actual_level != level:
  85. if level in ('lossless', 'jymaster'):
  86. break # We've already extracted the highest level of the user's account tier
  87. continue
  88. formats.append({
  89. 'url': song['url'],
  90. 'format_id': level,
  91. 'vcodec': 'none',
  92. **traverse_obj(song, {
  93. 'ext': ('type', {str}),
  94. 'abr': ('br', {self._kilo_or_none}),
  95. 'filesize': ('size', {int_or_none}),
  96. }),
  97. })
  98. if not actual_level:
  99. break # Only 1 level is available if API does not return a value (netease:program)
  100. if not formats:
  101. self.raise_geo_restricted(
  102. 'No media links found; possibly due to geo restriction', countries=['CN'])
  103. return formats
  104. def _query_api(self, endpoint, video_id, note):
  105. result = self._download_json(
  106. f'{self._API_BASE}{endpoint}', video_id, note, headers={'Referer': self._API_BASE})
  107. code = traverse_obj(result, ('code', {int}))
  108. message = traverse_obj(result, ('message', {str})) or ''
  109. if code == -462:
  110. self.raise_login_required(f'Login required to download: {message}')
  111. elif code != 200:
  112. raise ExtractorError(f'Failed to get meta info: {code} {message}')
  113. return result
  114. def _get_entries(self, songs_data, entry_keys=None, id_key='id', name_key='name'):
  115. for song in traverse_obj(songs_data, (
  116. *variadic(entry_keys, (str, bytes, dict, set)),
  117. lambda _, v: int_or_none(v[id_key]) is not None)):
  118. song_id = str(song[id_key])
  119. yield self.url_result(
  120. f'http://music.163.com/#/song?id={song_id}', NetEaseMusicIE,
  121. song_id, traverse_obj(song, (name_key, {str})))
  122. class NetEaseMusicIE(NetEaseMusicBaseIE):
  123. IE_NAME = 'netease:song'
  124. IE_DESC = '网易云音乐'
  125. _VALID_URL = r'https?://(?:y\.)?music\.163\.com/(?:[#m]/)?song\?.*?\bid=(?P<id>[0-9]+)'
  126. _TESTS = [{
  127. 'url': 'https://music.163.com/#/song?id=550136151',
  128. 'info_dict': {
  129. 'id': '550136151',
  130. 'ext': 'mp3',
  131. 'title': 'It\'s Ok (Live)',
  132. 'creators': 'count:10',
  133. 'timestamp': 1522944000,
  134. 'upload_date': '20180405',
  135. 'description': 'md5:9fd07059c2ccee3950dc8363429a3135',
  136. 'duration': 197,
  137. 'thumbnail': r're:^http.*\.jpg',
  138. 'album': '偶像练习生 表演曲目合集',
  139. 'average_rating': int,
  140. 'album_artists': ['偶像练习生'],
  141. },
  142. }, {
  143. 'url': 'http://music.163.com/song?id=17241424',
  144. 'info_dict': {
  145. 'id': '17241424',
  146. 'ext': 'mp3',
  147. 'title': 'Opus 28',
  148. 'upload_date': '20080211',
  149. 'timestamp': 1202745600,
  150. 'duration': 263,
  151. 'thumbnail': r're:^http.*\.jpg',
  152. 'album': 'Piano Solos Vol. 2',
  153. 'album_artist': 'Dustin O\'Halloran',
  154. 'average_rating': int,
  155. 'description': '[00:05.00]纯音乐,请欣赏\n',
  156. 'album_artists': ['Dustin O\'Halloran'],
  157. 'creators': ['Dustin O\'Halloran'],
  158. 'subtitles': {'lyrics': [{'ext': 'lrc'}]},
  159. },
  160. }, {
  161. 'url': 'https://y.music.163.com/m/song?app_version=8.8.45&id=95670&uct2=sKnvS4+0YStsWkqsPhFijw%3D%3D&dlt=0846',
  162. 'md5': 'b896be78d8d34bd7bb665b26710913ff',
  163. 'info_dict': {
  164. 'id': '95670',
  165. 'ext': 'mp3',
  166. 'title': '国际歌',
  167. 'upload_date': '19911130',
  168. 'timestamp': 691516800,
  169. 'description': 'md5:1ba2f911a2b0aa398479f595224f2141',
  170. 'subtitles': {'lyrics': [{'ext': 'lrc'}]},
  171. 'duration': 268,
  172. 'alt_title': '伴唱:现代人乐队 合唱:总政歌舞团',
  173. 'thumbnail': r're:^http.*\.jpg',
  174. 'average_rating': int,
  175. 'album': '红色摇滚',
  176. 'album_artist': '侯牧人',
  177. 'creators': ['马备'],
  178. 'album_artists': ['侯牧人'],
  179. },
  180. }, {
  181. 'url': 'http://music.163.com/#/song?id=32102397',
  182. 'md5': '3e909614ce09b1ccef4a3eb205441190',
  183. 'info_dict': {
  184. 'id': '32102397',
  185. 'ext': 'mp3',
  186. 'title': 'Bad Blood',
  187. 'creators': ['Taylor Swift', 'Kendrick Lamar'],
  188. 'upload_date': '20150516',
  189. 'timestamp': 1431792000,
  190. 'description': 'md5:21535156efb73d6d1c355f95616e285a',
  191. 'subtitles': {'lyrics': [{'ext': 'lrc'}]},
  192. 'duration': 199,
  193. 'thumbnail': r're:^http.*\.jpg',
  194. 'album': 'Bad Blood',
  195. 'average_rating': int,
  196. 'album_artist': 'Taylor Swift',
  197. },
  198. 'skip': 'Blocked outside Mainland China',
  199. }, {
  200. 'note': 'Has translated name.',
  201. 'url': 'http://music.163.com/#/song?id=22735043',
  202. 'info_dict': {
  203. 'id': '22735043',
  204. 'ext': 'mp3',
  205. 'title': '소원을 말해봐 (Genie)',
  206. 'creators': ['少女时代'],
  207. 'upload_date': '20100127',
  208. 'timestamp': 1264608000,
  209. 'description': 'md5:03d1ffebec3139aa4bafe302369269c5',
  210. 'subtitles': {'lyrics': [{'ext': 'lrc'}]},
  211. 'duration': 229,
  212. 'alt_title': '说出愿望吧(Genie)',
  213. 'thumbnail': r're:^http.*\.jpg',
  214. 'average_rating': int,
  215. 'album': 'Oh!',
  216. 'album_artist': '少女时代',
  217. },
  218. 'skip': 'Blocked outside Mainland China',
  219. }]
  220. def _process_lyrics(self, lyrics_info):
  221. original = traverse_obj(lyrics_info, ('lrc', 'lyric', {str}))
  222. translated = traverse_obj(lyrics_info, ('tlyric', 'lyric', {str}))
  223. if not original or original == '[99:00.00]纯音乐,请欣赏\n':
  224. return None
  225. if not translated:
  226. return {
  227. 'lyrics': [{'data': original, 'ext': 'lrc'}],
  228. }
  229. lyrics_expr = r'(\[[0-9]{2}:[0-9]{2}\.[0-9]{2,}\])([^\n]+)'
  230. original_ts_texts = re.findall(lyrics_expr, original)
  231. translation_ts_dict = dict(re.findall(lyrics_expr, translated))
  232. merged = '\n'.join(
  233. join_nonempty(f'{timestamp}{text}', translation_ts_dict.get(timestamp, ''), delim=' / ')
  234. for timestamp, text in original_ts_texts)
  235. return {
  236. 'lyrics_merged': [{'data': merged, 'ext': 'lrc'}],
  237. 'lyrics': [{'data': original, 'ext': 'lrc'}],
  238. 'lyrics_translated': [{'data': translated, 'ext': 'lrc'}],
  239. }
  240. def _real_extract(self, url):
  241. song_id = self._match_id(url)
  242. info = self._query_api(
  243. f'song/detail?id={song_id}&ids=%5B{song_id}%5D', song_id, 'Downloading song info')['songs'][0]
  244. formats = self._extract_formats(info)
  245. lyrics = self._process_lyrics(self._query_api(
  246. f'song/lyric?id={song_id}&lv=-1&tv=-1', song_id, 'Downloading lyrics data'))
  247. lyric_data = {
  248. 'description': traverse_obj(lyrics, (('lyrics_merged', 'lyrics'), 0, 'data'), get_all=False),
  249. 'subtitles': lyrics,
  250. } if lyrics else {}
  251. return {
  252. 'id': song_id,
  253. 'formats': formats,
  254. 'alt_title': '/'.join(traverse_obj(info, (('transNames', 'alias'), ...))) or None,
  255. 'creators': traverse_obj(info, ('artists', ..., 'name')) or None,
  256. 'album_artists': traverse_obj(info, ('album', 'artists', ..., 'name')) or None,
  257. **lyric_data,
  258. **traverse_obj(info, {
  259. 'title': ('name', {str}),
  260. 'timestamp': ('album', 'publishTime', {self._kilo_or_none}),
  261. 'thumbnail': ('album', 'picUrl', {url_or_none}),
  262. 'duration': ('duration', {self._kilo_or_none}),
  263. 'album': ('album', 'name', {str}),
  264. 'average_rating': ('score', {int_or_none}),
  265. }),
  266. }
  267. class NetEaseMusicAlbumIE(NetEaseMusicBaseIE):
  268. IE_NAME = 'netease:album'
  269. IE_DESC = '网易云音乐 - 专辑'
  270. _VALID_URL = r'https?://music\.163\.com/(?:#/)?album\?id=(?P<id>[0-9]+)'
  271. _TESTS = [{
  272. 'url': 'https://music.163.com/#/album?id=133153666',
  273. 'info_dict': {
  274. 'id': '133153666',
  275. 'title': '桃几的翻唱',
  276. 'upload_date': '20210913',
  277. 'description': '桃几2021年翻唱合集',
  278. 'thumbnail': r're:^http.*\.jpg',
  279. },
  280. 'playlist_mincount': 12,
  281. }, {
  282. 'url': 'http://music.163.com/#/album?id=220780',
  283. 'info_dict': {
  284. 'id': '220780',
  285. 'title': 'B\'Day',
  286. 'upload_date': '20060904',
  287. 'description': 'md5:71a74e1d8f392d88cf1bbe48879ad0b0',
  288. 'thumbnail': r're:^http.*\.jpg',
  289. },
  290. 'playlist_count': 23,
  291. }]
  292. def _real_extract(self, url):
  293. album_id = self._match_id(url)
  294. webpage = self._download_webpage(f'https://music.163.com/album?id={album_id}', album_id)
  295. songs = self._search_json(
  296. r'<textarea[^>]+\bid="song-list-pre-data"[^>]*>', webpage, 'metainfo', album_id,
  297. end_pattern=r'</textarea>', contains_pattern=r'\[(?s:.+)\]')
  298. metainfo = {
  299. 'title': self._og_search_property('title', webpage, 'title', fatal=False),
  300. 'description': self._html_search_regex(
  301. (rf'<div[^>]+\bid="album-desc-{suffix}"[^>]*>(.*?)</div>' for suffix in ('more', 'dot')),
  302. webpage, 'description', flags=re.S, fatal=False),
  303. 'thumbnail': self._og_search_property('image', webpage, 'thumbnail', fatal=False),
  304. 'upload_date': unified_strdate(self._html_search_meta('music:release_date', webpage, 'date', fatal=False)),
  305. }
  306. return self.playlist_result(self._get_entries(songs), album_id, **metainfo)
  307. class NetEaseMusicSingerIE(NetEaseMusicBaseIE):
  308. IE_NAME = 'netease:singer'
  309. IE_DESC = '网易云音乐 - 歌手'
  310. _VALID_URL = r'https?://music\.163\.com/(?:#/)?artist\?id=(?P<id>[0-9]+)'
  311. _TESTS = [{
  312. 'note': 'Singer has aliases.',
  313. 'url': 'http://music.163.com/#/artist?id=10559',
  314. 'info_dict': {
  315. 'id': '10559',
  316. 'title': '张惠妹 - aMEI;阿妹;阿密特',
  317. },
  318. 'playlist_count': 50,
  319. }, {
  320. 'note': 'Singer has translated name.',
  321. 'url': 'http://music.163.com/#/artist?id=124098',
  322. 'info_dict': {
  323. 'id': '124098',
  324. 'title': '李昇基 - 이승기',
  325. },
  326. 'playlist_count': 50,
  327. }, {
  328. 'note': 'Singer with both translated and alias',
  329. 'url': 'https://music.163.com/#/artist?id=159692',
  330. 'info_dict': {
  331. 'id': '159692',
  332. 'title': '初音ミク - 初音未来;Hatsune Miku',
  333. },
  334. 'playlist_count': 50,
  335. }]
  336. def _real_extract(self, url):
  337. singer_id = self._match_id(url)
  338. info = self._query_api(
  339. f'artist/{singer_id}?id={singer_id}', singer_id, note='Downloading singer data')
  340. name = join_nonempty(
  341. traverse_obj(info, ('artist', 'name', {str})),
  342. join_nonempty(*traverse_obj(info, ('artist', ('trans', ('alias', ...)), {str})), delim=';'),
  343. delim=' - ')
  344. return self.playlist_result(self._get_entries(info, 'hotSongs'), singer_id, name)
  345. class NetEaseMusicListIE(NetEaseMusicBaseIE):
  346. IE_NAME = 'netease:playlist'
  347. IE_DESC = '网易云音乐 - 歌单'
  348. _VALID_URL = r'https?://music\.163\.com/(?:#/)?(?:playlist|discover/toplist)\?id=(?P<id>[0-9]+)'
  349. _TESTS = [{
  350. 'url': 'http://music.163.com/#/playlist?id=79177352',
  351. 'info_dict': {
  352. 'id': '79177352',
  353. 'title': 'Billboard 2007 Top 100',
  354. 'description': 'md5:12fd0819cab2965b9583ace0f8b7b022',
  355. 'tags': ['欧美'],
  356. 'uploader': '浑然破灭',
  357. 'uploader_id': '67549805',
  358. 'timestamp': int,
  359. 'upload_date': r're:\d{8}',
  360. },
  361. 'playlist_mincount': 95,
  362. }, {
  363. 'note': 'Toplist/Charts sample',
  364. 'url': 'https://music.163.com/#/discover/toplist?id=60198',
  365. 'info_dict': {
  366. 'id': '60198',
  367. 'title': 're:美国Billboard榜 [0-9]{4}-[0-9]{2}-[0-9]{2}',
  368. 'description': '美国Billboard排行榜',
  369. 'tags': ['流行', '欧美', '榜单'],
  370. 'uploader': 'Billboard公告牌',
  371. 'uploader_id': '48171',
  372. 'timestamp': int,
  373. 'upload_date': r're:\d{8}',
  374. },
  375. 'playlist_count': 100,
  376. }, {
  377. 'note': 'Toplist/Charts sample',
  378. 'url': 'http://music.163.com/#/discover/toplist?id=3733003',
  379. 'info_dict': {
  380. 'id': '3733003',
  381. 'title': 're:韩国Melon排行榜周榜(?: [0-9]{4}-[0-9]{2}-[0-9]{2})?',
  382. 'description': 'md5:73ec782a612711cadc7872d9c1e134fc',
  383. 'upload_date': '20200109',
  384. 'uploader_id': '2937386',
  385. 'tags': ['韩语', '榜单'],
  386. 'uploader': 'Melon榜单',
  387. 'timestamp': 1578569373,
  388. },
  389. 'playlist_count': 50,
  390. }]
  391. def _real_extract(self, url):
  392. list_id = self._match_id(url)
  393. info = self._download_eapi_json(
  394. '/v3/playlist/detail', list_id,
  395. {'id': list_id, 't': '-1', 'n': '500', 's': '0'},
  396. note='Downloading playlist info')
  397. metainfo = traverse_obj(info, ('playlist', {
  398. 'title': ('name', {str}),
  399. 'description': ('description', {str}),
  400. 'tags': ('tags', ..., {str}),
  401. 'uploader': ('creator', 'nickname', {str}),
  402. 'uploader_id': ('creator', 'userId', {str_or_none}),
  403. 'timestamp': ('updateTime', {self._kilo_or_none}),
  404. }))
  405. if traverse_obj(info, ('playlist', 'specialType')) == 10:
  406. metainfo['title'] = f'{metainfo.get("title")} {strftime_or_none(metainfo.get("timestamp"), "%Y-%m-%d")}'
  407. return self.playlist_result(self._get_entries(info, ('playlist', 'tracks')), list_id, **metainfo)
  408. class NetEaseMusicMvIE(NetEaseMusicBaseIE):
  409. IE_NAME = 'netease:mv'
  410. IE_DESC = '网易云音乐 - MV'
  411. _VALID_URL = r'https?://music\.163\.com/(?:#/)?mv\?id=(?P<id>[0-9]+)'
  412. _TESTS = [{
  413. 'url': 'https://music.163.com/#/mv?id=10958064',
  414. 'info_dict': {
  415. 'id': '10958064',
  416. 'ext': 'mp4',
  417. 'title': '交换余生',
  418. 'description': 'md5:e845872cff28820642a2b02eda428fea',
  419. 'creators': ['林俊杰'],
  420. 'upload_date': '20200916',
  421. 'thumbnail': r're:http.*\.jpg',
  422. 'duration': 364,
  423. 'view_count': int,
  424. 'like_count': int,
  425. 'comment_count': int,
  426. },
  427. }, {
  428. 'url': 'http://music.163.com/#/mv?id=415350',
  429. 'info_dict': {
  430. 'id': '415350',
  431. 'ext': 'mp4',
  432. 'title': '이럴거면 그러지말지',
  433. 'description': '白雅言自作曲唱甜蜜爱情',
  434. 'creators': ['白娥娟'],
  435. 'upload_date': '20150520',
  436. 'thumbnail': r're:http.*\.jpg',
  437. 'duration': 216,
  438. 'view_count': int,
  439. 'like_count': int,
  440. 'comment_count': int,
  441. },
  442. 'skip': 'Blocked outside Mainland China',
  443. }, {
  444. 'note': 'This MV has multiple creators.',
  445. 'url': 'https://music.163.com/#/mv?id=22593543',
  446. 'info_dict': {
  447. 'id': '22593543',
  448. 'ext': 'mp4',
  449. 'title': '老北京杀器',
  450. 'creators': ['秃子2z', '辉子', 'Saber梁维嘉'],
  451. 'duration': 206,
  452. 'upload_date': '20240618',
  453. 'like_count': int,
  454. 'comment_count': int,
  455. 'thumbnail': r're:http.*\.jpg',
  456. 'view_count': int,
  457. },
  458. }]
  459. def _real_extract(self, url):
  460. mv_id = self._match_id(url)
  461. info = self._query_api(
  462. f'mv/detail?id={mv_id}&type=mp4', mv_id, 'Downloading mv info')['data']
  463. formats = [
  464. {'url': mv_url, 'ext': 'mp4', 'format_id': f'{brs}p', 'height': int_or_none(brs)}
  465. for brs, mv_url in info['brs'].items()
  466. ]
  467. return {
  468. 'id': mv_id,
  469. 'formats': formats,
  470. 'creators': traverse_obj(info, ('artists', ..., 'name')) or [info.get('artistName')],
  471. **traverse_obj(info, {
  472. 'title': ('name', {str}),
  473. 'description': (('desc', 'briefDesc'), {str}, {lambda x: x or None}),
  474. 'upload_date': ('publishTime', {unified_strdate}),
  475. 'thumbnail': ('cover', {url_or_none}),
  476. 'duration': ('duration', {self._kilo_or_none}),
  477. 'view_count': ('playCount', {int_or_none}),
  478. 'like_count': ('likeCount', {int_or_none}),
  479. 'comment_count': ('commentCount', {int_or_none}),
  480. }, get_all=False),
  481. }
  482. class NetEaseMusicProgramIE(NetEaseMusicBaseIE):
  483. IE_NAME = 'netease:program'
  484. IE_DESC = '网易云音乐 - 电台节目'
  485. _VALID_URL = r'https?://music\.163\.com/(?:#/)?program\?id=(?P<id>[0-9]+)'
  486. _TESTS = [{
  487. 'url': 'http://music.163.com/#/program?id=10109055',
  488. 'info_dict': {
  489. 'id': '32593346',
  490. 'ext': 'mp3',
  491. 'title': '不丹足球背后的故事',
  492. 'description': '喜马拉雅人的足球梦 ...',
  493. 'creators': ['大话西藏'],
  494. 'timestamp': 1434179287,
  495. 'upload_date': '20150613',
  496. 'thumbnail': r're:http.*\.jpg',
  497. 'duration': 900,
  498. },
  499. }, {
  500. 'note': 'This program has accompanying songs.',
  501. 'url': 'http://music.163.com/#/program?id=10141022',
  502. 'info_dict': {
  503. 'id': '10141022',
  504. 'title': '滚滚电台的有声节目',
  505. 'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
  506. 'creators': ['滚滚电台ORZ'],
  507. 'timestamp': 1434450733,
  508. 'upload_date': '20150616',
  509. 'thumbnail': r're:http.*\.jpg',
  510. },
  511. 'playlist_count': 4,
  512. }, {
  513. 'note': 'This program has accompanying songs.',
  514. 'url': 'http://music.163.com/#/program?id=10141022',
  515. 'info_dict': {
  516. 'id': '32647209',
  517. 'ext': 'mp3',
  518. 'title': '滚滚电台的有声节目',
  519. 'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
  520. 'creators': ['滚滚电台ORZ'],
  521. 'timestamp': 1434450733,
  522. 'upload_date': '20150616',
  523. 'thumbnail': r're:http.*\.jpg',
  524. 'duration': 1104,
  525. },
  526. 'params': {
  527. 'noplaylist': True,
  528. },
  529. }]
  530. def _real_extract(self, url):
  531. program_id = self._match_id(url)
  532. info = self._query_api(
  533. f'dj/program/detail?id={program_id}', program_id, note='Downloading program info')['program']
  534. metainfo = traverse_obj(info, {
  535. 'title': ('name', {str}),
  536. 'description': ('description', {str}),
  537. 'creator': ('dj', 'brand', {str}),
  538. 'thumbnail': ('coverUrl', {url_or_none}),
  539. 'timestamp': ('createTime', {self._kilo_or_none}),
  540. })
  541. if not self._yes_playlist(
  542. info['songs'] and program_id, info['mainSong']['id'], playlist_label='program', video_label='song'):
  543. formats = self._extract_formats(info['mainSong'])
  544. return {
  545. 'id': str(info['mainSong']['id']),
  546. 'formats': formats,
  547. 'duration': traverse_obj(info, ('mainSong', 'duration', {self._kilo_or_none})),
  548. **metainfo,
  549. }
  550. songs = traverse_obj(info, (('mainSong', ('songs', ...)),))
  551. return self.playlist_result(self._get_entries(songs), program_id, **metainfo)
  552. class NetEaseMusicDjRadioIE(NetEaseMusicBaseIE):
  553. IE_NAME = 'netease:djradio'
  554. IE_DESC = '网易云音乐 - 电台'
  555. _VALID_URL = r'https?://music\.163\.com/(?:#/)?djradio\?id=(?P<id>[0-9]+)'
  556. _TEST = {
  557. 'url': 'http://music.163.com/#/djradio?id=42',
  558. 'info_dict': {
  559. 'id': '42',
  560. 'title': '声音蔓延',
  561. 'description': 'md5:c7381ebd7989f9f367668a5aee7d5f08',
  562. },
  563. 'playlist_mincount': 40,
  564. }
  565. _PAGE_SIZE = 1000
  566. def _real_extract(self, url):
  567. dj_id = self._match_id(url)
  568. metainfo = {}
  569. entries = []
  570. for offset in itertools.count(start=0, step=self._PAGE_SIZE):
  571. info = self._query_api(
  572. f'dj/program/byradio?asc=false&limit={self._PAGE_SIZE}&radioId={dj_id}&offset={offset}',
  573. dj_id, note=f'Downloading dj programs - {offset}')
  574. entries.extend(self.url_result(
  575. f'http://music.163.com/#/program?id={program["id"]}', NetEaseMusicProgramIE,
  576. program['id'], program.get('name')) for program in info['programs'])
  577. if not metainfo:
  578. metainfo = traverse_obj(info, ('programs', 0, 'radio', {
  579. 'title': ('name', {str}),
  580. 'description': ('desc', {str}),
  581. }))
  582. if not info['more']:
  583. break
  584. return self.playlist_result(entries, dj_id, **metainfo)