2 from __future__ import unicode_literals
8 from .common import InfoExtractor
19 class SoundcloudIE(InfoExtractor):
20 """Information extractor for soundcloud.com
21 To access the media, the uid of the song and a stream token
22 must be extracted from the page source and the script must make
23 a request to media.soundcloud.com/crossdomain.xml. Then
24 the media can be grabbed by requesting from an url composed
25 of the stream token and uid
28 _VALID_URL = r'''(?x)^(?:https?://)?
29 (?:(?:(?:www\.|m\.)?soundcloud\.com/
30 (?P<uploader>[\w\d-]+)/
31 (?!sets/)(?P<title>[\w\d-]+)/?
32 (?P<token>[^?]+?)?(?:[?].*)?$)
33 |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+))
34 |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
37 IE_NAME = 'soundcloud'
40 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
41 'file': '62986583.mp3',
42 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
44 "upload_date": "20121011",
45 "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",
46 "uploader": "E.T. ExTerrestrial Music",
47 "title": "Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1"
52 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
56 'title': 'Goldrushed',
57 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
58 'uploader': 'The Royal Concept',
59 'upload_date': '20120521',
63 'skip_download': True,
68 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
69 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
73 'title': 'Youtube - Dl Test Video \'\' Ä↭',
74 'uploader': 'jaimeMF',
75 'description': 'test chars: \"\'/\\ä↭',
76 'upload_date': '20131209',
81 'url': 'https://soundcloud.com/simgretina/just-your-problem-baby-1',
82 'md5': '56a8b69568acaa967b4c49f9d1d52d19',
86 'title': 'Just Your Problem Baby (Acapella)',
87 'description': 'Vocals',
88 'uploader': 'Sim Gretina',
89 'upload_date': '20130815',
94 _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
95 _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
97 def report_resolve(self, video_id):
98 """Report information extraction."""
99 self.to_screen('%s: Resolving id' % video_id)
102 def _resolv_url(cls, url):
103 return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
105 def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
106 track_id = compat_str(info['id'])
107 name = full_title or track_id
109 self.report_extraction(name)
111 thumbnail = info['artwork_url']
112 if thumbnail is not None:
113 thumbnail = thumbnail.replace('-large', '-t500x500')
117 'uploader': info['user']['username'],
118 'upload_date': unified_strdate(info['created_at']),
119 'title': info['title'],
120 'description': info['description'],
121 'thumbnail': thumbnail,
124 if info.get('downloadable', False):
125 # We can build a direct link to the song
127 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
128 track_id, self._CLIENT_ID))
130 'format_id': 'download',
131 'ext': info.get('original_format', 'mp3'),
137 # We have to retrieve the url
138 streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
139 'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
140 format_dict = self._download_json(
142 track_id, 'Downloading track url')
144 for key, stream_url in format_dict.items():
145 if key.startswith('http'):
152 elif key.startswith('rtmp'):
153 # The url doesn't have an rtmp app, we have to extract the playpath
154 url, path = stream_url.split('mp3:', 1)
158 'play_path': 'mp3:' + path,
164 # We fallback to the stream_url in the original info, this
165 # cannot be always used, sometimes it can give an HTTP 404 error
167 'format_id': 'fallback',
168 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
174 if f['format_id'].startswith('http'):
175 f['protocol'] = 'http'
176 if f['format_id'].startswith('rtmp'):
177 f['protocol'] = 'rtmp'
179 self._sort_formats(formats)
180 result['formats'] = formats
184 def _real_extract(self, url):
185 mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
187 raise ExtractorError('Invalid URL: %s' % url)
189 track_id = mobj.group('track_id')
191 if track_id is not None:
192 info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
193 full_title = track_id
194 elif mobj.group('player'):
195 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
196 return self.url_result(query['url'][0])
198 # extract uploader (which is in the url)
199 uploader = mobj.group('uploader')
200 # extract simple title (uploader + slug of song title)
201 slug_title = mobj.group('title')
202 token = mobj.group('token')
203 full_title = resolve_title = '%s/%s' % (uploader, slug_title)
205 resolve_title += '/%s' % token
207 self.report_resolve(full_title)
209 url = 'http://soundcloud.com/%s' % resolve_title
210 info_json_url = self._resolv_url(url)
211 info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
213 return self._extract_info_dict(info, full_title, secret_token=token)
216 class SoundcloudSetIE(SoundcloudIE):
217 _VALID_URL = r'https?://(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)'
218 IE_NAME = 'soundcloud:set'
219 # it's in tests/test_playlists.py
222 def _real_extract(self, url):
223 mobj = re.match(self._VALID_URL, url)
225 raise ExtractorError('Invalid URL: %s' % url)
227 # extract uploader (which is in the url)
228 uploader = mobj.group(1)
229 # extract simple title (uploader + slug of song title)
230 slug_title = mobj.group(2)
231 full_title = '%s/sets/%s' % (uploader, slug_title)
233 self.report_resolve(full_title)
235 url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
236 resolv_url = self._resolv_url(url)
237 info = self._download_json(resolv_url, full_title)
240 for err in info['errors']:
241 self._downloader.report_error('unable to download video webpage: %s' % compat_str(err['error_message']))
244 self.report_extraction(full_title)
245 return {'_type': 'playlist',
246 'entries': [self._extract_info_dict(track) for track in info['tracks']],
248 'title': info['title'],
252 class SoundcloudUserIE(SoundcloudIE):
253 _VALID_URL = r'https?://(www\.)?soundcloud\.com/(?P<user>[^/]+)(/?(tracks/)?)?(\?.*)?$'
254 IE_NAME = 'soundcloud:user'
256 # it's in tests/test_playlists.py
259 def _real_extract(self, url):
260 mobj = re.match(self._VALID_URL, url)
261 uploader = mobj.group('user')
263 url = 'http://soundcloud.com/%s/' % uploader
264 resolv_url = self._resolv_url(url)
265 user = self._download_json(
266 resolv_url, uploader, 'Downloading user info')
267 base_url = 'http://api.soundcloud.com/users/%s/tracks.json?' % uploader
270 for i in itertools.count():
271 data = compat_urllib_parse.urlencode({
273 'client_id': self._CLIENT_ID,
275 new_entries = self._download_json(
276 base_url + data, uploader, 'Downloading track page %s' % (i + 1))
277 entries.extend(self._extract_info_dict(e, quiet=True) for e in new_entries)
278 if len(new_entries) < 50:
283 'id': compat_str(user['id']),
284 'title': user['username'],
289 class SoundcloudPlaylistIE(SoundcloudIE):
290 _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)'
291 IE_NAME = 'soundcloud:playlist'
293 # it's in tests/test_playlists.py
296 def _real_extract(self, url):
297 mobj = re.match(self._VALID_URL, url)
298 playlist_id = mobj.group('id')
299 base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
301 data = compat_urllib_parse.urlencode({
302 'client_id': self._CLIENT_ID,
304 data = self._download_json(
305 base_url + data, playlist_id, 'Downloading playlist')
308 self._extract_info_dict(t, quiet=True) for t in data['tracks']]
313 'title': data.get('title'),
314 'description': data.get('description'),