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.

453 lines
15 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://m1.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. _VALID_URL = r'https?://music\.163\.com/(#/)?album\?id=(?P<id>[0-9]+)'
  154. _TEST = {
  155. 'url': 'http://music.163.com/#/album?id=220780',
  156. 'info_dict': {
  157. 'id': '220780',
  158. 'title': 'B\'day',
  159. },
  160. 'playlist_count': 23,
  161. }
  162. def _real_extract(self, url):
  163. album_id = self._match_id(url)
  164. info = self.query_api(
  165. 'album/%s?id=%s' % (album_id, album_id),
  166. album_id, 'Downloading album data')['album']
  167. name = info['name']
  168. desc = info.get('description')
  169. entries = [
  170. self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
  171. 'NetEaseMusic', song['id'])
  172. for song in info['songs']
  173. ]
  174. return self.playlist_result(entries, album_id, name, desc)
  175. class NetEaseMusicSingerIE(NetEaseMusicBaseIE):
  176. IE_NAME = 'netease:singer'
  177. _VALID_URL = r'https?://music\.163\.com/(#/)?artist\?id=(?P<id>[0-9]+)'
  178. _TESTS = [{
  179. 'note': 'Singer has aliases.',
  180. 'url': 'http://music.163.com/#/artist?id=10559',
  181. 'info_dict': {
  182. 'id': '10559',
  183. 'title': '张惠妹 - aMEI;阿密特',
  184. },
  185. 'playlist_count': 50,
  186. }, {
  187. 'note': 'Singer has translated name.',
  188. 'url': 'http://music.163.com/#/artist?id=124098',
  189. 'info_dict': {
  190. 'id': '124098',
  191. 'title': '李昇基 - 이승기',
  192. },
  193. 'playlist_count': 50,
  194. }]
  195. def _real_extract(self, url):
  196. singer_id = self._match_id(url)
  197. info = self.query_api(
  198. 'artist/%s?id=%s' % (singer_id, singer_id),
  199. singer_id, 'Downloading singer data')
  200. name = info['artist']['name']
  201. if info['artist']['trans']:
  202. name = '%s - %s' % (name, info['artist']['trans'])
  203. if info['artist']['alias']:
  204. name = '%s - %s' % (name, ';'.join(info['artist']['alias']))
  205. entries = [
  206. self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
  207. 'NetEaseMusic', song['id'])
  208. for song in info['hotSongs']
  209. ]
  210. return self.playlist_result(entries, singer_id, name)
  211. class NetEaseMusicListIE(NetEaseMusicBaseIE):
  212. IE_NAME = 'netease:playlist'
  213. _VALID_URL = r'https?://music\.163\.com/(#/)?(playlist|discover/toplist)\?id=(?P<id>[0-9]+)'
  214. _TESTS = [{
  215. 'url': 'http://music.163.com/#/playlist?id=79177352',
  216. 'info_dict': {
  217. 'id': '79177352',
  218. 'title': 'Billboard 2007 Top 100',
  219. 'description': 'md5:12fd0819cab2965b9583ace0f8b7b022'
  220. },
  221. 'playlist_count': 99,
  222. }, {
  223. 'note': 'Toplist/Charts sample',
  224. 'url': 'http://music.163.com/#/discover/toplist?id=3733003',
  225. 'info_dict': {
  226. 'id': '3733003',
  227. 'title': 're:韩国Melon排行榜周榜 [0-9]{4}-[0-9]{2}-[0-9]{2}',
  228. 'description': 'md5:73ec782a612711cadc7872d9c1e134fc',
  229. },
  230. 'playlist_count': 50,
  231. }]
  232. def _real_extract(self, url):
  233. list_id = self._match_id(url)
  234. info = self.query_api(
  235. 'playlist/detail?id=%s&lv=-1&tv=-1' % list_id,
  236. list_id, 'Downloading playlist data')['result']
  237. name = info['name']
  238. desc = info.get('description')
  239. if info.get('specialType') == 10: # is a chart/toplist
  240. datestamp = datetime.fromtimestamp(
  241. self.convert_milliseconds(info['updateTime'])).strftime('%Y-%m-%d')
  242. name = '%s %s' % (name, datestamp)
  243. entries = [
  244. self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
  245. 'NetEaseMusic', song['id'])
  246. for song in info['tracks']
  247. ]
  248. return self.playlist_result(entries, list_id, name, desc)
  249. class NetEaseMusicMvIE(NetEaseMusicBaseIE):
  250. IE_NAME = 'netease:mv'
  251. _VALID_URL = r'https?://music\.163\.com/(#/)?mv\?id=(?P<id>[0-9]+)'
  252. _TEST = {
  253. 'url': 'http://music.163.com/#/mv?id=415350',
  254. 'info_dict': {
  255. 'id': '415350',
  256. 'ext': 'mp4',
  257. 'title': '이럴거면 그러지말지',
  258. 'description': '白雅言自作曲唱甜蜜爱情',
  259. 'creator': '白雅言',
  260. 'upload_date': '20150520',
  261. },
  262. }
  263. def _real_extract(self, url):
  264. mv_id = self._match_id(url)
  265. info = self.query_api(
  266. 'mv/detail?id=%s&type=mp4' % mv_id,
  267. mv_id, 'Downloading mv info')['data']
  268. formats = [
  269. {'url': mv_url, 'ext': 'mp4', 'format_id': '%sp' % brs, 'height': int(brs)}
  270. for brs, mv_url in info['brs'].items()
  271. ]
  272. self._sort_formats(formats)
  273. return {
  274. 'id': mv_id,
  275. 'title': info['name'],
  276. 'description': info.get('desc') or info.get('briefDesc'),
  277. 'creator': info['artistName'],
  278. 'upload_date': info['publishTime'].replace('-', ''),
  279. 'formats': formats,
  280. 'thumbnail': info.get('cover'),
  281. 'duration': self.convert_milliseconds(info.get('duration', 0)),
  282. }
  283. class NetEaseMusicProgramIE(NetEaseMusicBaseIE):
  284. IE_NAME = 'netease:program'
  285. _VALID_URL = r'https?://music\.163\.com/(#/?)program\?id=(?P<id>[0-9]+)'
  286. _TESTS = [{
  287. 'url': 'http://music.163.com/#/program?id=10109055',
  288. 'info_dict': {
  289. 'id': '10109055',
  290. 'ext': 'mp3',
  291. 'title': '不丹足球背后的故事',
  292. 'description': '喜马拉雅人的足球梦 ...',
  293. 'creator': '大话西藏',
  294. 'timestamp': 1434179342,
  295. 'upload_date': '20150613',
  296. 'duration': 900,
  297. },
  298. }, {
  299. 'note': 'This program has accompanying songs.',
  300. 'url': 'http://music.163.com/#/program?id=10141022',
  301. 'info_dict': {
  302. 'id': '10141022',
  303. 'title': '25岁,你是自在如风的少年<27°C>',
  304. 'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
  305. },
  306. 'playlist_count': 4,
  307. }, {
  308. 'note': 'This program has accompanying songs.',
  309. 'url': 'http://music.163.com/#/program?id=10141022',
  310. 'info_dict': {
  311. 'id': '10141022',
  312. 'ext': 'mp3',
  313. 'title': '25岁,你是自在如风的少年<27°C>',
  314. 'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
  315. 'timestamp': 1434450841,
  316. 'upload_date': '20150616',
  317. },
  318. 'params': {
  319. 'noplaylist': True
  320. }
  321. }]
  322. def _real_extract(self, url):
  323. program_id = self._match_id(url)
  324. info = self.query_api(
  325. 'dj/program/detail?id=%s' % program_id,
  326. program_id, 'Downloading program info')['program']
  327. name = info['name']
  328. description = info['description']
  329. if not info['songs'] or self._downloader.params.get('noplaylist'):
  330. if info['songs']:
  331. self.to_screen(
  332. 'Downloading just the main audio %s because of --no-playlist'
  333. % info['mainSong']['id'])
  334. formats = self.extract_formats(info['mainSong'])
  335. self._sort_formats(formats)
  336. return {
  337. 'id': program_id,
  338. 'title': name,
  339. 'description': description,
  340. 'creator': info['dj']['brand'],
  341. 'timestamp': self.convert_milliseconds(info['createTime']),
  342. 'thumbnail': info['coverUrl'],
  343. 'duration': self.convert_milliseconds(info.get('duration', 0)),
  344. 'formats': formats,
  345. }
  346. self.to_screen(
  347. 'Downloading playlist %s - add --no-playlist to just download the main audio %s'
  348. % (program_id, info['mainSong']['id']))
  349. song_ids = [info['mainSong']['id']]
  350. song_ids.extend([song['id'] for song in info['songs']])
  351. entries = [
  352. self.url_result('http://music.163.com/#/song?id=%s' % song_id,
  353. 'NetEaseMusic', song_id)
  354. for song_id in song_ids
  355. ]
  356. return self.playlist_result(entries, program_id, name, description)
  357. class NetEaseMusicDjRadioIE(NetEaseMusicBaseIE):
  358. IE_NAME = 'netease:djradio'
  359. _VALID_URL = r'https?://music\.163\.com/(#/)?djradio\?id=(?P<id>[0-9]+)'
  360. _TEST = {
  361. 'url': 'http://music.163.com/#/djradio?id=42',
  362. 'info_dict': {
  363. 'id': '42',
  364. 'title': '声音蔓延',
  365. 'description': 'md5:766220985cbd16fdd552f64c578a6b15'
  366. },
  367. 'playlist_mincount': 40,
  368. }
  369. _PAGE_SIZE = 1000
  370. def _real_extract(self, url):
  371. dj_id = self._match_id(url)
  372. name = None
  373. desc = None
  374. entries = []
  375. for offset in compat_itertools_count(start=0, step=self._PAGE_SIZE):
  376. info = self.query_api(
  377. 'dj/program/byradio?asc=false&limit=%d&radioId=%s&offset=%d'
  378. % (self._PAGE_SIZE, dj_id, offset),
  379. dj_id, 'Downloading dj programs - %d' % offset)
  380. entries.extend([
  381. self.url_result(
  382. 'http://music.163.com/#/program?id=%s' % program['id'],
  383. 'NetEaseMusicProgram', program['id'])
  384. for program in info['programs']
  385. ])
  386. if name is None:
  387. radio = info['programs'][0]['radio']
  388. name = radio['name']
  389. desc = radio['desc']
  390. if not info['more']:
  391. break
  392. return self.playlist_result(entries, dj_id, name, desc)