5 from .common import InfoExtractor
16 class SoundcloudIE(InfoExtractor):
17 """Information extractor for soundcloud.com
18 To access the media, the uid of the song and a stream token
19 must be extracted from the page source and the script must make
20 a request to media.soundcloud.com/crossdomain.xml. Then
21 the media can be grabbed by requesting from an url composed
22 of the stream token and uid
25 _VALID_URL = r'''^(?:https?://)?
26 (?:(?:(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)/?(?:[?].*)?$)
27 |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+))
28 |(?P<widget>w.soundcloud.com/player/?.*?url=.*)
31 IE_NAME = u'soundcloud'
34 u'url': u'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
35 u'file': u'62986583.mp3',
36 u'md5': u'ebef0a451b909710ed1d7787dddbf0d7',
38 u"upload_date": u"20121011",
39 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",
40 u"uploader": u"E.T. ExTerrestrial Music",
41 u"title": u"Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1"
46 u'url': u'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
50 u'title': u'Goldrushed',
51 u'uploader': u'The Royal Concept',
52 u'upload_date': u'20120521',
56 u'skip_download': True,
61 _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
62 _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
65 def suitable(cls, url):
66 return re.match(cls._VALID_URL, url, flags=re.VERBOSE) is not None
68 def report_resolve(self, video_id):
69 """Report information extraction."""
70 self.to_screen(u'%s: Resolving id' % video_id)
73 def _resolv_url(cls, url):
74 return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
76 def _extract_info_dict(self, info, full_title=None, quiet=False):
77 track_id = compat_str(info['id'])
78 name = full_title or track_id
80 self.report_extraction(name)
82 thumbnail = info['artwork_url']
83 if thumbnail is not None:
84 thumbnail = thumbnail.replace('-large', '-t500x500')
87 'uploader': info['user']['username'],
88 'upload_date': unified_strdate(info['created_at']),
89 'title': info['title'],
90 'ext': info.get('original_format', u'mp3'),
91 'description': info['description'],
92 'thumbnail': thumbnail,
94 if info.get('downloadable', False):
95 # We can build a direct link to the song
96 result['url'] = 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(track_id, self._CLIENT_ID)
98 # We have to retrieve the url
99 stream_json = self._download_webpage(
100 'http://api.soundcloud.com/i1/tracks/{0}/streams?client_id={1}'.format(track_id, self._IPHONE_CLIENT_ID),
101 track_id, u'Downloading track url')
102 # There should be only one entry in the dictionary
103 key, stream_url = list(json.loads(stream_json).items())[0]
104 if key.startswith(u'http'):
105 result['url'] = stream_url
106 elif key.startswith(u'rtmp'):
107 # The url doesn't have an rtmp app, we have to extract the playpath
108 url, path = stream_url.split('mp3:', 1)
111 'play_path': 'mp3:' + path,
114 # We fallback to the stream_url in the original info, this
115 # cannot be always used, sometimes it can give an HTTP 404 error
116 result['url'] = info['stream_url'] + '?client_id=' + self._CLIENT_ID,
120 def _real_extract(self, url):
121 mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
123 raise ExtractorError(u'Invalid URL: %s' % url)
125 track_id = mobj.group('track_id')
126 if track_id is not None:
127 info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
128 full_title = track_id
129 elif mobj.group('widget'):
130 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
131 return self.url_result(query['url'][0], ie='Soundcloud')
133 # extract uploader (which is in the url)
134 uploader = mobj.group(1)
135 # extract simple title (uploader + slug of song title)
136 slug_title = mobj.group(2)
137 full_title = '%s/%s' % (uploader, slug_title)
139 self.report_resolve(full_title)
141 url = 'http://soundcloud.com/%s/%s' % (uploader, slug_title)
142 info_json_url = self._resolv_url(url)
143 info_json = self._download_webpage(info_json_url, full_title, u'Downloading info JSON')
145 info = json.loads(info_json)
146 return self._extract_info_dict(info, full_title)
148 class SoundcloudSetIE(SoundcloudIE):
149 _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)(?:[?].*)?$'
150 IE_NAME = u'soundcloud:set'
151 # it's in tests/test_playlists.py
154 def _real_extract(self, url):
155 mobj = re.match(self._VALID_URL, url)
157 raise ExtractorError(u'Invalid URL: %s' % url)
159 # extract uploader (which is in the url)
160 uploader = mobj.group(1)
161 # extract simple title (uploader + slug of song title)
162 slug_title = mobj.group(2)
163 full_title = '%s/sets/%s' % (uploader, slug_title)
165 self.report_resolve(full_title)
167 url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
168 resolv_url = self._resolv_url(url)
169 info_json = self._download_webpage(resolv_url, full_title)
171 info = json.loads(info_json)
173 for err in info['errors']:
174 self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err['error_message']))
177 self.report_extraction(full_title)
178 return {'_type': 'playlist',
179 'entries': [self._extract_info_dict(track) for track in info['tracks']],
181 'title': info['title'],
185 class SoundcloudUserIE(SoundcloudIE):
186 _VALID_URL = r'https?://(www\.)?soundcloud.com/(?P<user>[^/]+)(/?(tracks/)?)?(\?.*)?$'
187 IE_NAME = u'soundcloud:user'
189 # it's in tests/test_playlists.py
192 def _real_extract(self, url):
193 mobj = re.match(self._VALID_URL, url)
194 uploader = mobj.group('user')
196 url = 'http://soundcloud.com/%s/' % uploader
197 resolv_url = self._resolv_url(url)
198 user_json = self._download_webpage(resolv_url, uploader,
199 u'Downloading user info')
200 user = json.loads(user_json)
203 for i in itertools.count():
204 data = compat_urllib_parse.urlencode({'offset': i*50,
205 'client_id': self._CLIENT_ID,
207 tracks_url = 'http://api.soundcloud.com/users/%s/tracks.json?' % user['id'] + data
208 response = self._download_webpage(tracks_url, uploader,
209 u'Downloading tracks page %s' % (i+1))
210 new_tracks = json.loads(response)
211 tracks.extend(self._extract_info_dict(track, quiet=True) for track in new_tracks)
212 if len(new_tracks) < 50:
217 'id': compat_str(user['id']),
218 'title': user['username'],