[kwuo] Fix KuwoChartIE and KuwoSingerIE and accept new URL forms
[youtube-dl] / youtube_dl / extractor / kuwo.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..utils import (
8     get_element_by_id,
9     clean_html,
10     ExtractorError,
11     InAdvancePagedList,
12     remove_start,
13 )
14
15
16 class KuwoBaseIE(InfoExtractor):
17     _FORMATS = [
18         {'format': 'ape', 'ext': 'ape', 'preference': 100},
19         {'format': 'mp3-320', 'ext': 'mp3', 'br': '320kmp3', 'abr': 320, 'preference': 80},
20         {'format': 'mp3-192', 'ext': 'mp3', 'br': '192kmp3', 'abr': 192, 'preference': 70},
21         {'format': 'mp3-128', 'ext': 'mp3', 'br': '128kmp3', 'abr': 128, 'preference': 60},
22         {'format': 'wma', 'ext': 'wma', 'preference': 20},
23         {'format': 'aac', 'ext': 'aac', 'abr': 48, 'preference': 10}
24     ]
25
26     def _get_formats(self, song_id, tolerate_ip_deny=False):
27         formats = []
28         for file_format in self._FORMATS:
29             song_url = self._download_webpage(
30                 'http://antiserver.kuwo.cn/anti.s?format=%s&br=%s&rid=MUSIC_%s&type=convert_url&response=url' %
31                 (file_format['ext'], file_format.get('br', ''), song_id),
32                 song_id, note='Download %s url info' % file_format['format'],
33             )
34
35             if song_url == 'IPDeny' and not tolerate_ip_deny:
36                 raise ExtractorError('This song is blocked in this region', expected=True)
37
38             if song_url.startswith('http://') or song_url.startswith('https://'):
39                 formats.append({
40                     'url': song_url,
41                     'format_id': file_format['format'],
42                     'format': file_format['format'],
43                     'preference': file_format['preference'],
44                     'abr': file_format.get('abr'),
45                 })
46
47         # XXX _sort_formats fails if there are not formats, while it's not the
48         # desired behavior if 'IPDeny' is ignored
49         # This check can be removed if https://github.com/rg3/youtube-dl/pull/8051 is merged
50         if not tolerate_ip_deny:
51             self._sort_formats(formats)
52         return formats
53
54
55 class KuwoIE(KuwoBaseIE):
56     IE_NAME = 'kuwo:song'
57     IE_DESC = '酷我音乐'
58     _VALID_URL = r'http://www\.kuwo\.cn/yinyue/(?P<id>\d+?)'
59     _TESTS = [{
60         'url': 'http://www.kuwo.cn/yinyue/635632/',
61         'info_dict': {
62             'id': '635632',
63             'ext': 'ape',
64             'title': '爱我别走',
65             'creator': '张震岳',
66             'upload_date': '20080122',
67             'description': 'md5:ed13f58e3c3bf3f7fd9fbc4e5a7aa75c'
68         },
69         'skip': 'this song has been offline because of copyright issues',
70     }, {
71         'url': 'http://www.kuwo.cn/yinyue/6446136/',
72         'info_dict': {
73             'id': '6446136',
74             'ext': 'mp3',
75             'title': '心',
76             'description': 'md5:b2ab6295d014005bfc607525bfc1e38a',
77             'creator': 'IU',
78             'upload_date': '20150518',
79         },
80         'params': {
81             'format': 'mp3-320'
82         },
83     }, {
84         'url': 'http://www.kuwo.cn/yinyue/3197154?catalog=yueku2016',
85         'only_matching': True,
86     }]
87
88     def _real_extract(self, url):
89         song_id = self._match_id(url)
90         webpage = self._download_webpage(
91             url, song_id, note='Download song detail info',
92             errnote='Unable to get song detail info')
93         if '对不起,该歌曲由于版权问题已被下线,将返回网站首页' in webpage:
94             raise ExtractorError('this song has been offline because of copyright issues', expected=True)
95
96         song_name = self._html_search_regex(
97             r'(?s)class="(?:[^"\s]+\s+)*title(?:\s+[^"\s]+)*".*?<h1[^>]+title="([^"]+)"', webpage, 'song name')
98         singer_name = self._html_search_regex(
99             r'<div[^>]+class="s_img">\s*<a[^>]+title="([^>]+)"',
100             webpage, 'singer name', fatal=False)
101         lrc_content = clean_html(get_element_by_id('lrcContent', webpage))
102         if lrc_content == '暂无':     # indicates no lyrics
103             lrc_content = None
104
105         formats = self._get_formats(song_id)
106
107         album_id = self._html_search_regex(
108             r'<p[^>]+class="album"[^<]+<a[^>]+href="http://www\.kuwo\.cn/album/(\d+)/"',
109             webpage, 'album id', fatal=False)
110
111         publish_time = None
112         if album_id is not None:
113             album_info_page = self._download_webpage(
114                 'http://www.kuwo.cn/album/%s/' % album_id, song_id,
115                 note='Download album detail info',
116                 errnote='Unable to get album detail info')
117
118             publish_time = self._html_search_regex(
119                 r'发行时间:(\d{4}-\d{2}-\d{2})', album_info_page,
120                 'publish time', fatal=False)
121             if publish_time:
122                 publish_time = publish_time.replace('-', '')
123
124         return {
125             'id': song_id,
126             'title': song_name,
127             'creator': singer_name,
128             'upload_date': publish_time,
129             'description': lrc_content,
130             'formats': formats,
131         }
132
133
134 class KuwoAlbumIE(InfoExtractor):
135     IE_NAME = 'kuwo:album'
136     IE_DESC = '酷我音乐 - 专辑'
137     _VALID_URL = r'http://www\.kuwo\.cn/album/(?P<id>\d+?)/'
138     _TEST = {
139         'url': 'http://www.kuwo.cn/album/502294/',
140         'info_dict': {
141             'id': '502294',
142             'title': 'M',
143             'description': 'md5:6a7235a84cc6400ec3b38a7bdaf1d60c',
144         },
145         'playlist_count': 2,
146     }
147
148     def _real_extract(self, url):
149         album_id = self._match_id(url)
150
151         webpage = self._download_webpage(
152             url, album_id, note='Download album info',
153             errnote='Unable to get album info')
154
155         album_name = self._html_search_regex(
156             r'<div[^>]+class="comm"[^<]+<h1[^>]+title="([^"]+)"', webpage,
157             'album name')
158         album_intro = remove_start(
159             clean_html(get_element_by_id('intro', webpage)),
160             '%s简介:' % album_name)
161
162         entries = [
163             self.url_result(song_url, 'Kuwo') for song_url in re.findall(
164                 r'<p[^>]+class="listen"><a[^>]+href="(http://www\.kuwo\.cn/yinyue/\d+/)"',
165                 webpage)
166         ]
167         return self.playlist_result(entries, album_id, album_name, album_intro)
168
169
170 class KuwoChartIE(InfoExtractor):
171     IE_NAME = 'kuwo:chart'
172     IE_DESC = '酷我音乐 - 排行榜'
173     _VALID_URL = r'http://yinyue\.kuwo\.cn/billboard_(?P<id>[^.]+).htm'
174     _TEST = {
175         'url': 'http://yinyue.kuwo.cn/billboard_香港中文龙虎榜.htm',
176         'info_dict': {
177             'id': '香港中文龙虎榜',
178         },
179         'playlist_mincount': 10,
180     }
181
182     def _real_extract(self, url):
183         chart_id = self._match_id(url)
184         webpage = self._download_webpage(
185             url, chart_id, note='Download chart info',
186             errnote='Unable to get chart info')
187
188         entries = [
189             self.url_result(song_url, 'Kuwo') for song_url in re.findall(
190                 r'<a[^>]+href="(http://www\.kuwo\.cn/yinyue/\d+)', webpage)
191         ]
192         return self.playlist_result(entries, chart_id)
193
194
195 class KuwoSingerIE(InfoExtractor):
196     IE_NAME = 'kuwo:singer'
197     IE_DESC = '酷我音乐 - 歌手'
198     _VALID_URL = r'http://www\.kuwo\.cn/mingxing/(?P<id>[^/]+)'
199     _TESTS = [{
200         'url': 'http://www.kuwo.cn/mingxing/bruno+mars/',
201         'info_dict': {
202             'id': 'bruno+mars',
203             'title': 'Bruno Mars',
204         },
205         'playlist_mincount': 329,
206     }, {
207         'url': 'http://www.kuwo.cn/mingxing/Ali/music.htm',
208         'info_dict': {
209             'id': 'Ali',
210             'title': 'Ali',
211         },
212         'playlist_mincount': 95,
213         'skip': 'Regularly stalls travis build',  # See https://travis-ci.org/rg3/youtube-dl/jobs/78878540
214     }]
215
216     PAGE_SIZE = 15
217
218     def _real_extract(self, url):
219         singer_id = self._match_id(url)
220         webpage = self._download_webpage(
221             url, singer_id, note='Download singer info',
222             errnote='Unable to get singer info')
223
224         singer_name = self._html_search_regex(
225             r'<h1>([^<]+)</h1>', webpage, 'singer name')
226
227         artist_id = self._html_search_regex(
228             r'data-artistid="(\d+)"', webpage, 'artist id')
229
230         page_count = int(self._html_search_regex(
231             r'data-page="(\d+)"', webpage, 'page count'))
232
233         def page_func(page_num):
234             webpage = self._download_webpage(
235                 'http://www.kuwo.cn/artist/contentMusicsAjax',
236                 singer_id, note='Download song list page #%d' % (page_num + 1),
237                 errnote='Unable to get song list page #%d' % (page_num + 1),
238                 query={'artistId': artist_id, 'pn': page_num, 'rn': self.PAGE_SIZE})
239
240             return [
241                 self.url_result(song_url, 'Kuwo') for song_url in re.findall(
242                     r'<div[^>]+class="name"><a[^>]+href="(http://www\.kuwo\.cn/yinyue/\d+)',
243                     webpage)
244             ]
245
246         entries = InAdvancePagedList(page_func, page_count, self.PAGE_SIZE)
247
248         return self.playlist_result(entries, singer_id, singer_name)
249
250
251 class KuwoCategoryIE(InfoExtractor):
252     IE_NAME = 'kuwo:category'
253     IE_DESC = '酷我音乐 - 分类'
254     _VALID_URL = r'http://yinyue\.kuwo\.cn/yy/cinfo_(?P<id>\d+?).htm'
255     _TEST = {
256         'url': 'http://yinyue.kuwo.cn/yy/cinfo_86375.htm',
257         'info_dict': {
258             'id': '86375',
259             'title': '八十年代精选',
260             'description': '这些都是属于八十年代的回忆!',
261         },
262         'playlist_count': 30,
263     }
264
265     def _real_extract(self, url):
266         category_id = self._match_id(url)
267         webpage = self._download_webpage(
268             url, category_id, note='Download category info',
269             errnote='Unable to get category info')
270
271         category_name = self._html_search_regex(
272             r'<h1[^>]+title="([^<>]+?)">[^<>]+?</h1>', webpage, 'category name')
273
274         category_desc = remove_start(
275             get_element_by_id('intro', webpage).strip(),
276             '%s简介:' % category_name)
277
278         jsonm = self._parse_json(self._html_search_regex(
279             r'var\s+jsonm\s*=\s*([^;]+);', webpage, 'category songs'), category_id)
280
281         entries = [
282             self.url_result('http://www.kuwo.cn/yinyue/%s/' % song['musicrid'], 'Kuwo')
283             for song in jsonm['musiclist']
284         ]
285         return self.playlist_result(entries, category_id, category_name, category_desc)
286
287
288 class KuwoMvIE(KuwoBaseIE):
289     IE_NAME = 'kuwo:mv'
290     IE_DESC = '酷我音乐 - MV'
291     _VALID_URL = r'http://www\.kuwo\.cn/mv/(?P<id>\d+?)/'
292     _TEST = {
293         'url': 'http://www.kuwo.cn/mv/6480076/',
294         'info_dict': {
295             'id': '6480076',
296             'ext': 'mp4',
297             'title': 'My HouseMV',
298             'creator': '2PM',
299         },
300         # In this video, music URLs (anti.s) are blocked outside China and
301         # USA, while the MV URL (mvurl) is available globally, so force the MV
302         # URL for consistent results in different countries
303         'params': {
304             'format': 'mv',
305         },
306     }
307     _FORMATS = KuwoBaseIE._FORMATS + [
308         {'format': 'mkv', 'ext': 'mkv', 'preference': 250},
309         {'format': 'mp4', 'ext': 'mp4', 'preference': 200},
310     ]
311
312     def _real_extract(self, url):
313         song_id = self._match_id(url)
314         webpage = self._download_webpage(
315             url, song_id, note='Download mv detail info: %s' % song_id,
316             errnote='Unable to get mv detail info: %s' % song_id)
317
318         mobj = re.search(
319             r'<h1[^>]+title="(?P<song>[^"]+)">[^<]+<span[^>]+title="(?P<singer>[^"]+)"',
320             webpage)
321         if mobj:
322             song_name = mobj.group('song')
323             singer_name = mobj.group('singer')
324         else:
325             raise ExtractorError('Unable to find song or singer names')
326
327         formats = self._get_formats(song_id, tolerate_ip_deny=True)
328
329         mv_url = self._download_webpage(
330             'http://www.kuwo.cn/yy/st/mvurl?rid=MUSIC_%s' % song_id,
331             song_id, note='Download %s MV URL' % song_id)
332         formats.append({
333             'url': mv_url,
334             'format_id': 'mv',
335         })
336
337         self._sort_formats(formats)
338
339         return {
340             'id': song_id,
341             'title': song_name,
342             'creator': singer_name,
343             'formats': formats,
344         }