You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

459 lines
16 KiB

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