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.

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