neteasemusic.py 14 KB

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