]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/soundcloud.py
[soundcloud] Support api urls with secret_token, Closes #3707
[yt-dlp.git] / youtube_dl / extractor / soundcloud.py
CommitLineData
de2dd4c5 1# encoding: utf-8
fbcd7b5f
PH
2from __future__ import unicode_literals
3
aad0d6d5 4import re
92790f4e 5import itertools
aad0d6d5
PH
6
7from .common import InfoExtractor
8from ..utils import (
9 compat_str,
668de34c 10 compat_urlparse,
92790f4e 11 compat_urllib_parse,
aad0d6d5
PH
12
13 ExtractorError,
eb920777 14 int_or_none,
aad0d6d5
PH
15 unified_strdate,
16)
17
18
19class 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
26 """
27
20991253 28 _VALID_URL = r'''(?x)^(?:https?://)?
71507a11 29 (?:(?:(?:www\.|m\.)?soundcloud\.com/
4ff50ef8 30 (?P<uploader>[\w\d-]+)/
22a6f150
PH
31 (?!sets/|likes/?(?:$|[?#]))
32 (?P<title>[\w\d-]+)/?
de2dd4c5 33 (?P<token>[^?]+?)?(?:[?].*)?$)
9296738f 34 |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+)
35 (?:/?\?secret_token=(?P<secret_token>[^&]+?))?$)
31c1cf5a 36 |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
eb6a41ba
JMF
37 )
38 '''
fbcd7b5f 39 IE_NAME = 'soundcloud'
12c167c8
JMF
40 _TESTS = [
41 {
fbcd7b5f
PH
42 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
43 'file': '62986583.mp3',
44 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
45 'info_dict': {
46 "upload_date": "20121011",
47 "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",
48 "uploader": "E.T. ExTerrestrial Music",
eb920777
PH
49 "title": "Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1",
50 "duration": 143,
12c167c8
JMF
51 }
52 },
53 # not streamable song
54 {
fbcd7b5f
PH
55 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
56 'info_dict': {
57 'id': '47127627',
58 'ext': 'mp3',
59 'title': 'Goldrushed',
63ad0315 60 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
fbcd7b5f
PH
61 'uploader': 'The Royal Concept',
62 'upload_date': '20120521',
eb920777 63 'duration': 227,
12c167c8 64 },
fbcd7b5f 65 'params': {
12c167c8 66 # rtmp
fbcd7b5f 67 'skip_download': True,
12c167c8
JMF
68 },
69 },
de2dd4c5
JMF
70 # private link
71 {
fbcd7b5f
PH
72 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
73 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
74 'info_dict': {
75 'id': '123998367',
76 'ext': 'mp3',
77 'title': 'Youtube - Dl Test Video \'\' Ä↭',
78 'uploader': 'jaimeMF',
79 'description': 'test chars: \"\'/\\ä↭',
80 'upload_date': '20131209',
eb920777 81 'duration': 9,
de2dd4c5
JMF
82 },
83 },
9296738f 84 # private link (alt format)
85 {
86 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
87 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
88 'info_dict': {
89 'id': '123998367',
90 'ext': 'mp3',
91 'title': 'Youtube - Dl Test Video \'\' Ä↭',
92 'uploader': 'jaimeMF',
93 'description': 'test chars: \"\'/\\ä↭',
94 'upload_date': '20131209',
95 'duration': 9,
96 },
97 },
f67ca84d
JMF
98 # downloadable song
99 {
00a82ea8 100 'url': 'https://soundcloud.com/oddsamples/bus-brakes',
eae12e3f 101 'md5': '7624f2351f8a3b2e7cd51522496e7631',
fbcd7b5f 102 'info_dict': {
00a82ea8 103 'id': '128590877',
eae12e3f 104 'ext': 'mp3',
00a82ea8
S
105 'title': 'Bus Brakes',
106 'description': 'md5:0170be75dd395c96025d210d261c784e',
107 'uploader': 'oddsamples',
108 'upload_date': '20140109',
109 'duration': 17,
f67ca84d
JMF
110 },
111 },
12c167c8 112 ]
aad0d6d5 113
7d239269 114 _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
64bb5187 115 _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
7d239269 116
aad0d6d5
PH
117 def report_resolve(self, video_id):
118 """Report information extraction."""
83622b6d 119 self.to_screen('%s: Resolving id' % video_id)
aad0d6d5 120
7d239269
JMF
121 @classmethod
122 def _resolv_url(cls, url):
123 return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
124
de2dd4c5 125 def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
12c167c8
JMF
126 track_id = compat_str(info['id'])
127 name = full_title or track_id
2a15e706 128 if quiet:
92790f4e 129 self.report_extraction(name)
7d239269
JMF
130
131 thumbnail = info['artwork_url']
132 if thumbnail is not None:
133 thumbnail = thumbnail.replace('-large', '-t500x500')
fbcd7b5f 134 ext = 'mp3'
12c167c8 135 result = {
2a15e706 136 'id': track_id,
7d239269
JMF
137 'uploader': info['user']['username'],
138 'upload_date': unified_strdate(info['created_at']),
2a15e706 139 'title': info['title'],
7d239269
JMF
140 'description': info['description'],
141 'thumbnail': thumbnail,
eb920777 142 'duration': int_or_none(info.get('duration'), 1000),
7d239269 143 }
5e114e4b 144 formats = []
12c167c8 145 if info.get('downloadable', False):
64bb5187 146 # We can build a direct link to the song
2a15e706 147 format_url = (
fbcd7b5f 148 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
2a15e706 149 track_id, self._CLIENT_ID))
5e114e4b 150 formats.append({
2a15e706 151 'format_id': 'download',
fbcd7b5f 152 'ext': info.get('original_format', 'mp3'),
2a15e706 153 'url': format_url,
fb04e403 154 'vcodec': 'none',
5e114e4b
PH
155 'preference': 10,
156 })
157
158 # We have to retrieve the url
159 streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
160 'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
20991253 161 format_dict = self._download_json(
5e114e4b
PH
162 streams_url,
163 track_id, 'Downloading track url')
164
5e114e4b
PH
165 for key, stream_url in format_dict.items():
166 if key.startswith('http'):
167 formats.append({
168 'format_id': key,
169 'ext': ext,
170 'url': stream_url,
171 'vcodec': 'none',
172 })
173 elif key.startswith('rtmp'):
174 # The url doesn't have an rtmp app, we have to extract the playpath
175 url, path = stream_url.split('mp3:', 1)
176 formats.append({
177 'format_id': key,
178 'url': url,
179 'play_path': 'mp3:' + path,
180 'ext': ext,
181 'vcodec': 'none',
182 })
2a15e706
PH
183
184 if not formats:
64bb5187
JMF
185 # We fallback to the stream_url in the original info, this
186 # cannot be always used, sometimes it can give an HTTP 404 error
2a15e706 187 formats.append({
fbcd7b5f 188 'format_id': 'fallback',
2a15e706
PH
189 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
190 'ext': ext,
fb04e403 191 'vcodec': 'none',
2a15e706
PH
192 })
193
fbcd7b5f 194 for f in formats:
2a15e706 195 if f['format_id'].startswith('http'):
fbcd7b5f 196 f['protocol'] = 'http'
2a15e706 197 if f['format_id'].startswith('rtmp'):
fbcd7b5f 198 f['protocol'] = 'rtmp'
2a15e706 199
fbcd7b5f 200 self._sort_formats(formats)
2a15e706 201 result['formats'] = formats
64bb5187 202
12c167c8 203 return result
7d239269 204
aad0d6d5 205 def _real_extract(self, url):
eb6a41ba 206 mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
aad0d6d5 207 if mobj is None:
83622b6d 208 raise ExtractorError('Invalid URL: %s' % url)
aad0d6d5 209
eb6a41ba 210 track_id = mobj.group('track_id')
de2dd4c5 211 token = None
eb6a41ba
JMF
212 if track_id is not None:
213 info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
214 full_title = track_id
9296738f 215 token = mobj.group('secret_token')
216 if token:
217 info_json_url += "&secret_token=" + token
31c1cf5a 218 elif mobj.group('player'):
668de34c 219 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
20991253 220 return self.url_result(query['url'][0])
eb6a41ba
JMF
221 else:
222 # extract uploader (which is in the url)
de2dd4c5 223 uploader = mobj.group('uploader')
eb6a41ba 224 # extract simple title (uploader + slug of song title)
de2dd4c5
JMF
225 slug_title = mobj.group('title')
226 token = mobj.group('token')
227 full_title = resolve_title = '%s/%s' % (uploader, slug_title)
228 if token:
229 resolve_title += '/%s' % token
eb6a41ba
JMF
230
231 self.report_resolve(full_title)
232
de2dd4c5 233 url = 'http://soundcloud.com/%s' % resolve_title
eb6a41ba 234 info_json_url = self._resolv_url(url)
20991253 235 info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
aad0d6d5 236
de2dd4c5 237 return self._extract_info_dict(info, full_title, secret_token=token)
aad0d6d5 238
20991253 239
7d239269 240class SoundcloudSetIE(SoundcloudIE):
9d3f7781 241 _VALID_URL = r'https?://(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)'
fbcd7b5f 242 IE_NAME = 'soundcloud:set'
22a6f150
PH
243 _TESTS = [{
244 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
245 'info_dict': {
246 'title': 'The Royal Concept EP',
247 },
248 'playlist_mincount': 6,
249 }]
aad0d6d5 250
aad0d6d5
PH
251 def _real_extract(self, url):
252 mobj = re.match(self._VALID_URL, url)
aad0d6d5
PH
253
254 # extract uploader (which is in the url)
255 uploader = mobj.group(1)
256 # extract simple title (uploader + slug of song title)
20991253 257 slug_title = mobj.group(2)
aad0d6d5
PH
258 full_title = '%s/sets/%s' % (uploader, slug_title)
259
260 self.report_resolve(full_title)
261
262 url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
7d239269 263 resolv_url = self._resolv_url(url)
20991253 264 info = self._download_json(resolv_url, full_title)
aad0d6d5 265
aad0d6d5
PH
266 if 'errors' in info:
267 for err in info['errors']:
83622b6d 268 self._downloader.report_error('unable to download video webpage: %s' % compat_str(err['error_message']))
aad0d6d5
PH
269 return
270
22a6f150
PH
271 return {
272 '_type': 'playlist',
273 'entries': [self._extract_info_dict(track) for track in info['tracks']],
274 'id': info['id'],
275 'title': info['title'],
276 }
92790f4e
JMF
277
278
279class SoundcloudUserIE(SoundcloudIE):
3941669d 280 _VALID_URL = r'https?://(www\.)?soundcloud\.com/(?P<user>[^/]+)/?((?P<rsrc>tracks|likes)/?)?(\?.*)?$'
fbcd7b5f 281 IE_NAME = 'soundcloud:user'
22a6f150
PH
282 _TESTS = [{
283 'url': 'https://soundcloud.com/the-concept-band',
284 'info_dict': {
285 'id': '9615865',
286 'title': 'The Royal Concept',
287 },
288 'playlist_mincount': 12
289 }, {
290 'url': 'https://soundcloud.com/the-concept-band/likes',
291 'info_dict': {
292 'id': '9615865',
293 'title': 'The Royal Concept',
294 },
295 'playlist_mincount': 1,
296 }]
92790f4e
JMF
297
298 def _real_extract(self, url):
299 mobj = re.match(self._VALID_URL, url)
300 uploader = mobj.group('user')
3941669d 301 resource = mobj.group('rsrc')
302 if resource is None:
303 resource = 'tracks'
304 elif resource == 'likes':
305 resource = 'favorites'
92790f4e
JMF
306
307 url = 'http://soundcloud.com/%s/' % uploader
308 resolv_url = self._resolv_url(url)
20991253
PH
309 user = self._download_json(
310 resolv_url, uploader, 'Downloading user info')
3941669d 311 base_url = 'http://api.soundcloud.com/users/%s/%s.json?' % (uploader, resource)
92790f4e 312
20991253 313 entries = []
92790f4e 314 for i in itertools.count():
20991253
PH
315 data = compat_urllib_parse.urlencode({
316 'offset': i * 50,
3941669d 317 'limit': 50,
20991253
PH
318 'client_id': self._CLIENT_ID,
319 })
320 new_entries = self._download_json(
321 base_url + data, uploader, 'Downloading track page %s' % (i + 1))
3941669d 322 if len(new_entries) == 0:
323 self.to_screen('%s: End page received' % uploader)
92790f4e 324 break
3941669d 325 entries.extend(self._extract_info_dict(e, quiet=True) for e in new_entries)
92790f4e
JMF
326
327 return {
328 '_type': 'playlist',
329 'id': compat_str(user['id']),
330 'title': user['username'],
20991253
PH
331 'entries': entries,
332 }
333
334
335class SoundcloudPlaylistIE(SoundcloudIE):
336 _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)'
337 IE_NAME = 'soundcloud:playlist'
22a6f150 338 _TESTS = [
20991253 339
22a6f150
PH
340 {
341 'url': 'http://api.soundcloud.com/playlists/4110309',
342 'info_dict': {
343 'id': '4110309',
344 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
345 'description': 're:.*?TILT Brass - Bowery Poetry Club',
346 },
347 'playlist_count': 6,
348 }
349 ]
20991253
PH
350
351 def _real_extract(self, url):
352 mobj = re.match(self._VALID_URL, url)
353 playlist_id = mobj.group('id')
354 base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
355
356 data = compat_urllib_parse.urlencode({
357 'client_id': self._CLIENT_ID,
358 })
359 data = self._download_json(
360 base_url + data, playlist_id, 'Downloading playlist')
361
362 entries = [
363 self._extract_info_dict(t, quiet=True) for t in data['tracks']]
364
365 return {
366 '_type': 'playlist',
367 'id': playlist_id,
368 'title': data.get('title'),
369 'description': data.get('description'),
370 'entries': entries,
92790f4e 371 }