6 from .common import InfoExtractor
17 class SoundcloudIE(InfoExtractor):
18 """Information extractor for soundcloud.com
19 To access the media, the uid of the song and a stream token
20 must be extracted from the page source and the script must make
21 a request to media.soundcloud.com/crossdomain.xml. Then
22 the media can be grabbed by requesting from an url composed
23 of the stream token and uid
26 _VALID_URL = r'''^(?:https?://)?
27 (?:(?:(?:www\.)?soundcloud\.com/
28 (?P<uploader>[\w\d-]+)/
29 (?!sets/)(?P<title>[\w\d-]+)/?
30 (?P<token>[^?]+?)?(?:[?].*)?$)
31 |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+))
32 |(?P<widget>w\.soundcloud\.com/player/?.*?url=.*)
35 IE_NAME = u'soundcloud'
38 u'url': u'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
39 u'file': u'62986583.mp3',
40 u'md5': u'ebef0a451b909710ed1d7787dddbf0d7',
42 u"upload_date": u"20121011",
43 u"description": u"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",
44 u"uploader": u"E.T. ExTerrestrial Music",
45 u"title": u"Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1"
50 u'url': u'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
54 u'title': u'Goldrushed',
55 u'uploader': u'The Royal Concept',
56 u'upload_date': u'20120521',
60 u'skip_download': True,
65 u'url': u'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
66 u'md5': u'aa0dd32bfea9b0c5ef4f02aacd080604',
70 u'title': u'Youtube - Dl Test Video \'\' Ä↭',
71 u'uploader': u'jaimeMF',
72 u'description': u'test chars: \"\'/\\ä↭',
73 u'upload_date': u'20131209',
78 _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
79 _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
82 def suitable(cls, url):
83 return re.match(cls._VALID_URL, url, flags=re.VERBOSE) is not None
85 def report_resolve(self, video_id):
86 """Report information extraction."""
87 self.to_screen(u'%s: Resolving id' % video_id)
90 def _resolv_url(cls, url):
91 return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
93 def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
94 track_id = compat_str(info['id'])
95 name = full_title or track_id
97 self.report_extraction(name)
99 thumbnail = info['artwork_url']
100 if thumbnail is not None:
101 thumbnail = thumbnail.replace('-large', '-t500x500')
105 'uploader': info['user']['username'],
106 'upload_date': unified_strdate(info['created_at']),
107 'title': info['title'],
108 'description': info['description'],
109 'thumbnail': thumbnail,
111 if info.get('downloadable', False):
112 # We can build a direct link to the song
114 u'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
115 track_id, self._CLIENT_ID))
116 result['formats'] = [{
117 'format_id': 'download',
123 # We have to retrieve the url
124 streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
125 'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
126 stream_json = self._download_webpage(
128 track_id, u'Downloading track url')
131 format_dict = json.loads(stream_json)
132 for key, stream_url in format_dict.items():
133 if key.startswith(u'http'):
140 elif key.startswith(u'rtmp'):
141 # The url doesn't have an rtmp app, we have to extract the playpath
142 url, path = stream_url.split('mp3:', 1)
146 'play_path': 'mp3:' + path,
152 # We fallback to the stream_url in the original info, this
153 # cannot be always used, sometimes it can give an HTTP 404 error
155 'format_id': u'fallback',
156 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
162 if f['format_id'].startswith('http'):
164 if f['format_id'].startswith('rtmp'):
168 formats.sort(key=format_pref)
169 result['formats'] = formats
173 def _real_extract(self, url):
174 mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
176 raise ExtractorError(u'Invalid URL: %s' % url)
178 track_id = mobj.group('track_id')
180 if track_id is not None:
181 info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
182 full_title = track_id
183 elif mobj.group('widget'):
184 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
185 return self.url_result(query['url'][0], ie='Soundcloud')
187 # extract uploader (which is in the url)
188 uploader = mobj.group('uploader')
189 # extract simple title (uploader + slug of song title)
190 slug_title = mobj.group('title')
191 token = mobj.group('token')
192 full_title = resolve_title = '%s/%s' % (uploader, slug_title)
194 resolve_title += '/%s' % token
196 self.report_resolve(full_title)
198 url = 'http://soundcloud.com/%s' % resolve_title
199 info_json_url = self._resolv_url(url)
200 info_json = self._download_webpage(info_json_url, full_title, u'Downloading info JSON')
202 info = json.loads(info_json)
203 return self._extract_info_dict(info, full_title, secret_token=token)
205 class SoundcloudSetIE(SoundcloudIE):
206 _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)(?:[?].*)?$'
207 IE_NAME = u'soundcloud:set'
208 # it's in tests/test_playlists.py
211 def _real_extract(self, url):
212 mobj = re.match(self._VALID_URL, url)
214 raise ExtractorError(u'Invalid URL: %s' % url)
216 # extract uploader (which is in the url)
217 uploader = mobj.group(1)
218 # extract simple title (uploader + slug of song title)
219 slug_title = mobj.group(2)
220 full_title = '%s/sets/%s' % (uploader, slug_title)
222 self.report_resolve(full_title)
224 url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
225 resolv_url = self._resolv_url(url)
226 info_json = self._download_webpage(resolv_url, full_title)
228 info = json.loads(info_json)
230 for err in info['errors']:
231 self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err['error_message']))
234 self.report_extraction(full_title)
235 return {'_type': 'playlist',
236 'entries': [self._extract_info_dict(track) for track in info['tracks']],
238 'title': info['title'],
242 class SoundcloudUserIE(SoundcloudIE):
243 _VALID_URL = r'https?://(www\.)?soundcloud\.com/(?P<user>[^/]+)(/?(tracks/)?)?(\?.*)?$'
244 IE_NAME = u'soundcloud:user'
246 # it's in tests/test_playlists.py
249 def _real_extract(self, url):
250 mobj = re.match(self._VALID_URL, url)
251 uploader = mobj.group('user')
253 url = 'http://soundcloud.com/%s/' % uploader
254 resolv_url = self._resolv_url(url)
255 user_json = self._download_webpage(resolv_url, uploader,
256 u'Downloading user info')
257 user = json.loads(user_json)
260 for i in itertools.count():
261 data = compat_urllib_parse.urlencode({'offset': i*50,
262 'client_id': self._CLIENT_ID,
264 tracks_url = 'http://api.soundcloud.com/users/%s/tracks.json?' % user['id'] + data
265 response = self._download_webpage(tracks_url, uploader,
266 u'Downloading tracks page %s' % (i+1))
267 new_tracks = json.loads(response)
268 tracks.extend(self._extract_info_dict(track, quiet=True) for track in new_tracks)
269 if len(new_tracks) < 50:
274 'id': compat_str(user['id']),
275 'title': user['username'],