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.

439 lines
15 KiB

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