2 from __future__
import unicode_literals
11 from ..compat
import (
14 compat_urllib_parse_urlencode
,
23 class SoundcloudIE(InfoExtractor
):
24 """Information extractor for soundcloud.com
25 To access the media, the uid of the song and a stream token
26 must be extracted from the page source and the script must make
27 a request to media.soundcloud.com/crossdomain.xml. Then
28 the media can be grabbed by requesting from an url composed
29 of the stream token and uid
32 _VALID_URL
= r
'''(?x)^(?:https?://)?
33 (?:(?:(?:www\.|m\.)?soundcloud\.com/
34 (?P<uploader>[\w\d-]+)/
35 (?!(?:tracks|sets(?:/[^/?#]+)?|reposts|likes|spotlight)/?(?:$|[?#]))
37 (?P<token>[^?]+?)?(?:[?].*)?$)
38 |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+)
39 (?:/?\?secret_token=(?P<secret_token>[^&]+))?)
40 |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
43 IE_NAME
= 'soundcloud'
46 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
47 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
51 'upload_date': '20121011',
52 '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',
53 'uploader': 'E.T. ExTerrestrial Music',
54 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
60 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
64 'title': 'Goldrushed',
65 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
66 'uploader': 'The Royal Concept',
67 'upload_date': '20120521',
72 'skip_download': True,
77 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
78 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
82 'title': 'Youtube - Dl Test Video \'\' Ä↭',
83 'uploader': 'jaimeMF',
84 'description': 'test chars: \"\'/\\ä↭',
85 'upload_date': '20131209',
89 # private link (alt format)
91 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
92 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
96 'title': 'Youtube - Dl Test Video \'\' Ä↭',
97 'uploader': 'jaimeMF',
98 'description': 'test chars: \"\'/\\ä↭',
99 'upload_date': '20131209',
105 'url': 'https://soundcloud.com/oddsamples/bus-brakes',
106 'md5': '7624f2351f8a3b2e7cd51522496e7631',
110 'title': 'Bus Brakes',
111 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66',
112 'uploader': 'oddsamples',
113 'upload_date': '20140109',
119 _CLIENT_ID
= '02gUJC0hH2ct1EGOcYXQIzRFU91c72Ea'
120 _IPHONE_CLIENT_ID
= '376f225bf427445fc4bfb6b99b72e0bf'
122 def report_resolve(self
, video_id
):
123 """Report information extraction."""
124 self
.to_screen('%s: Resolving id' % video_id
)
127 def _resolv_url(cls
, url
):
128 return 'http://api.soundcloud.com/resolve.json?url=' + url
+ '&client_id=' + cls
._CLIENT
_ID
130 def _extract_info_dict(self
, info
, full_title
=None, quiet
=False, secret_token
=None):
131 track_id
= compat_str(info
['id'])
132 name
= full_title
or track_id
134 self
.report_extraction(name
)
136 thumbnail
= info
['artwork_url']
137 if thumbnail
is not None:
138 thumbnail
= thumbnail
.replace('-large', '-t500x500')
142 'uploader': info
['user']['username'],
143 'upload_date': unified_strdate(info
['created_at']),
144 'title': info
['title'],
145 'description': info
['description'],
146 'thumbnail': thumbnail
,
147 'duration': int_or_none(info
.get('duration'), 1000),
148 'webpage_url': info
.get('permalink_url'),
151 if info
.get('downloadable', False):
152 # We can build a direct link to the song
154 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
155 track_id
, self
._CLIENT
_ID
))
157 'format_id': 'download',
158 'ext': info
.get('original_format', 'mp3'),
164 # We have to retrieve the url
165 streams_url
= ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
166 'client_id={1}&secret_token={2}'.format(track_id
, self
._IPHONE
_CLIENT
_ID
, secret_token
))
167 format_dict
= self
._download
_json
(
169 track_id
, 'Downloading track url')
171 for key
, stream_url
in format_dict
.items():
172 if key
.startswith('http'):
179 elif key
.startswith('rtmp'):
180 # The url doesn't have an rtmp app, we have to extract the playpath
181 url
, path
= stream_url
.split('mp3:', 1)
185 'play_path': 'mp3:' + path
,
191 # We fallback to the stream_url in the original info, this
192 # cannot be always used, sometimes it can give an HTTP 404 error
194 'format_id': 'fallback',
195 'url': info
['stream_url'] + '?client_id=' + self
._CLIENT
_ID
,
201 if f
['format_id'].startswith('http'):
202 f
['protocol'] = 'http'
203 if f
['format_id'].startswith('rtmp'):
204 f
['protocol'] = 'rtmp'
206 self
._check
_formats
(formats
, track_id
)
207 self
._sort
_formats
(formats
)
208 result
['formats'] = formats
212 def _real_extract(self
, url
):
213 mobj
= re
.match(self
._VALID
_URL
, url
, flags
=re
.VERBOSE
)
215 raise ExtractorError('Invalid URL: %s' % url
)
217 track_id
= mobj
.group('track_id')
219 if track_id
is not None:
220 info_json_url
= 'http://api.soundcloud.com/tracks/' + track_id
+ '.json?client_id=' + self
._CLIENT
_ID
221 full_title
= track_id
222 token
= mobj
.group('secret_token')
224 info_json_url
+= '&secret_token=' + token
225 elif mobj
.group('player'):
226 query
= compat_urlparse
.parse_qs(compat_urlparse
.urlparse(url
).query
)
227 real_url
= query
['url'][0]
228 # If the token is in the query of the original url we have to
230 if 'secret_token' in query
:
231 real_url
+= '?secret_token=' + query
['secret_token'][0]
232 return self
.url_result(real_url
)
234 # extract uploader (which is in the url)
235 uploader
= mobj
.group('uploader')
236 # extract simple title (uploader + slug of song title)
237 slug_title
= mobj
.group('title')
238 token
= mobj
.group('token')
239 full_title
= resolve_title
= '%s/%s' % (uploader
, slug_title
)
241 resolve_title
+= '/%s' % token
243 self
.report_resolve(full_title
)
245 url
= 'http://soundcloud.com/%s' % resolve_title
246 info_json_url
= self
._resolv
_url
(url
)
247 info
= self
._download
_json
(info_json_url
, full_title
, 'Downloading info JSON')
249 return self
._extract
_info
_dict
(info
, full_title
, secret_token
=token
)
252 class SoundcloudSetIE(SoundcloudIE
):
253 _VALID_URL
= r
'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
254 IE_NAME
= 'soundcloud:set'
256 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
259 'title': 'The Royal Concept EP',
261 'playlist_mincount': 6,
264 def _real_extract(self
, url
):
265 mobj
= re
.match(self
._VALID
_URL
, url
)
267 # extract uploader (which is in the url)
268 uploader
= mobj
.group('uploader')
269 # extract simple title (uploader + slug of song title)
270 slug_title
= mobj
.group('slug_title')
271 full_title
= '%s/sets/%s' % (uploader
, slug_title
)
272 url
= 'http://soundcloud.com/%s/sets/%s' % (uploader
, slug_title
)
274 token
= mobj
.group('token')
276 full_title
+= '/' + token
279 self
.report_resolve(full_title
)
281 resolv_url
= self
._resolv
_url
(url
)
282 info
= self
._download
_json
(resolv_url
, full_title
)
285 msgs
= (compat_str(err
['error_message']) for err
in info
['errors'])
286 raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs
))
288 entries
= [self
.url_result(track
['permalink_url'], 'Soundcloud') for track
in info
['tracks']]
293 'id': '%s' % info
['id'],
294 'title': info
['title'],
298 class SoundcloudUserIE(SoundcloudIE
):
299 _VALID_URL
= r
'''(?x)
301 (?:(?:www|m)\.)?soundcloud\.com/
304 (?P<rsrc>tracks|sets|reposts|likes|spotlight)
308 IE_NAME
= 'soundcloud:user'
310 'url': 'https://soundcloud.com/the-akashic-chronicler',
313 'title': 'The Akashic Chronicler (All)',
315 'playlist_mincount': 111,
317 'url': 'https://soundcloud.com/the-akashic-chronicler/tracks',
320 'title': 'The Akashic Chronicler (Tracks)',
322 'playlist_mincount': 50,
324 'url': 'https://soundcloud.com/the-akashic-chronicler/sets',
327 'title': 'The Akashic Chronicler (Playlists)',
329 'playlist_mincount': 3,
331 'url': 'https://soundcloud.com/the-akashic-chronicler/reposts',
334 'title': 'The Akashic Chronicler (Reposts)',
336 'playlist_mincount': 7,
338 'url': 'https://soundcloud.com/the-akashic-chronicler/likes',
341 'title': 'The Akashic Chronicler (Likes)',
343 'playlist_mincount': 321,
345 'url': 'https://soundcloud.com/grynpyret/spotlight',
348 'title': 'Grynpyret (Spotlight)',
350 'playlist_mincount': 1,
353 _API_BASE
= 'https://api.soundcloud.com'
354 _API_V2_BASE
= 'https://api-v2.soundcloud.com'
357 'all': '%s/profile/soundcloud:users:%%s' % _API_V2_BASE
,
358 'tracks': '%s/users/%%s/tracks' % _API_BASE
,
359 'sets': '%s/users/%%s/playlists' % _API_V2_BASE
,
360 'reposts': '%s/profile/soundcloud:users:%%s/reposts' % _API_V2_BASE
,
361 'likes': '%s/users/%%s/likes' % _API_V2_BASE
,
362 'spotlight': '%s/users/%%s/spotlight' % _API_V2_BASE
,
369 'reposts': 'Reposts',
371 'spotlight': 'Spotlight',
374 def _real_extract(self
, url
):
375 mobj
= re
.match(self
._VALID
_URL
, url
)
376 uploader
= mobj
.group('user')
378 url
= 'http://soundcloud.com/%s/' % uploader
379 resolv_url
= self
._resolv
_url
(url
)
380 user
= self
._download
_json
(
381 resolv_url
, uploader
, 'Downloading user info')
383 resource
= mobj
.group('rsrc') or 'all'
384 base_url
= self
._BASE
_URL
_MAP
[resource
] % user
['id']
388 'client_id': self
._CLIENT
_ID
,
389 'linked_partitioning': '1',
392 query
= COMMON_QUERY
.copy()
395 next_href
= base_url
+ '?' + compat_urllib_parse_urlencode(query
)
398 for i
in itertools
.count():
399 response
= self
._download
_json
(
400 next_href
, uploader
, 'Downloading track page %s' % (i
+ 1))
402 collection
= response
['collection']
406 def resolve_permalink_url(candidates
):
407 for cand
in candidates
:
408 if isinstance(cand
, dict):
409 permalink_url
= cand
.get('permalink_url')
410 if permalink_url
and permalink_url
.startswith('http'):
414 permalink_url
= resolve_permalink_url((e
, e
.get('track'), e
.get('playlist')))
416 entries
.append(self
.url_result(permalink_url
))
418 next_href
= response
.get('next_href')
422 parsed_next_href
= compat_urlparse
.urlparse(response
['next_href'])
423 qs
= compat_urlparse
.parse_qs(parsed_next_href
.query
)
424 qs
.update(COMMON_QUERY
)
425 next_href
= compat_urlparse
.urlunparse(
426 parsed_next_href
._replace
(query
=compat_urllib_parse_urlencode(qs
, True)))
430 'id': compat_str(user
['id']),
431 'title': '%s (%s)' % (user
['username'], self
._TITLE
_MAP
[resource
]),
436 class SoundcloudPlaylistIE(SoundcloudIE
):
437 _VALID_URL
= r
'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
438 IE_NAME
= 'soundcloud:playlist'
440 'url': 'http://api.soundcloud.com/playlists/4110309',
443 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
444 'description': 're:.*?TILT Brass - Bowery Poetry Club',
449 def _real_extract(self
, url
):
450 mobj
= re
.match(self
._VALID
_URL
, url
)
451 playlist_id
= mobj
.group('id')
452 base_url
= '%s//api.soundcloud.com/playlists/%s.json?' % (self
.http_scheme(), playlist_id
)
455 'client_id': self
._CLIENT
_ID
,
457 token
= mobj
.group('token')
460 data_dict
['secret_token'] = token
462 data
= compat_urllib_parse_urlencode(data_dict
)
463 data
= self
._download
_json
(
464 base_url
+ data
, playlist_id
, 'Downloading playlist')
466 entries
= [self
.url_result(track
['permalink_url'], 'Soundcloud') for track
in data
['tracks']]
471 'title': data
.get('title'),
472 'description': data
.get('description'),
477 class SoundcloudSearchIE(SearchInfoExtractor
, SoundcloudIE
):
478 IE_NAME
= 'soundcloud:search'
479 IE_DESC
= 'Soundcloud search'
480 _MAX_RESULTS
= float('inf')
482 'url': 'scsearch15:post-avant jazzcore',
484 'title': 'post-avant jazzcore',
486 'playlist_count': 15,
489 _SEARCH_KEY
= 'scsearch'
490 _MAX_RESULTS_PER_PAGE
= 200
491 _DEFAULT_RESULTS_PER_PAGE
= 50
492 _API_V2_BASE
= 'https://api-v2.soundcloud.com'
494 def _get_collection(self
, endpoint
, collection_id
, **query
):
496 query
.get('limit', self
._DEFAULT
_RESULTS
_PER
_PAGE
),
497 self
._MAX
_RESULTS
_PER
_PAGE
)
498 query
['limit'] = limit
499 query
['client_id'] = self
._CLIENT
_ID
500 query
['linked_partitioning'] = '1'
502 data
= compat_urllib_parse_urlencode(query
)
503 next_url
= '{0}{1}?{2}'.format(self
._API
_V
2_BASE
, endpoint
, data
)
505 collected_results
= 0
507 for i
in itertools
.count(1):
508 response
= self
._download
_json
(
509 next_url
, collection_id
, 'Downloading page {0}'.format(i
),
510 'Unable to download API page')
512 collection
= response
.get('collection', [])
516 collection
= list(filter(bool, collection
))
517 collected_results
+= len(collection
)
519 for item
in collection
:
520 yield self
.url_result(item
['uri'], SoundcloudIE
.ie_key())
522 if not collection
or collected_results
>= limit
:
525 next_url
= response
.get('next_href')
529 def _get_n_results(self
, query
, n
):
530 tracks
= self
._get
_collection
('/search/tracks', query
, limit
=n
, q
=query
)
531 return self
.playlist_result(tracks
, playlist_title
=query
)