qqmusic.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. import base64
  2. import functools
  3. import json
  4. import random
  5. import time
  6. from .common import InfoExtractor
  7. from ..utils import (
  8. ExtractorError,
  9. OnDemandPagedList,
  10. clean_html,
  11. int_or_none,
  12. join_nonempty,
  13. js_to_json,
  14. str_or_none,
  15. strip_jsonp,
  16. traverse_obj,
  17. unescapeHTML,
  18. url_or_none,
  19. urljoin,
  20. )
  21. class QQMusicBaseIE(InfoExtractor):
  22. def _get_cookie(self, key, default=None):
  23. return getattr(self._get_cookies('https://y.qq.com').get(key), 'value', default)
  24. def _get_g_tk(self):
  25. n = 5381
  26. for c in self._get_cookie('qqmusic_key', ''):
  27. n += (n << 5) + ord(c)
  28. return n & 2147483647
  29. def _get_uin(self):
  30. return int_or_none(self._get_cookie('uin')) or 0
  31. @property
  32. def is_logged_in(self):
  33. return bool(self._get_uin() and self._get_cookie('fqm_pvqid'))
  34. # Reference: m_r_GetRUin() in top_player.js
  35. # http://imgcache.gtimg.cn/music/portal_v3/y/top_player.js
  36. @staticmethod
  37. def _m_r_get_ruin():
  38. cur_ms = int(time.time() * 1000) % 1000
  39. return int(round(random.random() * 2147483647) * cur_ms % 1E10)
  40. def _download_init_data(self, url, mid, fatal=True):
  41. webpage = self._download_webpage(url, mid, fatal=fatal)
  42. return self._search_json(r'window\.__INITIAL_DATA__\s*=', webpage,
  43. 'init data', mid, transform_source=js_to_json, fatal=fatal)
  44. def _make_fcu_req(self, req_dict, mid, headers={}, **kwargs):
  45. return self._download_json(
  46. 'https://u.y.qq.com/cgi-bin/musicu.fcg', mid, data=json.dumps({
  47. 'comm': {
  48. 'cv': 0,
  49. 'ct': 24,
  50. 'format': 'json',
  51. 'uin': self._get_uin(),
  52. },
  53. **req_dict,
  54. }, separators=(',', ':')).encode(), headers=headers, **kwargs)
  55. class QQMusicIE(QQMusicBaseIE):
  56. IE_NAME = 'qqmusic'
  57. IE_DESC = 'QQ音乐'
  58. _VALID_URL = r'https?://y\.qq\.com/n/ryqq/songDetail/(?P<id>[0-9A-Za-z]+)'
  59. _TESTS = [{
  60. 'url': 'https://y.qq.com/n/ryqq/songDetail/004Ti8rT003TaZ',
  61. 'md5': 'd7adc5c438d12e2cb648cca81593fd47',
  62. 'info_dict': {
  63. 'id': '004Ti8rT003TaZ',
  64. 'ext': 'mp3',
  65. 'title': '永夜のパレード (永夜的游行)',
  66. 'album': '幻想遊園郷 -Fantastic Park-',
  67. 'release_date': '20111230',
  68. 'duration': 281,
  69. 'creators': ['ケーキ姫', 'JUMA'],
  70. 'genres': ['Pop'],
  71. 'description': 'md5:b5261f3d595657ae561e9e6aee7eb7d9',
  72. 'size': 4501244,
  73. 'thumbnail': r're:^https?://.*\.jpg(?:$|[#?])',
  74. 'subtitles': 'count:1',
  75. },
  76. }, {
  77. 'url': 'https://y.qq.com/n/ryqq/songDetail/004295Et37taLD',
  78. 'md5': '5f1e6cea39e182857da7ffc5ef5e6bb8',
  79. 'info_dict': {
  80. 'id': '004295Et37taLD',
  81. 'ext': 'mp3',
  82. 'title': '可惜没如果',
  83. 'album': '新地球 - 人 (Special Edition)',
  84. 'release_date': '20150129',
  85. 'duration': 298,
  86. 'creators': ['林俊杰'],
  87. 'genres': ['Pop'],
  88. 'description': 'md5:f568421ff618d2066e74b65a04149c4e',
  89. 'thumbnail': r're:^https?://.*\.jpg(?:$|[#?])',
  90. },
  91. 'skip': 'premium member only',
  92. }, {
  93. 'note': 'There is no mp3-320 version of this song.',
  94. 'url': 'https://y.qq.com/n/ryqq/songDetail/004MsGEo3DdNxV',
  95. 'md5': '028aaef1ae13d8a9f4861a92614887f9',
  96. 'info_dict': {
  97. 'id': '004MsGEo3DdNxV',
  98. 'ext': 'mp3',
  99. 'title': '如果',
  100. 'album': '新传媒电视连续剧金曲系列II',
  101. 'release_date': '20050626',
  102. 'duration': 220,
  103. 'creators': ['李季美'],
  104. 'genres': [],
  105. 'description': 'md5:fc711212aa623b28534954dc4bd67385',
  106. 'size': 3535730,
  107. 'thumbnail': r're:^https?://.*\.jpg(?:$|[#?])',
  108. },
  109. }, {
  110. 'note': 'lyrics not in .lrc format',
  111. 'url': 'https://y.qq.com/n/ryqq/songDetail/001JyApY11tIp6',
  112. 'info_dict': {
  113. 'id': '001JyApY11tIp6',
  114. 'ext': 'mp3',
  115. 'title': 'Shadows Over Transylvania',
  116. 'release_date': '19970225',
  117. 'creator': 'Dark Funeral',
  118. 'description': 'md5:c9b20210587cbcd6836a1c597bab4525',
  119. 'thumbnail': r're:^https?://.*\.jpg(?:$|[#?])',
  120. },
  121. 'params': {'skip_download': True},
  122. 'skip': 'no longer available',
  123. }]
  124. _FORMATS = {
  125. 'F000': {'name': 'flac', 'prefix': 'F000', 'ext': 'flac', 'preference': 60},
  126. 'A000': {'name': 'ape', 'prefix': 'A000', 'ext': 'ape', 'preference': 50},
  127. 'M800': {'name': '320mp3', 'prefix': 'M800', 'ext': 'mp3', 'preference': 40, 'abr': 320},
  128. 'M500': {'name': '128mp3', 'prefix': 'M500', 'ext': 'mp3', 'preference': 30, 'abr': 128},
  129. 'C400': {'name': '96aac', 'prefix': 'C400', 'ext': 'm4a', 'preference': 20, 'abr': 96},
  130. 'C200': {'name': '48aac', 'prefix': 'C200', 'ext': 'm4a', 'preference': 20, 'abr': 48},
  131. }
  132. def _real_extract(self, url):
  133. mid = self._match_id(url)
  134. init_data = self._download_init_data(url, mid, fatal=False)
  135. info_data = self._make_fcu_req({'info': {
  136. 'module': 'music.pf_song_detail_svr',
  137. 'method': 'get_song_detail_yqq',
  138. 'param': {
  139. 'song_mid': mid,
  140. 'song_type': 0,
  141. },
  142. }}, mid, note='Downloading song info')['info']['data']['track_info']
  143. media_mid = info_data['file']['media_mid']
  144. data = self._make_fcu_req({
  145. 'req_1': {
  146. 'module': 'vkey.GetVkeyServer',
  147. 'method': 'CgiGetVkey',
  148. 'param': {
  149. 'guid': str(self._m_r_get_ruin()),
  150. 'songmid': [mid] * len(self._FORMATS),
  151. 'songtype': [0] * len(self._FORMATS),
  152. 'uin': str(self._get_uin()),
  153. 'loginflag': 1,
  154. 'platform': '20',
  155. 'filename': [f'{f["prefix"]}{media_mid}.{f["ext"]}' for f in self._FORMATS.values()],
  156. },
  157. },
  158. 'req_2': {
  159. 'module': 'music.musichallSong.PlayLyricInfo',
  160. 'method': 'GetPlayLyricInfo',
  161. 'param': {'songMID': mid},
  162. },
  163. }, mid, note='Downloading formats and lyric', headers=self.geo_verification_headers())
  164. code = traverse_obj(data, ('req_1', 'code', {int}))
  165. if code != 0:
  166. raise ExtractorError(f'Failed to download format info, error code {code or "unknown"}')
  167. formats = []
  168. for media_info in traverse_obj(data, (
  169. 'req_1', 'data', 'midurlinfo', lambda _, v: v['songmid'] == mid and v['purl']),
  170. ):
  171. format_key = traverse_obj(media_info, ('filename', {str}, {lambda x: x[:4]}))
  172. format_info = self._FORMATS.get(format_key) or {}
  173. format_id = format_info.get('name')
  174. formats.append({
  175. 'url': urljoin('https://dl.stream.qqmusic.qq.com', media_info['purl']),
  176. 'format': format_id,
  177. 'format_id': format_id,
  178. 'size': traverse_obj(info_data, ('file', f'size_{format_id}', {int_or_none})),
  179. 'quality': format_info.get('preference'),
  180. 'abr': format_info.get('abr'),
  181. 'ext': format_info.get('ext'),
  182. 'vcodec': 'none',
  183. })
  184. if not formats and not self.is_logged_in:
  185. self.raise_login_required()
  186. if traverse_obj(data, ('req_2', 'code')):
  187. self.report_warning(f'Failed to download lyric, error {data["req_2"]["code"]!r}')
  188. lrc_content = traverse_obj(data, ('req_2', 'data', 'lyric', {lambda x: base64.b64decode(x).decode('utf-8')}))
  189. info_dict = {
  190. 'id': mid,
  191. 'formats': formats,
  192. **traverse_obj(info_data, {
  193. 'title': ('title', {str}),
  194. 'album': ('album', 'title', {str}, {lambda x: x or None}),
  195. 'release_date': ('time_public', {lambda x: x.replace('-', '') or None}),
  196. 'creators': ('singer', ..., 'name', {str}),
  197. 'alt_title': ('subtitle', {str}, {lambda x: x or None}),
  198. 'duration': ('interval', {int_or_none}),
  199. }),
  200. **traverse_obj(init_data, ('detail', {
  201. 'thumbnail': ('picurl', {url_or_none}),
  202. 'description': ('info', 'intro', 'content', ..., 'value', {str}),
  203. 'genres': ('info', 'genre', 'content', ..., 'value', {str}, all),
  204. }), get_all=False),
  205. }
  206. if lrc_content:
  207. info_dict['subtitles'] = {'origin': [{'ext': 'lrc', 'data': lrc_content}]}
  208. info_dict['description'] = join_nonempty(info_dict.get('description'), lrc_content, delim='\n')
  209. return info_dict
  210. class QQMusicSingerIE(QQMusicBaseIE):
  211. IE_NAME = 'qqmusic:singer'
  212. IE_DESC = 'QQ音乐 - 歌手'
  213. _VALID_URL = r'https?://y\.qq\.com/n/ryqq/singer/(?P<id>[0-9A-Za-z]+)'
  214. _TESTS = [{
  215. 'url': 'https://y.qq.com/n/ryqq/singer/001BLpXF2DyJe2',
  216. 'info_dict': {
  217. 'id': '001BLpXF2DyJe2',
  218. 'title': '林俊杰',
  219. 'description': 'md5:10624ce73b06fa400bc846f59b0305fa',
  220. 'thumbnail': r're:^https?://.*\.jpg(?:$|[#?])',
  221. },
  222. 'playlist_mincount': 100,
  223. }, {
  224. 'url': 'https://y.qq.com/n/ryqq/singer/000Q00f213YzNV',
  225. 'info_dict': {
  226. 'id': '000Q00f213YzNV',
  227. 'title': '桃几OvO',
  228. 'description': '小破站小唱见~希望大家喜欢听我唱歌~!',
  229. 'thumbnail': r're:^https?://.*\.jpg(?:$|[#?])',
  230. },
  231. 'playlist_count': 12,
  232. 'playlist': [{
  233. 'info_dict': {
  234. 'id': '0016cvsy02mmCl',
  235. 'ext': 'mp3',
  236. 'title': '群青',
  237. 'album': '桃几2021年翻唱集',
  238. 'release_date': '20210913',
  239. 'duration': 248,
  240. 'creators': ['桃几OvO'],
  241. 'genres': ['Pop'],
  242. 'description': 'md5:4296005a04edcb5cdbe0889d5055a7ae',
  243. 'size': 3970822,
  244. 'thumbnail': r're:^https?://.*\.jpg(?:$|[#?])',
  245. },
  246. }],
  247. }]
  248. _PAGE_SIZE = 50
  249. def _fetch_page(self, mid, page_size, page_num):
  250. data = self._make_fcu_req({'req_1': {
  251. 'module': 'music.web_singer_info_svr',
  252. 'method': 'get_singer_detail_info',
  253. 'param': {
  254. 'sort': 5,
  255. 'singermid': mid,
  256. 'sin': page_num * page_size,
  257. 'num': page_size,
  258. }}}, mid, note=f'Downloading page {page_num}')
  259. yield from traverse_obj(data, ('req_1', 'data', 'songlist', ..., {lambda x: self.url_result(
  260. f'https://y.qq.com/n/ryqq/songDetail/{x["mid"]}', QQMusicIE, x['mid'], x.get('title'))}))
  261. def _real_extract(self, url):
  262. mid = self._match_id(url)
  263. init_data = self._download_init_data(url, mid, fatal=False)
  264. return self.playlist_result(
  265. OnDemandPagedList(functools.partial(self._fetch_page, mid, self._PAGE_SIZE), self._PAGE_SIZE),
  266. mid, **traverse_obj(init_data, ('singerDetail', {
  267. 'title': ('basic_info', 'name', {str}),
  268. 'description': ('ex_info', 'desc', {str}),
  269. 'thumbnail': ('pic', 'pic', {url_or_none}),
  270. })))
  271. class QQPlaylistBaseIE(InfoExtractor):
  272. def _extract_entries(self, info_json, path):
  273. for song in traverse_obj(info_json, path):
  274. song_mid = song.get('songmid')
  275. if not song_mid:
  276. continue
  277. yield self.url_result(
  278. f'https://y.qq.com/n/ryqq/songDetail/{song_mid}',
  279. QQMusicIE, song_mid, song.get('songname'))
  280. class QQMusicAlbumIE(QQPlaylistBaseIE):
  281. IE_NAME = 'qqmusic:album'
  282. IE_DESC = 'QQ音乐 - 专辑'
  283. _VALID_URL = r'https?://y\.qq\.com/n/ryqq/albumDetail/(?P<id>[0-9A-Za-z]+)'
  284. _TESTS = [{
  285. 'url': 'https://y.qq.com/n/ryqq/albumDetail/000gXCTb2AhRR1',
  286. 'info_dict': {
  287. 'id': '000gXCTb2AhRR1',
  288. 'title': '我们都是这样长大的',
  289. 'description': 'md5:179c5dce203a5931970d306aa9607ea6',
  290. },
  291. 'playlist_count': 4,
  292. }, {
  293. 'url': 'https://y.qq.com/n/ryqq/albumDetail/002Y5a3b3AlCu3',
  294. 'info_dict': {
  295. 'id': '002Y5a3b3AlCu3',
  296. 'title': '그리고…',
  297. 'description': 'md5:a48823755615508a95080e81b51ba729',
  298. },
  299. 'playlist_count': 8,
  300. }]
  301. def _real_extract(self, url):
  302. mid = self._match_id(url)
  303. album_json = self._download_json(
  304. 'http://i.y.qq.com/v8/fcg-bin/fcg_v8_album_info_cp.fcg',
  305. mid, 'Download album page',
  306. query={'albummid': mid, 'format': 'json'})['data']
  307. entries = self._extract_entries(album_json, ('list', ...))
  308. return self.playlist_result(entries, mid, **traverse_obj(album_json, {
  309. 'title': ('name', {str}),
  310. 'description': ('desc', {str.strip}),
  311. }))
  312. class QQMusicToplistIE(QQPlaylistBaseIE):
  313. IE_NAME = 'qqmusic:toplist'
  314. IE_DESC = 'QQ音乐 - 排行榜'
  315. _VALID_URL = r'https?://y\.qq\.com/n/ryqq/toplist/(?P<id>[0-9]+)'
  316. _TESTS = [{
  317. 'url': 'https://y.qq.com/n/ryqq/toplist/123',
  318. 'info_dict': {
  319. 'id': '123',
  320. 'title': r're:美国热门音乐榜 \d{4}-\d{2}-\d{2}',
  321. 'description': '美国热门音乐榜,每周一更新。',
  322. },
  323. 'playlist_count': 95,
  324. }, {
  325. 'url': 'https://y.qq.com/n/ryqq/toplist/3',
  326. 'info_dict': {
  327. 'id': '3',
  328. 'title': r're:巅峰榜·欧美 \d{4}-\d{2}-\d{2}',
  329. 'description': 'md5:4def03b60d3644be4c9a36f21fd33857',
  330. },
  331. 'playlist_count': 100,
  332. }, {
  333. 'url': 'https://y.qq.com/n/ryqq/toplist/106',
  334. 'info_dict': {
  335. 'id': '106',
  336. 'title': r're:韩国Mnet榜 \d{4}-\d{2}-\d{2}',
  337. 'description': 'md5:cb84b325215e1d21708c615cac82a6e7',
  338. },
  339. 'playlist_count': 50,
  340. }]
  341. def _real_extract(self, url):
  342. list_id = self._match_id(url)
  343. toplist_json = self._download_json(
  344. 'http://i.y.qq.com/v8/fcg-bin/fcg_v8_toplist_cp.fcg', list_id,
  345. note='Download toplist page',
  346. query={'type': 'toplist', 'topid': list_id, 'format': 'json'})
  347. return self.playlist_result(
  348. self._extract_entries(toplist_json, ('songlist', ..., 'data')), list_id,
  349. playlist_title=join_nonempty(*traverse_obj(
  350. toplist_json, ((('topinfo', 'ListName'), 'update_time'), None)), delim=' '),
  351. playlist_description=traverse_obj(toplist_json, ('topinfo', 'info')))
  352. class QQMusicPlaylistIE(QQPlaylistBaseIE):
  353. IE_NAME = 'qqmusic:playlist'
  354. IE_DESC = 'QQ音乐 - 歌单'
  355. _VALID_URL = r'https?://y\.qq\.com/n/ryqq/playlist/(?P<id>[0-9]+)'
  356. _TESTS = [{
  357. 'url': 'https://y.qq.com/n/ryqq/playlist/1374105607',
  358. 'info_dict': {
  359. 'id': '1374105607',
  360. 'title': '易入人心的华语民谣',
  361. 'description': '民谣的歌曲易于传唱、、歌词朗朗伤口、旋律简单温馨。属于那种才入耳孔。却上心头的感觉。没有太多的复杂情绪。简单而直接地表达乐者的情绪,就是这样的简单才易入人心。',
  362. },
  363. 'playlist_count': 20,
  364. }]
  365. def _real_extract(self, url):
  366. list_id = self._match_id(url)
  367. list_json = self._download_json(
  368. 'http://i.y.qq.com/qzone-music/fcg-bin/fcg_ucc_getcdinfo_byids_cp.fcg',
  369. list_id, 'Download list page',
  370. query={'type': 1, 'json': 1, 'utf8': 1, 'onlysong': 0, 'disstid': list_id},
  371. transform_source=strip_jsonp, headers={'Referer': url})
  372. if not len(list_json.get('cdlist', [])):
  373. raise ExtractorError(join_nonempty(
  374. 'Unable to get playlist info',
  375. join_nonempty('code', 'subcode', from_dict=list_json),
  376. list_json.get('msg'), delim=': '))
  377. entries = self._extract_entries(list_json, ('cdlist', 0, 'songlist', ...))
  378. return self.playlist_result(entries, list_id, **traverse_obj(list_json, ('cdlist', 0, {
  379. 'title': ('dissname', {str}),
  380. 'description': ('desc', {unescapeHTML}, {clean_html}),
  381. })))
  382. class QQMusicVideoIE(QQMusicBaseIE):
  383. IE_NAME = 'qqmusic:mv'
  384. IE_DESC = 'QQ音乐 - MV'
  385. _VALID_URL = r'https?://y\.qq\.com/n/ryqq/mv/(?P<id>[0-9A-Za-z]+)'
  386. _TESTS = [{
  387. 'url': 'https://y.qq.com/n/ryqq/mv/002Vsarh3SVU8K',
  388. 'info_dict': {
  389. 'id': '002Vsarh3SVU8K',
  390. 'ext': 'mp4',
  391. 'title': 'The Chant (Extended Mix / Audio)',
  392. 'description': '',
  393. 'thumbnail': r're:^https?://.*\.jpg(?:$|[#?])',
  394. 'release_timestamp': 1688918400,
  395. 'release_date': '20230709',
  396. 'duration': 313,
  397. 'creators': ['Duke Dumont'],
  398. 'view_count': int,
  399. },
  400. }]
  401. def _parse_url_formats(self, url_data):
  402. return traverse_obj(url_data, ('mp4', lambda _, v: v['freeflow_url'], {
  403. 'url': ('freeflow_url', 0, {url_or_none}),
  404. 'filesize': ('fileSize', {int_or_none}),
  405. 'format_id': ('newFileType', {str_or_none}),
  406. }))
  407. def _real_extract(self, url):
  408. video_id = self._match_id(url)
  409. video_info = self._make_fcu_req({
  410. 'mvInfo': {
  411. 'module': 'music.video.VideoData',
  412. 'method': 'get_video_info_batch',
  413. 'param': {
  414. 'vidlist': [video_id],
  415. 'required': [
  416. 'vid', 'type', 'sid', 'cover_pic', 'duration', 'singers',
  417. 'video_pay', 'hint', 'code', 'msg', 'name', 'desc',
  418. 'playcnt', 'pubdate', 'play_forbid_reason'],
  419. },
  420. },
  421. 'mvUrl': {
  422. 'module': 'music.stream.MvUrlProxy',
  423. 'method': 'GetMvUrls',
  424. 'param': {'vids': [video_id]},
  425. },
  426. }, video_id, headers=self.geo_verification_headers())
  427. if traverse_obj(video_info, ('mvInfo', 'data', video_id, 'play_forbid_reason')) == 3:
  428. self.raise_geo_restricted()
  429. return {
  430. 'id': video_id,
  431. 'formats': self._parse_url_formats(traverse_obj(video_info, ('mvUrl', 'data', video_id))),
  432. **traverse_obj(video_info, ('mvInfo', 'data', video_id, {
  433. 'title': ('name', {str}),
  434. 'description': ('desc', {str}),
  435. 'thumbnail': ('cover_pic', {url_or_none}),
  436. 'release_timestamp': ('pubdate', {int_or_none}),
  437. 'duration': ('duration', {int_or_none}),
  438. 'creators': ('singers', ..., 'name', {str}),
  439. 'view_count': ('playcnt', {int_or_none}),
  440. })),
  441. }