Merge pull request #8092 from bpfoley/twitter-thumbnail
[youtube-dl] / youtube_dl / extractor / kuwo.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import itertools
6
7 from .common import InfoExtractor
8 from ..utils import (
9     get_element_by_id,
10     clean_html,
11     ExtractorError,
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
85     def _real_extract(self, url):
86         song_id = self._match_id(url)
87         webpage = self._download_webpage(
88             url, song_id, note='Download song detail info',
89             errnote='Unable to get song detail info')
90         if '对不起,该歌曲由于版权问题已被下线,将返回网站首页' in webpage:
91             raise ExtractorError('this song has been offline because of copyright issues', expected=True)
92
93         song_name = self._html_search_regex(
94             r'(?s)class="(?:[^"\s]+\s+)*title(?:\s+[^"\s]+)*".*?<h1[^>]+title="([^"]+)"', webpage, 'song name')
95         singer_name = self._html_search_regex(
96             r'<div[^>]+class="s_img">\s*<a[^>]+title="([^>]+)"',
97             webpage, 'singer name', fatal=False)
98         lrc_content = clean_html(get_element_by_id('lrcContent', webpage))
99         if lrc_content == '暂无':     # indicates no lyrics
100             lrc_content = None
101
102         formats = self._get_formats(song_id)
103
104         album_id = self._html_search_regex(
105             r'<p[^>]+class="album"[^<]+<a[^>]+href="http://www\.kuwo\.cn/album/(\d+)/"',
106             webpage, 'album id', fatal=False)
107
108         publish_time = None
109         if album_id is not None:
110             album_info_page = self._download_webpage(
111                 'http://www.kuwo.cn/album/%s/' % album_id, song_id,
112                 note='Download album detail info',
113                 errnote='Unable to get album detail info')
114
115             publish_time = self._html_search_regex(
116                 r'发行时间:(\d{4}-\d{2}-\d{2})', album_info_page,
117                 'publish time', fatal=False)
118             if publish_time:
119                 publish_time = publish_time.replace('-', '')
120
121         return {
122             'id': song_id,
123             'title': song_name,
124             'creator': singer_name,
125             'upload_date': publish_time,
126             'description': lrc_content,
127             'formats': formats,
128         }
129
130
131 class KuwoAlbumIE(InfoExtractor):
132     IE_NAME = 'kuwo:album'
133     IE_DESC = '酷我音乐 - 专辑'
134     _VALID_URL = r'http://www\.kuwo\.cn/album/(?P<id>\d+?)/'
135     _TEST = {
136         'url': 'http://www.kuwo.cn/album/502294/',
137         'info_dict': {
138             'id': '502294',
139             'title': 'M',
140             'description': 'md5:6a7235a84cc6400ec3b38a7bdaf1d60c',
141         },
142         'playlist_count': 2,
143     }
144
145     def _real_extract(self, url):
146         album_id = self._match_id(url)
147
148         webpage = self._download_webpage(
149             url, album_id, note='Download album info',
150             errnote='Unable to get album info')
151
152         album_name = self._html_search_regex(
153             r'<div[^>]+class="comm"[^<]+<h1[^>]+title="([^"]+)"', webpage,
154             'album name')
155         album_intro = remove_start(
156             clean_html(get_element_by_id('intro', webpage)),
157             '%s简介:' % album_name)
158
159         entries = [
160             self.url_result(song_url, 'Kuwo') for song_url in re.findall(
161                 r'<p[^>]+class="listen"><a[^>]+href="(http://www\.kuwo\.cn/yinyue/\d+/)"',
162                 webpage)
163         ]
164         return self.playlist_result(entries, album_id, album_name, album_intro)
165
166
167 class KuwoChartIE(InfoExtractor):
168     IE_NAME = 'kuwo:chart'
169     IE_DESC = '酷我音乐 - 排行榜'
170     _VALID_URL = r'http://yinyue\.kuwo\.cn/billboard_(?P<id>[^.]+).htm'
171     _TEST = {
172         'url': 'http://yinyue.kuwo.cn/billboard_香港中文龙虎榜.htm',
173         'info_dict': {
174             'id': '香港中文龙虎榜',
175             'title': '香港中文龙虎榜',
176             'description': 're:\d{4}第\d{2}期',
177         },
178         'playlist_mincount': 10,
179     }
180
181     def _real_extract(self, url):
182         chart_id = self._match_id(url)
183         webpage = self._download_webpage(
184             url, chart_id, note='Download chart info',
185             errnote='Unable to get chart info')
186
187         chart_name = self._html_search_regex(
188             r'<h1[^>]+class="unDis">([^<]+)</h1>', webpage, 'chart name')
189
190         chart_desc = self._html_search_regex(
191             r'<p[^>]+class="tabDef">(\d{4}第\d{2}期)</p>', webpage, 'chart desc')
192
193         entries = [
194             self.url_result(song_url, 'Kuwo') for song_url in re.findall(
195                 r'<a[^>]+href="(http://www\.kuwo\.cn/yinyue/\d+)/"', webpage)
196         ]
197         return self.playlist_result(entries, chart_id, chart_name, chart_desc)
198
199
200 class KuwoSingerIE(InfoExtractor):
201     IE_NAME = 'kuwo:singer'
202     IE_DESC = '酷我音乐 - 歌手'
203     _VALID_URL = r'http://www\.kuwo\.cn/mingxing/(?P<id>[^/]+)'
204     _TESTS = [{
205         'url': 'http://www.kuwo.cn/mingxing/bruno+mars/',
206         'info_dict': {
207             'id': 'bruno+mars',
208             'title': 'Bruno Mars',
209         },
210         'playlist_count': 10,
211     }, {
212         'url': 'http://www.kuwo.cn/mingxing/Ali/music.htm',
213         'info_dict': {
214             'id': 'Ali',
215             'title': 'Ali',
216         },
217         'playlist_mincount': 95,
218         'skip': 'Regularly stalls travis build',  # See https://travis-ci.org/rg3/youtube-dl/jobs/78878540
219     }]
220
221     def _real_extract(self, url):
222         singer_id = self._match_id(url)
223         webpage = self._download_webpage(
224             url, singer_id, note='Download singer info',
225             errnote='Unable to get singer info')
226
227         singer_name = self._html_search_regex(
228             r'<div class="title clearfix">\s*<h1>([^<]+)<span', webpage, 'singer name'
229         )
230
231         entries = []
232         first_page_only = False if re.search(r'/music(?:_\d+)?\.htm', url) else True
233         for page_num in itertools.count(1):
234             webpage = self._download_webpage(
235                 'http://www.kuwo.cn/mingxing/%s/music_%d.htm' % (singer_id, page_num),
236                 singer_id, note='Download song list page #%d' % page_num,
237                 errnote='Unable to get song list page #%d' % page_num)
238
239             entries.extend([
240                 self.url_result(song_url, 'Kuwo') for song_url in re.findall(
241                     r'<p[^>]+class="m_name"><a[^>]+href="(http://www\.kuwo\.cn/yinyue/\d+)/',
242                     webpage)
243             ][:10 if first_page_only else None])
244
245             if first_page_only or not re.search(r'<a[^>]+href="[^"]+">下一页</a>', webpage):
246                 break
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         }