Merge remote-tracking branch 'ralfharing/vh1'
[youtube-dl] / youtube_dl / extractor / soundcloud.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import json
5 import re
6 import itertools
7
8 from .common import InfoExtractor
9 from ..utils import (
10     compat_str,
11     compat_urlparse,
12     compat_urllib_parse,
13
14     ExtractorError,
15     int_or_none,
16     unified_strdate,
17 )
18
19
20 class SoundcloudIE(InfoExtractor):
21     """Information extractor for soundcloud.com
22        To access the media, the uid of the song and a stream token
23        must be extracted from the page source and the script must make
24        a request to media.soundcloud.com/crossdomain.xml. Then
25        the media can be grabbed by requesting from an url composed
26        of the stream token and uid
27      """
28
29     _VALID_URL = r'''(?x)^(?:https?://)?
30                     (?:(?:(?:www\.|m\.)?soundcloud\.com/
31                             (?P<uploader>[\w\d-]+)/
32                             (?!sets/)(?P<title>[\w\d-]+)/?
33                             (?P<token>[^?]+?)?(?:[?].*)?$)
34                        |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+))
35                        |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
36                     )
37                     '''
38     IE_NAME = 'soundcloud'
39     _TESTS = [
40         {
41             'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
42             'file': '62986583.mp3',
43             'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
44             'info_dict': {
45                 "upload_date": "20121011",
46                 "description": "No Downloads untill we record the finished version this weekend, i was too pumped n i had to post it , earl is prolly gonna b hella p.o'd",
47                 "uploader": "E.T. ExTerrestrial Music",
48                 "title": "Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1",
49                 "duration": 143,
50             }
51         },
52         # not streamable song
53         {
54             'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
55             'info_dict': {
56                 'id': '47127627',
57                 'ext': 'mp3',
58                 'title': 'Goldrushed',
59                 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
60                 'uploader': 'The Royal Concept',
61                 'upload_date': '20120521',
62                 'duration': 227,
63             },
64             'params': {
65                 # rtmp
66                 'skip_download': True,
67             },
68         },
69         # private link
70         {
71             'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
72             'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
73             'info_dict': {
74                 'id': '123998367',
75                 'ext': 'mp3',
76                 'title': 'Youtube - Dl Test Video \'\' Ä↭',
77                 'uploader': 'jaimeMF',
78                 'description': 'test chars:  \"\'/\\ä↭',
79                 'upload_date': '20131209',
80                 'duration': 9,
81             },
82         },
83         # downloadable song
84         {
85             'url': 'https://soundcloud.com/simgretina/just-your-problem-baby-1',
86             'md5': '56a8b69568acaa967b4c49f9d1d52d19',
87             'info_dict': {
88                 'id': '105614606',
89                 'ext': 'wav',
90                 'title': 'Just Your Problem Baby (Acapella)',
91                 'description': 'Vocals',
92                 'uploader': 'Sim Gretina',
93                 'upload_date': '20130815',
94                 #'duration': 42,
95             },
96         },
97     ]
98
99     _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
100     _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
101
102     def report_resolve(self, video_id):
103         """Report information extraction."""
104         self.to_screen('%s: Resolving id' % video_id)
105
106     @classmethod
107     def _resolv_url(cls, url):
108         return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
109
110     def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
111         track_id = compat_str(info['id'])
112         name = full_title or track_id
113         if quiet:
114             self.report_extraction(name)
115
116         thumbnail = info['artwork_url']
117         if thumbnail is not None:
118             thumbnail = thumbnail.replace('-large', '-t500x500')
119         ext = 'mp3'
120         result = {
121             'id': track_id,
122             'uploader': info['user']['username'],
123             'upload_date': unified_strdate(info['created_at']),
124             'title': info['title'],
125             'description': info['description'],
126             'thumbnail': thumbnail,
127             'duration': int_or_none(info.get('duration'), 1000),
128         }
129         formats = []
130         if info.get('downloadable', False):
131             # We can build a direct link to the song
132             format_url = (
133                 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
134                     track_id, self._CLIENT_ID))
135             formats.append({
136                 'format_id': 'download',
137                 'ext': info.get('original_format', 'mp3'),
138                 'url': format_url,
139                 'vcodec': 'none',
140                 'preference': 10,
141             })
142
143         # We have to retrieve the url
144         streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
145             'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
146         format_dict = self._download_json(
147             streams_url,
148             track_id, 'Downloading track url')
149
150         for key, stream_url in format_dict.items():
151             if key.startswith('http'):
152                 formats.append({
153                     'format_id': key,
154                     'ext': ext,
155                     'url': stream_url,
156                     'vcodec': 'none',
157                 })
158             elif key.startswith('rtmp'):
159                 # The url doesn't have an rtmp app, we have to extract the playpath
160                 url, path = stream_url.split('mp3:', 1)
161                 formats.append({
162                     'format_id': key,
163                     'url': url,
164                     'play_path': 'mp3:' + path,
165                     'ext': ext,
166                     'vcodec': 'none',
167                 })
168
169             if not formats:
170                 # We fallback to the stream_url in the original info, this
171                 # cannot be always used, sometimes it can give an HTTP 404 error
172                 formats.append({
173                     'format_id': 'fallback',
174                     'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
175                     'ext': ext,
176                     'vcodec': 'none',
177                 })
178
179             for f in formats:
180                 if f['format_id'].startswith('http'):
181                     f['protocol'] = 'http'
182                 if f['format_id'].startswith('rtmp'):
183                     f['protocol'] = 'rtmp'
184
185             self._sort_formats(formats)
186             result['formats'] = formats
187
188         return result
189
190     def _real_extract(self, url):
191         mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
192         if mobj is None:
193             raise ExtractorError('Invalid URL: %s' % url)
194
195         track_id = mobj.group('track_id')
196         token = None
197         if track_id is not None:
198             info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
199             full_title = track_id
200         elif mobj.group('player'):
201             query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
202             return self.url_result(query['url'][0])
203         else:
204             # extract uploader (which is in the url)
205             uploader = mobj.group('uploader')
206             # extract simple title (uploader + slug of song title)
207             slug_title =  mobj.group('title')
208             token = mobj.group('token')
209             full_title = resolve_title = '%s/%s' % (uploader, slug_title)
210             if token:
211                 resolve_title += '/%s' % token
212     
213             self.report_resolve(full_title)
214     
215             url = 'http://soundcloud.com/%s' % resolve_title
216             info_json_url = self._resolv_url(url)
217         info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
218
219         return self._extract_info_dict(info, full_title, secret_token=token)
220
221
222 class SoundcloudSetIE(SoundcloudIE):
223     _VALID_URL = r'https?://(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)'
224     IE_NAME = 'soundcloud:set'
225     # it's in tests/test_playlists.py
226     _TESTS = []
227
228     def _real_extract(self, url):
229         mobj = re.match(self._VALID_URL, url)
230         if mobj is None:
231             raise ExtractorError('Invalid URL: %s' % url)
232
233         # extract uploader (which is in the url)
234         uploader = mobj.group(1)
235         # extract simple title (uploader + slug of song title)
236         slug_title = mobj.group(2)
237         full_title = '%s/sets/%s' % (uploader, slug_title)
238
239         self.report_resolve(full_title)
240
241         url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
242         resolv_url = self._resolv_url(url)
243         info = self._download_json(resolv_url, full_title)
244
245         if 'errors' in info:
246             for err in info['errors']:
247                 self._downloader.report_error('unable to download video webpage: %s' % compat_str(err['error_message']))
248             return
249
250         self.report_extraction(full_title)
251         return {'_type': 'playlist',
252                 'entries': [self._extract_info_dict(track) for track in info['tracks']],
253                 'id': info['id'],
254                 'title': info['title'],
255                 }
256
257
258 class SoundcloudUserIE(SoundcloudIE):
259     _VALID_URL = r'https?://(www\.)?soundcloud\.com/(?P<user>[^/]+)(/?(tracks/)?)?(\?.*)?$'
260     IE_NAME = 'soundcloud:user'
261
262     # it's in tests/test_playlists.py
263     _TESTS = []
264
265     def _real_extract(self, url):
266         mobj = re.match(self._VALID_URL, url)
267         uploader = mobj.group('user')
268
269         url = 'http://soundcloud.com/%s/' % uploader
270         resolv_url = self._resolv_url(url)
271         user = self._download_json(
272             resolv_url, uploader, 'Downloading user info')
273         base_url = 'http://api.soundcloud.com/users/%s/tracks.json?' % uploader
274
275         entries = []
276         for i in itertools.count():
277             data = compat_urllib_parse.urlencode({
278                 'offset': i * 50,
279                 'client_id': self._CLIENT_ID,
280             })
281             new_entries = self._download_json(
282                 base_url + data, uploader, 'Downloading track page %s' % (i + 1))
283             entries.extend(self._extract_info_dict(e, quiet=True) for e in new_entries)
284             if len(new_entries) < 50:
285                 break
286
287         return {
288             '_type': 'playlist',
289             'id': compat_str(user['id']),
290             'title': user['username'],
291             'entries': entries,
292         }
293
294
295 class SoundcloudPlaylistIE(SoundcloudIE):
296     _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)'
297     IE_NAME = 'soundcloud:playlist'
298
299      # it's in tests/test_playlists.py
300     _TESTS = []
301
302     def _real_extract(self, url):
303         mobj = re.match(self._VALID_URL, url)
304         playlist_id = mobj.group('id')
305         base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
306
307         data = compat_urllib_parse.urlencode({
308             'client_id': self._CLIENT_ID,
309         })
310         data = self._download_json(
311             base_url + data, playlist_id, 'Downloading playlist')
312
313         entries = [
314             self._extract_info_dict(t, quiet=True) for t in data['tracks']]
315
316         return {
317             '_type': 'playlist',
318             'id': playlist_id,
319             'title': data.get('title'),
320             'description': data.get('description'),
321             'entries': entries,
322         }