[qqmusic] Fix song extraction when certain formats are unavailable
[youtube-dl] / youtube_dl / extractor / qqmusic.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import random
5 import time
6 import re
7
8 from .common import InfoExtractor
9 from ..utils import (
10     strip_jsonp,
11     unescapeHTML,
12     HEADRequest,
13     ExtractorError,
14 )
15 from ..compat import (
16     compat_urllib_request,
17     compat_HTTPError,
18 )
19
20
21 class QQMusicIE(InfoExtractor):
22     IE_NAME = 'qqmusic'
23     _VALID_URL = r'http://y.qq.com/#type=song&mid=(?P<id>[0-9A-Za-z]+)'
24     _TESTS = [{
25         'url': 'http://y.qq.com/#type=song&mid=004295Et37taLD',
26         'md5': '9ce1c1c8445f561506d2e3cfb0255705',
27         'info_dict': {
28             'id': '004295Et37taLD',
29             'ext': 'mp3',
30             'title': '可惜没如果',
31             'upload_date': '20141227',
32             'creator': '林俊杰',
33             'description': 'md5:d327722d0361576fde558f1ac68a7065',
34             'thumbnail': 'http://i.gtimg.cn/music/photo/mid_album_500/7/p/001IV22P1RDX7p.jpg',
35         }
36     }, {
37         'note': 'There is no mp3-320 version of this song.',
38         'url': 'http://y.qq.com/#type=song&mid=004MsGEo3DdNxV',
39         'md5': 'fa3926f0c585cda0af8fa4f796482e3e',
40         'info_dict': {
41             'id': '004MsGEo3DdNxV',
42             'ext': 'mp3',
43             'title': '如果',
44             'upload_date': '20050626',
45             'creator': '李季美',
46             'description': 'md5:46857d5ed62bc4ba84607a805dccf437',
47             'thumbnail': 'http://i.gtimg.cn/music/photo/mid_album_500/r/Q/0042owYj46IxrQ.jpg',
48         }
49     }]
50
51     _FORMATS = {
52         'mp3-320': {'prefix': 'M800', 'ext': 'mp3', 'preference': 40, 'abr': 320},
53         'mp3-128': {'prefix': 'M500', 'ext': 'mp3', 'preference': 30, 'abr': 128},
54         'm4a': {'prefix': 'C200', 'ext': 'm4a', 'preference': 10}
55     }
56
57     # Reference: m_r_GetRUin() in top_player.js
58     # http://imgcache.gtimg.cn/music/portal_v3/y/top_player.js
59     @staticmethod
60     def m_r_get_ruin():
61         curMs = int(time.time() * 1000) % 1000
62         return int(round(random.random() * 2147483647) * curMs % 1E10)
63
64     def _real_extract(self, url):
65         mid = self._match_id(url)
66
67         detail_info_page = self._download_webpage(
68             'http://s.plcloud.music.qq.com/fcgi-bin/fcg_yqq_song_detail_info.fcg?songmid=%s&play=0' % mid,
69             mid, note='Download song detail info',
70             errnote='Unable to get song detail info', encoding='gbk')
71
72         song_name = self._html_search_regex(
73             r"songname:\s*'([^']+)'", detail_info_page, 'song name')
74
75         publish_time = self._html_search_regex(
76             r'发行时间:(\d{4}-\d{2}-\d{2})', detail_info_page,
77             'publish time', default=None)
78         if publish_time:
79             publish_time = publish_time.replace('-', '')
80
81         singer = self._html_search_regex(
82             r"singer:\s*'([^']+)", detail_info_page, 'singer', default=None)
83
84         lrc_content = self._html_search_regex(
85             r'<div class="content" id="lrc_content"[^<>]*>([^<>]+)</div>',
86             detail_info_page, 'LRC lyrics', default=None)
87         if lrc_content:
88             lrc_content = lrc_content.replace('\\n', '\n')
89
90         thumbnail_url = None
91         albummid = self._search_regex(
92             [r'albummid:\'([0-9a-zA-Z]+)\'', r'"albummid":"([0-9a-zA-Z]+)"'], detail_info_page, 'album mid', default=None)
93         if albummid:
94             thumbnail_url = "http://i.gtimg.cn/music/photo/mid_album_500/%s/%s/%s.jpg" \
95                             % (albummid[-2:-1], albummid[-1], albummid)
96
97         guid = self.m_r_get_ruin()
98
99         vkey = self._download_json(
100             'http://base.music.qq.com/fcgi-bin/fcg_musicexpress.fcg?json=3&guid=%s' % guid,
101             mid, note='Retrieve vkey', errnote='Unable to get vkey',
102             transform_source=strip_jsonp)['key']
103
104         formats = []
105         for format_id, details in self._FORMATS.items():
106             video_url = 'http://cc.stream.qqmusic.qq.com/%s%s.%s?vkey=%s&guid=%s&fromtag=0' \
107                         % (details['prefix'], mid, details['ext'], vkey, guid)
108             req = HEADRequest(video_url)
109             try:
110                 res = self._request_webpage(
111                     req, mid, note='Testing %s video URL' % format_id, fatal=False)
112             except ExtractorError as e:
113                 if isinstance(e.cause, compat_HTTPError) and e.cause.code in [400, 404]:
114                     self.report_warning('Invalid %s video URL' % format_id, mid)
115             else:
116                 if res:
117                     formats.append({
118                         'url': video_url,
119                         'format': format_id,
120                         'format_id': format_id,
121                         'preference': details['preference'],
122                         'abr': details.get('abr'),
123                     })
124         self._sort_formats(formats)
125
126         return {
127             'id': mid,
128             'formats': formats,
129             'title': song_name,
130             'upload_date': publish_time,
131             'creator': singer,
132             'description': lrc_content,
133             'thumbnail': thumbnail_url,
134         }
135
136
137 class QQPlaylistBaseIE(InfoExtractor):
138     @staticmethod
139     def qq_static_url(category, mid):
140         return 'http://y.qq.com/y/static/%s/%s/%s/%s.html' % (category, mid[-2], mid[-1], mid)
141
142     @classmethod
143     def get_entries_from_page(cls, page):
144         entries = []
145
146         for item in re.findall(r'class="data"[^<>]*>([^<>]+)</', page):
147             song_mid = unescapeHTML(item).split('|')[-5]
148             entries.append(cls.url_result(
149                 'http://y.qq.com/#type=song&mid=' + song_mid, 'QQMusic',
150                 song_mid))
151
152         return entries
153
154
155 class QQMusicSingerIE(QQPlaylistBaseIE):
156     IE_NAME = 'qqmusic:singer'
157     _VALID_URL = r'http://y.qq.com/#type=singer&mid=(?P<id>[0-9A-Za-z]+)'
158     _TEST = {
159         'url': 'http://y.qq.com/#type=singer&mid=001BLpXF2DyJe2',
160         'info_dict': {
161             'id': '001BLpXF2DyJe2',
162             'title': '林俊杰',
163             'description': 'md5:2a222d89ba4455a3af19940c0481bb78',
164         },
165         'playlist_count': 12,
166     }
167
168     def _real_extract(self, url):
169         mid = self._match_id(url)
170
171         singer_page = self._download_webpage(
172             self.qq_static_url('singer', mid), mid, 'Download singer page')
173
174         entries = self.get_entries_from_page(singer_page)
175
176         singer_name = self._html_search_regex(
177             r"singername\s*:\s*'([^']+)'", singer_page, 'singer name',
178             default=None)
179
180         singer_id = self._html_search_regex(
181             r"singerid\s*:\s*'([0-9]+)'", singer_page, 'singer id',
182             default=None)
183
184         singer_desc = None
185
186         if singer_id:
187             req = compat_urllib_request.Request(
188                 'http://s.plcloud.music.qq.com/fcgi-bin/fcg_get_singer_desc.fcg?utf8=1&outCharset=utf-8&format=xml&singerid=%s' % singer_id)
189             req.add_header(
190                 'Referer', 'http://s.plcloud.music.qq.com/xhr_proxy_utf8.html')
191             singer_desc_page = self._download_xml(
192                 req, mid, 'Donwload singer description XML')
193
194             singer_desc = singer_desc_page.find('./data/info/desc').text
195
196         return self.playlist_result(entries, mid, singer_name, singer_desc)
197
198
199 class QQMusicAlbumIE(QQPlaylistBaseIE):
200     IE_NAME = 'qqmusic:album'
201     _VALID_URL = r'http://y.qq.com/#type=album&mid=(?P<id>[0-9A-Za-z]+)'
202
203     _TEST = {
204         'url': 'http://y.qq.com/#type=album&mid=000gXCTb2AhRR1&play=0',
205         'info_dict': {
206             'id': '000gXCTb2AhRR1',
207             'title': '我们都是这样长大的',
208             'description': 'md5:d216c55a2d4b3537fe4415b8767d74d6',
209         },
210         'playlist_count': 4,
211     }
212
213     def _real_extract(self, url):
214         mid = self._match_id(url)
215
216         album_page = self._download_webpage(
217             self.qq_static_url('album', mid), mid, 'Download album page')
218
219         entries = self.get_entries_from_page(album_page)
220
221         album_name = self._html_search_regex(
222             r"albumname\s*:\s*'([^']+)',", album_page, 'album name',
223             default=None)
224
225         album_detail = self._html_search_regex(
226             r'<div class="album_detail close_detail">\s*<p>((?:[^<>]+(?:<br />)?)+)</p>',
227             album_page, 'album details', default=None)
228
229         return self.playlist_result(entries, mid, album_name, album_detail)
230
231
232 class QQMusicToplistIE(QQPlaylistBaseIE):
233     IE_NAME = 'qqmusic:toplist'
234     _VALID_URL = r'http://y\.qq\.com/#type=toplist&p=(?P<id>(top|global)_[0-9]+)'
235
236     _TESTS = [{
237         'url': 'http://y.qq.com/#type=toplist&p=global_123',
238         'info_dict': {
239             'id': 'global_123',
240             'title': '美国iTunes榜',
241         },
242         'playlist_count': 10,
243     }, {
244         'url': 'http://y.qq.com/#type=toplist&p=top_3',
245         'info_dict': {
246             'id': 'top_3',
247             'title': 'QQ音乐巅峰榜·欧美',
248             'description': 'QQ音乐巅峰榜·欧美根据用户收听行为自动生成,集结当下最流行的欧美新歌!:更新时间:每周四22点|统'
249                            '计周期:一周(上周四至本周三)|统计对象:三个月内发行的欧美歌曲|统计数量:100首|统计算法:根据'
250                            '歌曲在一周内的有效播放次数,由高到低取前100名(同一歌手最多允许5首歌曲同时上榜)|有效播放次数:'
251                            '登录用户完整播放一首歌曲,记为一次有效播放;同一用户收听同一首歌曲,每天记录为1次有效播放'
252         },
253         'playlist_count': 100,
254     }, {
255         'url': 'http://y.qq.com/#type=toplist&p=global_106',
256         'info_dict': {
257             'id': 'global_106',
258             'title': '韩国Mnet榜',
259         },
260         'playlist_count': 50,
261     }]
262
263     def _real_extract(self, url):
264         list_id = self._match_id(url)
265
266         list_type, num_id = list_id.split("_")
267
268         toplist_json = self._download_json(
269             'http://i.y.qq.com/v8/fcg-bin/fcg_v8_toplist_cp.fcg?type=%s&topid=%s&format=json'
270             % (list_type, num_id),
271             list_id, 'Download toplist page')
272
273         entries = [
274             self.url_result(
275                 'http://y.qq.com/#type=song&mid=' + song['data']['songmid'], 'QQMusic', song['data']['songmid']
276             ) for song in toplist_json['songlist']
277         ]
278
279         topinfo = toplist_json.get('topinfo', {})
280         list_name = topinfo.get('ListName')
281         list_description = topinfo.get('info')
282         return self.playlist_result(entries, list_id, list_name, list_description)