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.

471 lines
16 KiB

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