neteasemusic.py 16 KB

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