Fix "invalid escape sequences" error on Python 3.6
[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     sanitized_Request,
11     strip_jsonp,
12     unescapeHTML,
13     clean_html,
14     ExtractorError,
15 )
16
17
18 class QQMusicIE(InfoExtractor):
19     IE_NAME = 'qqmusic'
20     IE_DESC = 'QQ音乐'
21     _VALID_URL = r'https?://y\.qq\.com/#type=song&mid=(?P<id>[0-9A-Za-z]+)'
22     _TESTS = [{
23         'url': 'http://y.qq.com/#type=song&mid=004295Et37taLD',
24         'md5': '9ce1c1c8445f561506d2e3cfb0255705',
25         'info_dict': {
26             'id': '004295Et37taLD',
27             'ext': 'mp3',
28             'title': '可惜没如果',
29             'release_date': '20141227',
30             'creator': '林俊杰',
31             'description': 'md5:d327722d0361576fde558f1ac68a7065',
32             'thumbnail': r're:^https?://.*\.jpg$',
33         }
34     }, {
35         'note': 'There is no mp3-320 version of this song.',
36         'url': 'http://y.qq.com/#type=song&mid=004MsGEo3DdNxV',
37         'md5': 'fa3926f0c585cda0af8fa4f796482e3e',
38         'info_dict': {
39             'id': '004MsGEo3DdNxV',
40             'ext': 'mp3',
41             'title': '如果',
42             'release_date': '20050626',
43             'creator': '李季美',
44             'description': 'md5:46857d5ed62bc4ba84607a805dccf437',
45             'thumbnail': r're:^https?://.*\.jpg$',
46         }
47     }, {
48         'note': 'lyrics not in .lrc format',
49         'url': 'http://y.qq.com/#type=song&mid=001JyApY11tIp6',
50         'info_dict': {
51             'id': '001JyApY11tIp6',
52             'ext': 'mp3',
53             'title': 'Shadows Over Transylvania',
54             'release_date': '19970225',
55             'creator': 'Dark Funeral',
56             'description': 'md5:ed14d5bd7ecec19609108052c25b2c11',
57             'thumbnail': r're:^https?://.*\.jpg$',
58         },
59         'params': {
60             'skip_download': True,
61         },
62     }]
63
64     _FORMATS = {
65         'mp3-320': {'prefix': 'M800', 'ext': 'mp3', 'preference': 40, 'abr': 320},
66         'mp3-128': {'prefix': 'M500', 'ext': 'mp3', 'preference': 30, 'abr': 128},
67         'm4a': {'prefix': 'C200', 'ext': 'm4a', 'preference': 10}
68     }
69
70     # Reference: m_r_GetRUin() in top_player.js
71     # http://imgcache.gtimg.cn/music/portal_v3/y/top_player.js
72     @staticmethod
73     def m_r_get_ruin():
74         curMs = int(time.time() * 1000) % 1000
75         return int(round(random.random() * 2147483647) * curMs % 1E10)
76
77     def _real_extract(self, url):
78         mid = self._match_id(url)
79
80         detail_info_page = self._download_webpage(
81             'http://s.plcloud.music.qq.com/fcgi-bin/fcg_yqq_song_detail_info.fcg?songmid=%s&play=0' % mid,
82             mid, note='Download song detail info',
83             errnote='Unable to get song detail info', encoding='gbk')
84
85         song_name = self._html_search_regex(
86             r"songname:\s*'([^']+)'", detail_info_page, 'song name')
87
88         publish_time = self._html_search_regex(
89             r'发行时间:(\d{4}-\d{2}-\d{2})', detail_info_page,
90             'publish time', default=None)
91         if publish_time:
92             publish_time = publish_time.replace('-', '')
93
94         singer = self._html_search_regex(
95             r"singer:\s*'([^']+)", detail_info_page, 'singer', default=None)
96
97         lrc_content = self._html_search_regex(
98             r'<div class="content" id="lrc_content"[^<>]*>([^<>]+)</div>',
99             detail_info_page, 'LRC lyrics', default=None)
100         if lrc_content:
101             lrc_content = lrc_content.replace('\\n', '\n')
102
103         thumbnail_url = None
104         albummid = self._search_regex(
105             [r'albummid:\'([0-9a-zA-Z]+)\'', r'"albummid":"([0-9a-zA-Z]+)"'],
106             detail_info_page, 'album mid', default=None)
107         if albummid:
108             thumbnail_url = "http://i.gtimg.cn/music/photo/mid_album_500/%s/%s/%s.jpg" \
109                             % (albummid[-2:-1], albummid[-1], albummid)
110
111         guid = self.m_r_get_ruin()
112
113         vkey = self._download_json(
114             'http://base.music.qq.com/fcgi-bin/fcg_musicexpress.fcg?json=3&guid=%s' % guid,
115             mid, note='Retrieve vkey', errnote='Unable to get vkey',
116             transform_source=strip_jsonp)['key']
117
118         formats = []
119         for format_id, details in self._FORMATS.items():
120             formats.append({
121                 'url': 'http://cc.stream.qqmusic.qq.com/%s%s.%s?vkey=%s&guid=%s&fromtag=0'
122                        % (details['prefix'], mid, details['ext'], vkey, guid),
123                 'format': format_id,
124                 'format_id': format_id,
125                 'preference': details['preference'],
126                 'abr': details.get('abr'),
127             })
128         self._check_formats(formats, mid)
129         self._sort_formats(formats)
130
131         actual_lrc_lyrics = ''.join(
132             line + '\n' for line in re.findall(
133                 r'(?m)^(\[[0-9]{2}:[0-9]{2}(?:\.[0-9]{2,})?\][^\n]*|\[[^\]]*\])', lrc_content))
134
135         info_dict = {
136             'id': mid,
137             'formats': formats,
138             'title': song_name,
139             'release_date': publish_time,
140             'creator': singer,
141             'description': lrc_content,
142             'thumbnail': thumbnail_url
143         }
144         if actual_lrc_lyrics:
145             info_dict['subtitles'] = {
146                 'origin': [{
147                     'ext': 'lrc',
148                     'data': actual_lrc_lyrics,
149                 }]
150             }
151         return info_dict
152
153
154 class QQPlaylistBaseIE(InfoExtractor):
155     @staticmethod
156     def qq_static_url(category, mid):
157         return 'http://y.qq.com/y/static/%s/%s/%s/%s.html' % (category, mid[-2], mid[-1], mid)
158
159     @classmethod
160     def get_entries_from_page(cls, page):
161         entries = []
162
163         for item in re.findall(r'class="data"[^<>]*>([^<>]+)</', page):
164             song_mid = unescapeHTML(item).split('|')[-5]
165             entries.append(cls.url_result(
166                 'http://y.qq.com/#type=song&mid=' + song_mid, 'QQMusic',
167                 song_mid))
168
169         return entries
170
171
172 class QQMusicSingerIE(QQPlaylistBaseIE):
173     IE_NAME = 'qqmusic:singer'
174     IE_DESC = 'QQ音乐 - 歌手'
175     _VALID_URL = r'https?://y\.qq\.com/#type=singer&mid=(?P<id>[0-9A-Za-z]+)'
176     _TEST = {
177         'url': 'http://y.qq.com/#type=singer&mid=001BLpXF2DyJe2',
178         'info_dict': {
179             'id': '001BLpXF2DyJe2',
180             'title': '林俊杰',
181             'description': 'md5:870ec08f7d8547c29c93010899103751',
182         },
183         'playlist_count': 12,
184     }
185
186     def _real_extract(self, url):
187         mid = self._match_id(url)
188
189         singer_page = self._download_webpage(
190             self.qq_static_url('singer', mid), mid, 'Download singer page')
191
192         entries = self.get_entries_from_page(singer_page)
193
194         singer_name = self._html_search_regex(
195             r"singername\s*:\s*'([^']+)'", singer_page, 'singer name',
196             default=None)
197
198         singer_id = self._html_search_regex(
199             r"singerid\s*:\s*'([0-9]+)'", singer_page, 'singer id',
200             default=None)
201
202         singer_desc = None
203
204         if singer_id:
205             req = sanitized_Request(
206                 'http://s.plcloud.music.qq.com/fcgi-bin/fcg_get_singer_desc.fcg?utf8=1&outCharset=utf-8&format=xml&singerid=%s' % singer_id)
207             req.add_header(
208                 'Referer', 'http://s.plcloud.music.qq.com/xhr_proxy_utf8.html')
209             singer_desc_page = self._download_xml(
210                 req, mid, 'Donwload singer description XML')
211
212             singer_desc = singer_desc_page.find('./data/info/desc').text
213
214         return self.playlist_result(entries, mid, singer_name, singer_desc)
215
216
217 class QQMusicAlbumIE(QQPlaylistBaseIE):
218     IE_NAME = 'qqmusic:album'
219     IE_DESC = 'QQ音乐 - 专辑'
220     _VALID_URL = r'https?://y\.qq\.com/#type=album&mid=(?P<id>[0-9A-Za-z]+)'
221
222     _TESTS = [{
223         'url': 'http://y.qq.com/#type=album&mid=000gXCTb2AhRR1',
224         'info_dict': {
225             'id': '000gXCTb2AhRR1',
226             'title': '我们都是这样长大的',
227             'description': 'md5:179c5dce203a5931970d306aa9607ea6',
228         },
229         'playlist_count': 4,
230     }, {
231         'url': 'http://y.qq.com/#type=album&mid=002Y5a3b3AlCu3',
232         'info_dict': {
233             'id': '002Y5a3b3AlCu3',
234             'title': '그리고...',
235             'description': 'md5:a48823755615508a95080e81b51ba729',
236         },
237         'playlist_count': 8,
238     }]
239
240     def _real_extract(self, url):
241         mid = self._match_id(url)
242
243         album = self._download_json(
244             'http://i.y.qq.com/v8/fcg-bin/fcg_v8_album_info_cp.fcg?albummid=%s&format=json' % mid,
245             mid, 'Download album page')['data']
246
247         entries = [
248             self.url_result(
249                 'http://y.qq.com/#type=song&mid=' + song['songmid'], 'QQMusic', song['songmid']
250             ) for song in album['list']
251         ]
252         album_name = album.get('name')
253         album_detail = album.get('desc')
254         if album_detail is not None:
255             album_detail = album_detail.strip()
256
257         return self.playlist_result(entries, mid, album_name, album_detail)
258
259
260 class QQMusicToplistIE(QQPlaylistBaseIE):
261     IE_NAME = 'qqmusic:toplist'
262     IE_DESC = 'QQ音乐 - 排行榜'
263     _VALID_URL = r'https?://y\.qq\.com/#type=toplist&p=(?P<id>(top|global)_[0-9]+)'
264
265     _TESTS = [{
266         'url': 'http://y.qq.com/#type=toplist&p=global_123',
267         'info_dict': {
268             'id': 'global_123',
269             'title': '美国iTunes榜',
270         },
271         'playlist_count': 10,
272     }, {
273         'url': 'http://y.qq.com/#type=toplist&p=top_3',
274         'info_dict': {
275             'id': 'top_3',
276             'title': '巅峰榜·欧美',
277             'description': 'QQ音乐巅峰榜·欧美根据用户收听行为自动生成,集结当下最流行的欧美新歌!:更新时间:每周四22点|统'
278                            '计周期:一周(上周四至本周三)|统计对象:三个月内发行的欧美歌曲|统计数量:100首|统计算法:根据'
279                            '歌曲在一周内的有效播放次数,由高到低取前100名(同一歌手最多允许5首歌曲同时上榜)|有效播放次数:'
280                            '登录用户完整播放一首歌曲,记为一次有效播放;同一用户收听同一首歌曲,每天记录为1次有效播放'
281         },
282         'playlist_count': 100,
283     }, {
284         'url': 'http://y.qq.com/#type=toplist&p=global_106',
285         'info_dict': {
286             'id': 'global_106',
287             'title': '韩国Mnet榜',
288         },
289         'playlist_count': 50,
290     }]
291
292     def _real_extract(self, url):
293         list_id = self._match_id(url)
294
295         list_type, num_id = list_id.split("_")
296
297         toplist_json = self._download_json(
298             'http://i.y.qq.com/v8/fcg-bin/fcg_v8_toplist_cp.fcg?type=%s&topid=%s&format=json'
299             % (list_type, num_id),
300             list_id, 'Download toplist page')
301
302         entries = [
303             self.url_result(
304                 'http://y.qq.com/#type=song&mid=' + song['data']['songmid'], 'QQMusic', song['data']['songmid']
305             ) for song in toplist_json['songlist']
306         ]
307
308         topinfo = toplist_json.get('topinfo', {})
309         list_name = topinfo.get('ListName')
310         list_description = topinfo.get('info')
311         return self.playlist_result(entries, list_id, list_name, list_description)
312
313
314 class QQMusicPlaylistIE(QQPlaylistBaseIE):
315     IE_NAME = 'qqmusic:playlist'
316     IE_DESC = 'QQ音乐 - 歌单'
317     _VALID_URL = r'https?://y\.qq\.com/#type=taoge&id=(?P<id>[0-9]+)'
318
319     _TESTS = [{
320         'url': 'http://y.qq.com/#type=taoge&id=3462654915',
321         'info_dict': {
322             'id': '3462654915',
323             'title': '韩国5月新歌精选下旬',
324             'description': 'md5:d2c9d758a96b9888cf4fe82f603121d4',
325         },
326         'playlist_count': 40,
327         'skip': 'playlist gone',
328     }, {
329         'url': 'http://y.qq.com/#type=taoge&id=1374105607',
330         'info_dict': {
331             'id': '1374105607',
332             'title': '易入人心的华语民谣',
333             'description': '民谣的歌曲易于传唱、、歌词朗朗伤口、旋律简单温馨。属于那种才入耳孔。却上心头的感觉。没有太多的复杂情绪。简单而直接地表达乐者的情绪,就是这样的简单才易入人心。',
334         },
335         'playlist_count': 20,
336     }]
337
338     def _real_extract(self, url):
339         list_id = self._match_id(url)
340
341         list_json = self._download_json(
342             'http://i.y.qq.com/qzone-music/fcg-bin/fcg_ucc_getcdinfo_byids_cp.fcg?type=1&json=1&utf8=1&onlysong=0&disstid=%s'
343             % list_id, list_id, 'Download list page',
344             transform_source=strip_jsonp)
345         if not len(list_json.get('cdlist', [])):
346             if list_json.get('code'):
347                 raise ExtractorError(
348                     'QQ Music said: error %d in fetching playlist info' % list_json['code'],
349                     expected=True)
350             raise ExtractorError('Unable to get playlist info')
351
352         cdlist = list_json['cdlist'][0]
353         entries = [
354             self.url_result(
355                 'http://y.qq.com/#type=song&mid=' + song['songmid'], 'QQMusic', song['songmid']
356             ) for song in cdlist['songlist']
357         ]
358
359         list_name = cdlist.get('dissname')
360         list_description = clean_html(unescapeHTML(cdlist.get('desc')))
361         return self.playlist_result(entries, list_id, list_name, list_description)