[neteasemusic] Do proper rounding conversion of millisecond timestamps/durations
[youtube-dl] / youtube_dl / extractor / neteasemusic.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 from hashlib import md5
5 from datetime import datetime
6 import itertools
7 import re
8
9 from .common import InfoExtractor
10 from ..compat import (
11     compat_urllib_request,
12     compat_urllib_parse,
13 )
14
15
16 class NetEaseMusicBaseIE(InfoExtractor):
17     _FORMATS = ['bMusic', 'mMusic', 'hMusic']
18     _NETEASE_SALT = '3go8&$8*3*3h0k(2)2'
19     _API_BASE = 'http://music.163.com/api/'
20
21     @classmethod
22     def _encrypt(cls, dfsid):
23         salt_bytes = bytearray(str(cls._NETEASE_SALT))
24         string_bytes = bytearray(str(dfsid))
25         salt_len = len(salt_bytes)
26         for i in xrange(len(string_bytes)):
27             string_bytes[i] = string_bytes[i] ^ salt_bytes[i % salt_len]
28         m = md5()
29         m.update(string_bytes)
30         result = m.digest().encode('base64')[:-1]
31         return result.replace('/', '_').replace('+', '-')
32
33     @classmethod
34     def extract_formats(cls, info):
35         formats = []
36         for song_format in cls._FORMATS:
37             details = info.get(song_format)
38             if not details:
39                 continue
40             formats.append({
41                 'url': 'http://m1.music.126.net/%s/%s.%s' %
42                        (cls._encrypt(details['dfsId']), details['dfsId'],
43                         details['extension']),
44                 'ext': details['extension'],
45                 'abr': details['bitrate'] / 1000,
46                 'preference': details['bitrate'],
47                 'format_id': song_format,
48                 'filesize': details['size'],
49                 'asr': details['sr']
50             })
51         return formats
52
53     @classmethod
54     def convert_milliseconds(cls, ms):
55         return int(round(ms/1000.0))
56
57     def query_api(self, endpoint, video_id, note):
58         req = compat_urllib_request.Request('%s%s' % (self._API_BASE, endpoint))
59         req.add_header('Referer', self._API_BASE)
60         return self._download_json(req, video_id, note)
61
62
63 class NetEaseMusicIE(NetEaseMusicBaseIE):
64     IE_NAME = 'netease:song'
65     _VALID_URL = r'https?://music\.163\.com/(#/)?song\?id=(?P<id>[0-9]+)'
66     _TESTS = [{
67         'url': 'http://music.163.com/#/song?id=32102397',
68         'md5': 'f2e97280e6345c74ba9d5677dd5dcb45',
69         'info_dict': {
70             'id': '32102397',
71             'ext': 'mp3',
72             'title': 'Bad Blood (feat. Kendrick Lamar)',
73             'creator': 'Taylor Swift / Kendrick Lamar',
74             'upload_date': '20150517',
75             'timestamp': 1431878400,
76             'description': 'md5:a10a54589c2860300d02e1de821eb2ef',
77         },
78     }, {
79         'note': 'No lyrics translation.',
80         'url': 'http://music.163.com/#/song?id=29822014',
81         'info_dict': {
82             'id': '29822014',
83             'ext': 'mp3',
84             'title': '听见下雨的声音',
85             'creator': '周杰伦',
86             'upload_date': '20141225',
87             'timestamp': 1419523200,
88             'description': 'md5:a4d8d89f44656af206b7b2555c0bce6c',
89         },
90     }, {
91         'note': 'No lyrics.',
92         'url': 'http://music.163.com/song?id=17241424',
93         'info_dict': {
94             'id': '17241424',
95             'ext': 'mp3',
96             'title': 'Opus 28',
97             'creator': 'Dustin O\'Halloran',
98             'upload_date': '20080211',
99             'timestamp': 1202745600,
100         },
101     }]
102
103     def _process_lyrics(self, lyrics_info):
104         original = lyrics_info.get('lrc', {}).get('lyric')
105         translated = lyrics_info.get('tlyric', {}).get('lyric')
106
107         if not translated:
108             return original
109
110         lyrics_expr = r'(\[[0-9]{2}:[0-9]{2}\.[0-9]{2,}\])([^\n]+)'
111         original_ts_texts = re.findall(lyrics_expr, original)
112         translation_ts_dict = {
113             time_stamp: text for time_stamp, text in re.findall(lyrics_expr, translated)
114         }
115
116         lyrics = '\n'.join([
117             '%s%s / %s' % (time_stamp, text, translation_ts_dict.get(time_stamp, ''))
118             for time_stamp, text in original_ts_texts
119         ])
120         return lyrics
121
122     def _real_extract(self, url):
123         song_id = self._match_id(url)
124
125         params = {
126             'id': song_id,
127             'ids': '[%s]' % song_id
128         }
129         info = self.query_api(
130             'song/detail?' + compat_urllib_parse.urlencode(params),
131             song_id, 'Downloading song info')['songs'][0]
132
133         formats = self.extract_formats(info)
134         self._sort_formats(formats)
135
136         lyrics_info = self.query_api(
137             'song/lyric?id=%s&lv=-1&tv=-1' % song_id, 
138             song_id, 'Downloading lyrics data')
139         lyrics = self._process_lyrics(lyrics_info)
140
141         alt_title = None
142         if info.get('alias'):
143             alt_title = '/'.join(info.get('alias'))
144
145         return {
146             'id': song_id,
147             'title': info['name'],
148             'alt_title': alt_title,
149             'creator': ' / '.join([artist['name'] for artist in info.get('artists', [])]),
150             'timestamp': self.convert_milliseconds(info.get('album', {}).get('publishTime')),
151             'thumbnail': info.get('album', {}).get('picUrl'),
152             'duration': self.convert_milliseconds(info.get('duration', 0)),
153             'description': lyrics,
154             'formats': formats,
155         }
156
157
158 class NetEaseMusicAlbumIE(NetEaseMusicBaseIE):
159     IE_NAME = 'netease:album'
160     _VALID_URL = r'https?://music\.163\.com/(#/)?album\?id=(?P<id>[0-9]+)'
161     _TEST = {
162         'url': 'http://music.163.com/#/album?id=220780',
163         'info_dict': {
164             'id': '220780',
165             'title': 'B\'day',
166         },
167         'playlist_count': 23,
168     }
169
170     def _real_extract(self, url):
171         album_id = self._match_id(url)
172
173         info = self.query_api(
174             'album/%s?id=%s' % (album_id, album_id), 
175             album_id, 'Downloading album data')['album']
176
177         name = info['name']
178         desc = info.get('description')
179         entries = [
180             self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
181                             'NetEaseMusic', song['id'])
182             for song in info['songs']
183         ]
184         return self.playlist_result(entries, album_id, name, desc)
185
186
187 class NetEaseMusicSingerIE(NetEaseMusicBaseIE):
188     IE_NAME = 'netease:singer'
189     _VALID_URL = r'https?://music\.163\.com/(#/)?artist\?id=(?P<id>[0-9]+)'
190     _TESTS = [{
191         'note': 'Singer has aliases.',
192         'url': 'http://music.163.com/#/artist?id=10559',
193         'info_dict': {
194             'id': '10559',
195             'title': '张惠妹 - aMEI;阿密特',
196         },
197         'playlist_count': 50,
198     }, {
199         'note': 'Singer has translated name.',
200         'url': 'http://music.163.com/#/artist?id=124098',
201         'info_dict': {
202             'id': '124098',
203             'title': '李昇基 - 이승기',
204         },
205         'playlist_count': 50,
206     }]
207
208     def _real_extract(self, url):
209         singer_id = self._match_id(url)
210
211         info = self.query_api(
212             'artist/%s?id=%s' % (singer_id, singer_id), 
213             singer_id, 'Downloading singer data')
214
215         name = info['artist']['name']
216         if info['artist']['trans']:
217             name = '%s - %s' % (name, info['artist']['trans'])
218         if info['artist']['alias']:
219             name = '%s - %s' % (name, ";".join(info['artist']['alias']))
220
221         entries = [
222             self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
223                             'NetEaseMusic', song['id'])
224             for song in info['hotSongs']
225         ]
226         return self.playlist_result(entries, singer_id, name)
227
228
229 class NetEaseMusicListIE(NetEaseMusicBaseIE):
230     IE_NAME = 'netease:playlist'
231     _VALID_URL = r'https?://music\.163\.com/(#/)?(playlist|discover/toplist)\?id=(?P<id>[0-9]+)'
232     _TESTS = [{
233         'url': 'http://music.163.com/#/playlist?id=79177352',
234         'info_dict': {
235             'id': '79177352',
236             'title': 'Billboard 2007 Top 100',
237             'description': 'md5:12fd0819cab2965b9583ace0f8b7b022'
238         },
239         'playlist_count': 99,
240     }, {
241         'note': 'Toplist/Charts sample',
242         'url': 'http://music.163.com/#/discover/toplist?id=3733003',
243         'info_dict': {
244             'id': '3733003',
245             'title': 're:韩国Melon排行榜周榜 [0-9]{4}-[0-9]{2}-[0-9]{2}',
246             'description': 'md5:73ec782a612711cadc7872d9c1e134fc',
247         },
248         'playlist_count': 50,
249     }]
250
251     def _real_extract(self, url):
252         list_id = self._match_id(url)
253
254         info = self.query_api(
255             'playlist/detail?id=%s&lv=-1&tv=-1' % list_id, 
256             list_id, 'Downloading playlist data')['result']
257
258         name = info['name']
259         desc = info.get('description')
260
261         if info.get('specialType') == 10:  # is a chart/toplist
262             datestamp = datetime.fromtimestamp(
263                 self.convert_milliseconds(info['updateTime'])).strftime('%Y-%m-%d')
264             name = '%s %s' % (name, datestamp)
265
266         entries = [
267             self.url_result('http://music.163.com/#/song?id=%s' % song['id'],
268                             'NetEaseMusic', song['id'])
269             for song in info['tracks']
270         ]
271         return self.playlist_result(entries, list_id, name, desc)
272
273
274 class NetEaseMusicMvIE(NetEaseMusicBaseIE):
275     IE_NAME = 'netease:mv'
276     _VALID_URL = r'https?://music\.163\.com/(#/)?mv\?id=(?P<id>[0-9]+)'
277     _TEST = {
278         'url': 'http://music.163.com/#/mv?id=415350',
279         'info_dict': {
280             'id': '415350',
281             'ext': 'mp4',
282             'title': '이럴거면 그러지말지',
283             'description': '白雅言自作曲唱甜蜜爱情',
284             'creator': '白雅言',
285             'upload_date': '20150520',
286         },
287     }
288
289     def _real_extract(self, url):
290         mv_id = self._match_id(url)
291
292         info = self.query_api(
293             'mv/detail?id=%s&type=mp4' % mv_id,
294             mv_id, 'Downloading mv info')['data']
295
296         formats = [
297             {'url': mv_url, 'ext': 'mp4', 'format_id': '%sp' % brs, 'preference': int(brs)}
298             for brs, mv_url in info['brs'].items()
299         ]
300         self._sort_formats(formats)
301
302         return {
303             'id': mv_id,
304             'title': info['name'],
305             'description': info.get('desc') or info.get('briefDesc'),
306             'creator': info['artistName'],
307             'upload_date': info['publishTime'].replace('-', ''),
308             'formats': formats,
309             'thumbnail': info.get('cover'),
310             'duration': self.convert_milliseconds(info.get('duration', 0)),
311         }
312
313
314 class NetEaseMusicProgramIE(NetEaseMusicBaseIE):
315     IE_NAME = 'netease:program'
316     _VALID_URL = r'https?://music\.163\.com/(#/?)program\?id=(?P<id>[0-9]+)'
317     _TESTS = [{
318         'url': 'http://music.163.com/#/program?id=10109055',
319         'info_dict': {
320             'id': '10109055',
321             'ext': 'mp3',
322             'title': '不丹足球背后的故事',
323             'description': '喜马拉雅人的足球梦 ...',
324             'creator': '大话西藏',
325             'timestamp': 1434179342,
326             'upload_date': '20150613',
327             'duration': 900,
328         },
329     }, {
330         'note': 'This program has accompanying songs.',
331         'url': 'http://music.163.com/#/program?id=10141022',
332         'info_dict': {
333             'id': '10141022',
334             'title': '25岁,你是自在如风的少年<27°C>',
335             'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
336         },
337         'playlist_count': 4,
338     }, {
339         'note': 'This program has accompanying songs.',
340         'url': 'http://music.163.com/#/program?id=10141022',
341         'info_dict': {
342             'id': '10141022',
343             'ext': 'mp3',
344             'title': '25岁,你是自在如风的少年<27°C>',
345             'description': 'md5:8d594db46cc3e6509107ede70a4aaa3b',
346             'timestamp': 1434450841,
347             'upload_date': '20150616',
348         },
349         'params': {
350             'noplaylist': True
351         }
352     }]
353
354     def _real_extract(self, url):
355         program_id = self._match_id(url)
356
357         info = self.query_api(
358             'dj/program/detail?id=%s' % program_id,
359             program_id, 'Downloading program info')['program']
360
361         name = info['name']
362         description = info['description']
363
364         if not info['songs'] or self._downloader.params.get('noplaylist'):
365             if info['songs']:
366                 self.to_screen(
367                     'Downloading just the main audio %s because of --no-playlist'
368                     % info['mainSong']['id'])
369             
370             formats = self.extract_formats(info['mainSong'])
371             self._sort_formats(formats)
372
373             return {
374                 'id': program_id,
375                 'title': name,
376                 'description': description,
377                 'creator': info['dj']['brand'],
378                 'timestamp': self.convert_milliseconds(info['createTime']),
379                 'thumbnail': info['coverUrl'],
380                 'duration': self.convert_milliseconds(info.get('duration', 0)),
381                 'formats': formats,
382             }
383
384         self.to_screen(
385             'Downloading playlist %s - add --no-playlist to just download the main audio %s'
386             % (program_id, info['mainSong']['id']))
387
388         song_ids = [info['mainSong']['id']]
389         song_ids.extend([song['id'] for song in info['songs']])
390         entries = [
391             self.url_result('http://music.163.com/#/song?id=%s' % song_id,
392                             'NetEaseMusic', song_id)
393             for song_id in song_ids
394         ]
395         return self.playlist_result(entries, program_id, name, description)
396
397
398 class NetEaseMusicDjRadioIE(NetEaseMusicBaseIE):
399     IE_NAME = 'netease:djradio'
400     _VALID_URL = r'https?://music\.163\.com/(#/)?djradio\?id=(?P<id>[0-9]+)'
401     _TEST = {
402         'url': 'http://music.163.com/#/djradio?id=42',
403         'info_dict': {
404             'id': '42',
405             'title': '声音蔓延',
406             'description': 'md5:766220985cbd16fdd552f64c578a6b15'
407         },
408         'playlist_mincount': 40,
409     }
410     _PAGE_SIZE = 1000
411
412     def _real_extract(self, url):
413         dj_id = self._match_id(url)
414
415         name = None
416         desc = None
417         entries = []
418         for offset in itertools.count(start=0, step=self._PAGE_SIZE):
419             info = self.query_api(
420                 'dj/program/byradio?asc=false&limit=%d&radioId=%s&offset=%d' 
421                 % (self._PAGE_SIZE, dj_id, offset),
422                 dj_id, 'Downloading dj programs - %d' % offset)
423
424             entries.extend([
425                 self.url_result(
426                     'http://music.163.com/#/program?id=%s' % program['id'],
427                     'NetEaseMusicProgram', program['id'])
428                 for program in info['programs']
429             ])
430
431             if name is None:
432                 radio = info['programs'][0]['radio']
433                 name = radio['name']
434                 desc = radio['desc']
435
436             if not info['more']:
437                 break
438
439         return self.playlist_result(entries, dj_id, name, desc)