logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

neteasemusic.py (20141B)


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