neteasemusic.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. from base64 import b64encode
  4. from binascii import hexlify
  5. from datetime import datetime
  6. from hashlib import md5
  7. from random import randint
  8. import json
  9. import re
  10. import time
  11. from .common import InfoExtractor
  12. from ..aes import aes_ecb_encrypt, pkcs7_padding
  13. from ..compat import (
  14. compat_urllib_parse_urlencode,
  15. compat_str,
  16. compat_itertools_count,
  17. )
  18. from ..utils import (
  19. ExtractorError,
  20. bytes_to_intlist,
  21. float_or_none,
  22. int_or_none,
  23. intlist_to_bytes,
  24. sanitized_Request,
  25. std_headers,
  26. try_get,
  27. )
  28. class NetEaseMusicBaseIE(InfoExtractor):
  29. _FORMATS = ['bMusic', 'mMusic', 'hMusic']
  30. _NETEASE_SALT = '3go8&$8*3*3h0k(2)2'
  31. _API_BASE = 'http://music.163.com/api/'
  32. @classmethod
  33. def _encrypt(cls, dfsid):
  34. salt_bytes = bytearray(cls._NETEASE_SALT.encode('utf-8'))
  35. string_bytes = bytearray(compat_str(dfsid).encode('ascii'))
  36. salt_len = len(salt_bytes)
  37. for i in range(len(string_bytes)):
  38. string_bytes[i] = string_bytes[i] ^ salt_bytes[i % salt_len]
  39. m = md5()
  40. m.update(bytes(string_bytes))
  41. result = b64encode(m.digest()).decode('ascii')
  42. return result.replace('/', '_').replace('+', '-')
  43. @classmethod
  44. def make_player_api_request_data_and_headers(cls, song_id, bitrate):
  45. KEY = b'e82ckenh8dichen8'
  46. URL = '/api/song/enhance/player/url'
  47. now = int(time.time() * 1000)
  48. rand = randint(0, 1000)
  49. cookie = {
  50. 'osver': None,
  51. 'deviceId': None,
  52. 'appver': '8.0.0',
  53. 'versioncode': '140',
  54. 'mobilename': None,
  55. 'buildver': '1623435496',
  56. 'resolution': '1920x1080',
  57. '__csrf': '',
  58. 'os': 'pc',
  59. 'channel': None,
  60. 'requestId': '{0}_{1:04}'.format(now, rand),
  61. }
  62. request_text = json.dumps(
  63. {'ids': '[{0}]'.format(song_id), 'br': bitrate, 'header': cookie},
  64. separators=(',', ':'))
  65. message = 'nobody{0}use{1}md5forencrypt'.format(
  66. URL, request_text).encode('latin1')
  67. 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()
  73. cookie = '; '.join(
  74. ['{0}={1}'.format(k, v if v is not None else 'undefined')
  75. for [k, v] in cookie.items()])
  76. headers = {
  77. 'User-Agent': std_headers['User-Agent'],
  78. 'Content-Type': 'application/x-www-form-urlencoded',
  79. 'Referer': 'https://music.163.com',
  80. 'Cookie': cookie,
  81. }
  82. return ('params={0}'.format(encrypted_params), headers)
  83. def _call_player_api(self, song_id, bitrate):
  84. url = 'https://interface3.music.163.com/eapi/song/enhance/player/url'
  85. data, headers = self.make_player_api_request_data_and_headers(song_id, bitrate)
  86. try:
  87. return self._download_json(
  88. url, song_id, data=data.encode('ascii'), headers=headers)
  89. except ExtractorError as e:
  90. if type(e.cause) in (ValueError, TypeError):
  91. # JSON load failure
  92. raise
  93. except Exception:
  94. pass
  95. return {}
  96. def extract_formats(self, info):
  97. formats = []
  98. song_id = info['id']
  99. for song_format in self._FORMATS:
  100. details = info.get(song_format)
  101. if not details:
  102. continue
  103. bitrate = int_or_none(details.get('bitrate')) or 999000
  104. data = self._call_player_api(song_id, bitrate)
  105. for song in try_get(data, lambda x: x['data'], list) or []:
  106. song_url = try_get(song, lambda x: x['url'])
  107. if self._is_valid_url(song_url, info['id'], 'song'):
  108. formats.append({
  109. 'url': song_url,
  110. 'ext': details.get('extension'),
  111. 'abr': float_or_none(song.get('br'), scale=1000),
  112. 'format_id': song_format,
  113. 'filesize': int_or_none(song.get('size')),
  114. 'asr': int_or_none(details.get('sr')),
  115. })
  116. return formats
  117. @classmethod
  118. def convert_milliseconds(cls, ms):
  119. return int(round(ms / 1000.0))
  120. def query_api(self, endpoint, video_id, note):
  121. req = sanitized_Request('%s%s' % (self._API_BASE, endpoint))
  122. req.add_header('Referer', self._API_BASE)
  123. return self._download_json(req, video_id, note)
  124. class NetEaseMusicIE(NetEaseMusicBaseIE):
  125. IE_NAME = 'netease:song'
  126. IE_DESC = '网易云音乐'
  127. _VALID_URL = r'https?://music\.163\.com/(#/)?song\?id=(?P<id>[0-9]+)'
  128. _TESTS = [{
  129. 'url': 'http://music.163.com/#/song?id=32102397',
  130. 'md5': '3e909614ce09b1ccef4a3eb205441190',
  131. 'info_dict': {
  132. 'id': '32102397',
  133. 'ext': 'mp3',
  134. 'title': 'Bad Blood',
  135. 'creator': 'Taylor Swift / Kendrick Lamar',
  136. 'upload_date': '20150516',
  137. 'timestamp': 1431792000,
  138. 'description': 'md5:25fc5f27e47aad975aa6d36382c7833c',
  139. },
  140. }, {
  141. 'note': 'No lyrics.',
  142. 'url': 'http://music.163.com/song?id=17241424',
  143. 'info_dict': {
  144. 'id': '17241424',
  145. 'ext': 'mp3',
  146. 'title': 'Opus 28',
  147. 'creator': 'Dustin O\'Halloran',
  148. 'upload_date': '20080211',
  149. 'description': 'md5:f12945b0f6e0365e3b73c5032e1b0ff4',
  150. 'timestamp': 1202745600,
  151. },
  152. }, {
  153. 'note': 'Has translated name.',
  154. 'url': 'http://music.163.com/#/song?id=22735043',
  155. 'info_dict': {
  156. 'id': '22735043',
  157. 'ext': 'mp3',
  158. 'title': '소원을 말해봐 (Genie)',
  159. 'creator': '少女时代',
  160. 'description': 'md5:79d99cc560e4ca97e0c4d86800ee4184',
  161. 'upload_date': '20100127',
  162. 'timestamp': 1264608000,
  163. 'alt_title': '说出愿望吧(Genie)',
  164. },
  165. }]
  166. def _process_lyrics(self, lyrics_info):
  167. original = lyrics_info.get('lrc', {}).get('lyric')
  168. translated = lyrics_info.get('tlyric', {}).get('lyric')
  169. if not translated:
  170. return original
  171. lyrics_expr = r'(\[[0-9]{2}:[0-9]{2}\.[0-9]{2,}\])([^\n]+)'
  172. original_ts_texts = re.findall(lyrics_expr, original)
  173. translation_ts_dict = dict(
  174. (time_stamp, text) for time_stamp, text in re.findall(lyrics_expr, translated)
  175. )
  176. lyrics = '\n'.join([
  177. '%s%s / %s' % (time_stamp, text, translation_ts_dict.get(time_stamp, ''))
  178. for time_stamp, text in original_ts_texts
  179. ])
  180. return lyrics
  181. def _real_extract(self, url):
  182. song_id = self._match_id(url)
  183. params = {
  184. 'id': song_id,
  185. 'ids': '[%s]' % song_id
  186. }
  187. info = self.query_api(
  188. 'song/detail?' + compat_urllib_parse_urlencode(params),
  189. song_id, 'Downloading song info')['songs'][0]
  190. formats = self.extract_formats(info)
  191. self._sort_formats(formats)
  192. lyrics_info = self.query_api(
  193. 'song/lyric?id=%s&lv=-1&tv=-1' % song_id,
  194. song_id, 'Downloading lyrics data')
  195. lyrics = self._process_lyrics(lyrics_info)
  196. alt_title = None
  197. if info.get('transNames'):
  198. alt_title = '/'.join(info.get('transNames'))
  199. return {
  200. 'id': song_id,
  201. 'title': info['name'],
  202. 'alt_title': alt_title,
  203. 'creator': ' / '.join([artist['name'] for artist in info.get('artists', [])]),
  204. 'timestamp': self.convert_milliseconds(info.get('album', {}).get('publishTime')),
  205. 'thumbnail': info.get('album', {}).get('picUrl'),
  206. 'duration': self.convert_milliseconds(info.get('duration', 0)),
  207. 'description': lyrics,
  208. 'formats': formats,
  209. }
  210. class NetEaseMusicAlbumIE(NetEaseMusicBaseIE):
  211. IE_NAME = 'netease:album'
  212. IE_DESC = '网易云音乐 - 专辑'
  213. _VALID_URL = r'https?://music\.163\.com/(#/)?album\?id=(?P<id>[0-9]+)'
  214. _TEST = {
  215. 'url': 'http://music.163.com/#/album?id=220780',
  216. 'info_dict': {
  217. 'id': '220780',
  218. 'title': 'B\'day',
  219. },
  220. 'playlist_count': 23,
  221. 'skip': 'Blocked outside Mainland China',
  222. }
  223. def _real_extract(self, url):
  224. album_id = self._match_id(url)
  225. info = self.query_api(
  226. 'album/%s?id=%s' % (album_id, album_id),
  227. album_id, 'Downloading album data')['album']
  228. name = info['name']
  229. desc = info.get('description')
  230. entries = [
  231. self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
  232. 'NetEaseMusic', song['id'])
  233. for song in info['songs']
  234. ]
  235. return self.playlist_result(entries, album_id, name, desc)
  236. class NetEaseMusicSingerIE(NetEaseMusicBaseIE):
  237. IE_NAME = 'netease:singer'
  238. IE_DESC = '网易云音乐 - 歌手'
  239. _VALID_URL = r'https?://music\.163\.com/(#/)?artist\?id=(?P<id>[0-9]+)'
  240. _TESTS = [{
  241. 'note': 'Singer has aliases.',
  242. 'url': 'http://music.163.com/#/artist?id=10559',
  243. 'info_dict': {
  244. 'id': '10559',
  245. 'title': '张惠妹 - aMEI;阿密特',
  246. },
  247. 'playlist_count': 50,
  248. 'skip': 'Blocked outside Mainland China',
  249. }, {
  250. 'note': 'Singer has translated name.',
  251. 'url': 'http://music.163.com/#/artist?id=124098',
  252. 'info_dict': {
  253. 'id': '124098',
  254. 'title': '李昇基 - 이승기',
  255. },
  256. 'playlist_count': 50,
  257. 'skip': 'Blocked outside Mainland China',
  258. }]
  259. def _real_extract(self, url):
  260. singer_id = self._match_id(url)
  261. info = self.query_api(
  262. 'artist/%s?id=%s' % (singer_id, singer_id),
  263. singer_id, 'Downloading singer data')
  264. name = info['artist']['name']
  265. if info['artist']['trans']:
  266. name = '%s - %s' % (name, info['artist']['trans'])
  267. if info['artist']['alias']:
  268. name = '%s - %s' % (name, ';'.join(info['artist']['alias']))
  269. entries = [
  270. self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
  271. 'NetEaseMusic', song['id'])
  272. for song in info['hotSongs']
  273. ]
  274. return self.playlist_result(entries, singer_id, name)
  275. class NetEaseMusicListIE(NetEaseMusicBaseIE):
  276. IE_NAME = 'netease:playlist'
  277. IE_DESC = '网易云音乐 - 歌单'
  278. _VALID_URL = r'https?://music\.163\.com/(#/)?(playlist|discover/toplist)\?id=(?P<id>[0-9]+)'
  279. _TESTS = [{
  280. 'url': 'http://music.163.com/#/playlist?id=79177352',
  281. 'info_dict': {
  282. 'id': '79177352',
  283. 'title': 'Billboard 2007 Top 100',
  284. 'description': 'md5:12fd0819cab2965b9583ace0f8b7b022'
  285. },
  286. 'playlist_count': 99,
  287. 'skip': 'Blocked outside Mainland China',
  288. }, {
  289. 'note': 'Toplist/Charts sample',
  290. 'url': 'http://music.163.com/#/discover/toplist?id=3733003',
  291. 'info_dict': {
  292. 'id': '3733003',
  293. 'title': 're:韩国Melon排行榜周榜 [0-9]{4}-[0-9]{2}-[0-9]{2}',
  294. 'description': 'md5:73ec782a612711cadc7872d9c1e134fc',
  295. },
  296. 'playlist_count': 50,
  297. 'skip': 'Blocked outside Mainland China',
  298. }]
  299. def _real_extract(self, url):
  300. list_id = self._match_id(url)
  301. info = self.query_api(
  302. 'playlist/detail?id=%s&lv=-1&tv=-1' % list_id,
  303. list_id, 'Downloading playlist data')['result']
  304. name = info['name']
  305. desc = info.get('description')
  306. if info.get('specialType') == 10: # is a chart/toplist
  307. datestamp = datetime.fromtimestamp(
  308. self.convert_milliseconds(info['updateTime'])).strftime('%Y-%m-%d')
  309. name = '%s %s' % (name, datestamp)
  310. entries = [
  311. self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
  312. 'NetEaseMusic', song['id'])
  313. for song in info['tracks']
  314. ]
  315. return self.playlist_result(entries, list_id, name, desc)
  316. class NetEaseMusicMvIE(NetEaseMusicBaseIE):
  317. IE_NAME = 'netease:mv'
  318. IE_DESC = '网易云音乐 - MV'
  319. _VALID_URL = r'https?://music\.163\.com/(#/)?mv\?id=(?P<id>[0-9]+)'
  320. _TEST = {
  321. 'url': 'http://music.163.com/#/mv?id=415350',
  322. 'info_dict': {
  323. 'id': '415350',
  324. 'ext': 'mp4',
  325. 'title': '이럴거면 그러지말지',
  326. 'description': '白雅言自作曲唱甜蜜爱情',
  327. 'creator': '白雅言',
  328. 'upload_date': '20150520',
  329. },
  330. 'skip': 'Blocked outside Mainland China',
  331. }
  332. def _real_extract(self, url):
  333. mv_id = self._match_id(url)
  334. info = self.query_api(
  335. 'mv/detail?id=%s&type=mp4' % mv_id,
  336. mv_id, 'Downloading mv info')['data']
  337. formats = [
  338. {'url': mv_url, 'ext': 'mp4', 'format_id': '%sp' % brs, 'height': int(brs)}
  339. for brs, mv_url in info['brs'].items()
  340. ]
  341. self._sort_formats(formats)
  342. return {
  343. 'id': mv_id,
  344. 'title': info['name'],
  345. 'description': info.get('desc') or info.get('briefDesc'),
  346. 'creator': info['artistName'],
  347. 'upload_date': info['publishTime'].replace('-', ''),
  348. 'formats': formats,
  349. 'thumbnail': info.get('cover'),
  350. 'duration': self.convert_milliseconds(info.get('duration', 0)),
  351. }
  352. class NetEaseMusicProgramIE(NetEaseMusicBaseIE):
  353. IE_NAME = 'netease:program'
  354. IE_DESC = '网易云音乐 - 电台节目'
  355. _VALID_URL = r'https?://music\.163\.com/(#/?)program\?id=(?P<id>[0-9]+)'
  356. _TESTS = [{
  357. 'url': 'http://music.163.com/#/program?id=10109055',
  358. 'info_dict': {
  359. 'id': '10109055',
  360. 'ext': 'mp3',
  361. 'title': '不丹足球背后的故事',
  362. 'description': '喜马拉雅人的足球梦 ...',
  363. 'creator': '大话西藏',
  364. 'timestamp': 1434179342,
  365. 'upload_date': '20150613',
  366. 'duration': 900,
  367. },
  368. 'skip': 'Blocked outside Mainland China',
  369. }, {
  370. 'note': 'This program has accompanying songs.',
  371. 'url': 'http://music.163.com/#/program?id=10141022',
  372. 'info_dict': {
  373. 'id': '10141022',
  374. 'title': '25岁,你是自在如风的少年<27°C>',
  375. 'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
  376. },
  377. 'playlist_count': 4,
  378. 'skip': 'Blocked outside Mainland China',
  379. }, {
  380. 'note': 'This program has accompanying songs.',
  381. 'url': 'http://music.163.com/#/program?id=10141022',
  382. 'info_dict': {
  383. 'id': '10141022',
  384. 'ext': 'mp3',
  385. 'title': '25岁,你是自在如风的少年<27°C>',
  386. 'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
  387. 'timestamp': 1434450841,
  388. 'upload_date': '20150616',
  389. },
  390. 'params': {
  391. 'noplaylist': True
  392. },
  393. 'skip': 'Blocked outside Mainland China',
  394. }]
  395. def _real_extract(self, url):
  396. program_id = self._match_id(url)
  397. info = self.query_api(
  398. 'dj/program/detail?id=%s' % program_id,
  399. program_id, 'Downloading program info')['program']
  400. name = info['name']
  401. description = info['description']
  402. if not info['songs'] or self._downloader.params.get('noplaylist'):
  403. if info['songs']:
  404. self.to_screen(
  405. 'Downloading just the main audio %s because of --no-playlist'
  406. % info['mainSong']['id'])
  407. formats = self.extract_formats(info['mainSong'])
  408. self._sort_formats(formats)
  409. return {
  410. 'id': program_id,
  411. 'title': name,
  412. 'description': description,
  413. 'creator': info['dj']['brand'],
  414. 'timestamp': self.convert_milliseconds(info['createTime']),
  415. 'thumbnail': info['coverUrl'],
  416. 'duration': self.convert_milliseconds(info.get('duration', 0)),
  417. 'formats': formats,
  418. }
  419. self.to_screen(
  420. 'Downloading playlist %s - add --no-playlist to just download the main audio %s'
  421. % (program_id, info['mainSong']['id']))
  422. song_ids = [info['mainSong']['id']]
  423. song_ids.extend([song['id'] for song in info['songs']])
  424. entries = [
  425. self.url_result('http://music.163.com/#/song?id=%s' % song_id,
  426. 'NetEaseMusic', song_id)
  427. for song_id in song_ids
  428. ]
  429. return self.playlist_result(entries, program_id, name, description)
  430. class NetEaseMusicDjRadioIE(NetEaseMusicBaseIE):
  431. IE_NAME = 'netease:djradio'
  432. IE_DESC = '网易云音乐 - 电台'
  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,
  442. 'skip': 'Blocked outside Mainland China',
  443. }
  444. _PAGE_SIZE = 1000
  445. def _real_extract(self, url):
  446. dj_id = self._match_id(url)
  447. name = None
  448. desc = None
  449. entries = []
  450. for offset in compat_itertools_count(start=0, step=self._PAGE_SIZE):
  451. info = self.query_api(
  452. 'dj/program/byradio?asc=false&limit=%d&radioId=%s&offset=%d'
  453. % (self._PAGE_SIZE, dj_id, offset),
  454. dj_id, 'Downloading dj programs - %d' % offset)
  455. entries.extend([
  456. self.url_result(
  457. 'http://music.163.com/#/program?id=%s' % program['id'],
  458. 'NetEaseMusicProgram', program['id'])
  459. for program in info['programs']
  460. ])
  461. if name is None:
  462. radio = info['programs'][0]['radio']
  463. name = radio['name']
  464. desc = radio['desc']
  465. if not info['more']:
  466. break
  467. return self.playlist_result(entries, dj_id, name, desc)