neteasemusic.py 15 KB

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