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'
123 def _extract_urls(webpage
):
124 return [m
.group('url') for m
in re
.finditer(
125 r
'<iframe[^>]+src=(["\'])(?P
<url
>(?
:https?
://)?
(?
:w\
.)?soundcloud\
.com
/player
.+?
)\
1',
128 def report_resolve(self, video_id):
129 """Report information extraction."""
130 self.to_screen('%s: Resolving
id' % video_id)
133 def _resolv_url(cls, url):
134 return 'http
://api
.soundcloud
.com
/resolve
.json?url
=' + url + '&client_id
=' + cls._CLIENT_ID
136 def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
137 track_id = compat_str(info['id'])
138 name = full_title or track_id
140 self.report_extraction(name)
142 thumbnail = info['artwork_url
']
143 if thumbnail is not None:
144 thumbnail = thumbnail.replace('-large
', '-t500x500
')
148 'uploader
': info['user
']['username
'],
149 'upload_date
': unified_strdate(info['created_at
']),
150 'title
': info['title
'],
151 'description
': info['description
'],
152 'thumbnail
': thumbnail,
153 'duration
': int_or_none(info.get('duration
'), 1000),
154 'webpage_url
': info.get('permalink_url
'),
157 if info.get('downloadable
', False):
158 # We can build a direct link to the song
160 'https
://api
.soundcloud
.com
/tracks
/{0}
/download?client_id
={1}
'.format(
161 track_id, self._CLIENT_ID))
163 'format_id
': 'download
',
164 'ext
': info.get('original_format
', 'mp3
'),
170 # We have to retrieve the url
171 streams_url = ('http
://api
.soundcloud
.com
/i1
/tracks
/{0}
/streams?
'
172 'client_id
={1}
&secret_token
={2}
'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
173 format_dict = self._download_json(
175 track_id, 'Downloading track url
')
177 for key, stream_url in format_dict.items():
178 if key.startswith('http
'):
185 elif key.startswith('rtmp
'):
186 # The url doesn't have an rtmp app
, we have to extract the playpath
187 url
, path
= stream_url
.split('mp3:', 1)
191 'play_path': 'mp3:' + path
,
197 # We fallback to the stream_url in the original info, this
198 # cannot be always used, sometimes it can give an HTTP 404 error
200 'format_id': 'fallback',
201 'url': info
['stream_url'] + '?client_id=' + self
._CLIENT
_ID
,
207 if f
['format_id'].startswith('http'):
208 f
['protocol'] = 'http'
209 if f
['format_id'].startswith('rtmp'):
210 f
['protocol'] = 'rtmp'
212 self
._check
_formats
(formats
, track_id
)
213 self
._sort
_formats
(formats
)
214 result
['formats'] = formats
218 def _real_extract(self
, url
):
219 mobj
= re
.match(self
._VALID
_URL
, url
, flags
=re
.VERBOSE
)
221 raise ExtractorError('Invalid URL: %s' % url
)
223 track_id
= mobj
.group('track_id')
225 if track_id
is not None:
226 info_json_url
= 'http://api.soundcloud.com/tracks/' + track_id
+ '.json?client_id=' + self
._CLIENT
_ID
227 full_title
= track_id
228 token
= mobj
.group('secret_token')
230 info_json_url
+= '&secret_token=' + token
231 elif mobj
.group('player'):
232 query
= compat_urlparse
.parse_qs(compat_urlparse
.urlparse(url
).query
)
233 real_url
= query
['url'][0]
234 # If the token is in the query of the original url we have to
236 if 'secret_token' in query
:
237 real_url
+= '?secret_token=' + query
['secret_token'][0]
238 return self
.url_result(real_url
)
240 # extract uploader (which is in the url)
241 uploader
= mobj
.group('uploader')
242 # extract simple title (uploader + slug of song title)
243 slug_title
= mobj
.group('title')
244 token
= mobj
.group('token')
245 full_title
= resolve_title
= '%s/%s' % (uploader
, slug_title
)
247 resolve_title
+= '/%s' % token
249 self
.report_resolve(full_title
)
251 url
= 'http://soundcloud.com/%s' % resolve_title
252 info_json_url
= self
._resolv
_url
(url
)
253 info
= self
._download
_json
(info_json_url
, full_title
, 'Downloading info JSON')
255 return self
._extract
_info
_dict
(info
, full_title
, secret_token
=token
)
258 class SoundcloudSetIE(SoundcloudIE
):
259 _VALID_URL
= r
'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
260 IE_NAME
= 'soundcloud:set'
262 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
265 'title': 'The Royal Concept EP',
267 'playlist_mincount': 6,
270 def _real_extract(self
, url
):
271 mobj
= re
.match(self
._VALID
_URL
, url
)
273 # extract uploader (which is in the url)
274 uploader
= mobj
.group('uploader')
275 # extract simple title (uploader + slug of song title)
276 slug_title
= mobj
.group('slug_title')
277 full_title
= '%s/sets/%s' % (uploader
, slug_title
)
278 url
= 'http://soundcloud.com/%s/sets/%s' % (uploader
, slug_title
)
280 token
= mobj
.group('token')
282 full_title
+= '/' + token
285 self
.report_resolve(full_title
)
287 resolv_url
= self
._resolv
_url
(url
)
288 info
= self
._download
_json
(resolv_url
, full_title
)
291 msgs
= (compat_str(err
['error_message']) for err
in info
['errors'])
292 raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs
))
294 entries
= [self
.url_result(track
['permalink_url'], 'Soundcloud') for track
in info
['tracks']]
299 'id': '%s' % info
['id'],
300 'title': info
['title'],
304 class SoundcloudUserIE(SoundcloudIE
):
305 _VALID_URL
= r
'''(?x)
307 (?:(?:www|m)\.)?soundcloud\.com/
310 (?P<rsrc>tracks|sets|reposts|likes|spotlight)
314 IE_NAME
= 'soundcloud:user'
316 'url': 'https://soundcloud.com/the-akashic-chronicler',
319 'title': 'The Akashic Chronicler (All)',
321 'playlist_mincount': 111,
323 'url': 'https://soundcloud.com/the-akashic-chronicler/tracks',
326 'title': 'The Akashic Chronicler (Tracks)',
328 'playlist_mincount': 50,
330 'url': 'https://soundcloud.com/the-akashic-chronicler/sets',
333 'title': 'The Akashic Chronicler (Playlists)',
335 'playlist_mincount': 3,
337 'url': 'https://soundcloud.com/the-akashic-chronicler/reposts',
340 'title': 'The Akashic Chronicler (Reposts)',
342 'playlist_mincount': 7,
344 'url': 'https://soundcloud.com/the-akashic-chronicler/likes',
347 'title': 'The Akashic Chronicler (Likes)',
349 'playlist_mincount': 321,
351 'url': 'https://soundcloud.com/grynpyret/spotlight',
354 'title': 'Grynpyret (Spotlight)',
356 'playlist_mincount': 1,
359 _API_BASE
= 'https://api.soundcloud.com'
360 _API_V2_BASE
= 'https://api-v2.soundcloud.com'
363 'all': '%s/profile/soundcloud:users:%%s' % _API_V2_BASE
,
364 'tracks': '%s/users/%%s/tracks' % _API_BASE
,
365 'sets': '%s/users/%%s/playlists' % _API_V2_BASE
,
366 'reposts': '%s/profile/soundcloud:users:%%s/reposts' % _API_V2_BASE
,
367 'likes': '%s/users/%%s/likes' % _API_V2_BASE
,
368 'spotlight': '%s/users/%%s/spotlight' % _API_V2_BASE
,
375 'reposts': 'Reposts',
377 'spotlight': 'Spotlight',
380 def _real_extract(self
, url
):
381 mobj
= re
.match(self
._VALID
_URL
, url
)
382 uploader
= mobj
.group('user')
384 url
= 'http://soundcloud.com/%s/' % uploader
385 resolv_url
= self
._resolv
_url
(url
)
386 user
= self
._download
_json
(
387 resolv_url
, uploader
, 'Downloading user info')
389 resource
= mobj
.group('rsrc') or 'all'
390 base_url
= self
._BASE
_URL
_MAP
[resource
] % user
['id']
394 'client_id': self
._CLIENT
_ID
,
395 'linked_partitioning': '1',
398 query
= COMMON_QUERY
.copy()
401 next_href
= base_url
+ '?' + compat_urllib_parse_urlencode(query
)
404 for i
in itertools
.count():
405 response
= self
._download
_json
(
406 next_href
, uploader
, 'Downloading track page %s' % (i
+ 1))
408 collection
= response
['collection']
412 def resolve_permalink_url(candidates
):
413 for cand
in candidates
:
414 if isinstance(cand
, dict):
415 permalink_url
= cand
.get('permalink_url')
416 if permalink_url
and permalink_url
.startswith('http'):
420 permalink_url
= resolve_permalink_url((e
, e
.get('track'), e
.get('playlist')))
422 entries
.append(self
.url_result(permalink_url
))
424 next_href
= response
.get('next_href')
428 parsed_next_href
= compat_urlparse
.urlparse(response
['next_href'])
429 qs
= compat_urlparse
.parse_qs(parsed_next_href
.query
)
430 qs
.update(COMMON_QUERY
)
431 next_href
= compat_urlparse
.urlunparse(
432 parsed_next_href
._replace
(query
=compat_urllib_parse_urlencode(qs
, True)))
436 'id': compat_str(user
['id']),
437 'title': '%s (%s)' % (user
['username'], self
._TITLE
_MAP
[resource
]),
442 class SoundcloudPlaylistIE(SoundcloudIE
):
443 _VALID_URL
= r
'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
444 IE_NAME
= 'soundcloud:playlist'
446 'url': 'http://api.soundcloud.com/playlists/4110309',
449 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
450 'description': 're:.*?TILT Brass - Bowery Poetry Club',
455 def _real_extract(self
, url
):
456 mobj
= re
.match(self
._VALID
_URL
, url
)
457 playlist_id
= mobj
.group('id')
458 base_url
= '%s//api.soundcloud.com/playlists/%s.json?' % (self
.http_scheme(), playlist_id
)
461 'client_id': self
._CLIENT
_ID
,
463 token
= mobj
.group('token')
466 data_dict
['secret_token'] = token
468 data
= compat_urllib_parse_urlencode(data_dict
)
469 data
= self
._download
_json
(
470 base_url
+ data
, playlist_id
, 'Downloading playlist')
472 entries
= [self
.url_result(track
['permalink_url'], 'Soundcloud') for track
in data
['tracks']]
477 'title': data
.get('title'),
478 'description': data
.get('description'),
483 class SoundcloudSearchIE(SearchInfoExtractor
, SoundcloudIE
):
484 IE_NAME
= 'soundcloud:search'
485 IE_DESC
= 'Soundcloud search'
486 _MAX_RESULTS
= float('inf')
488 'url': 'scsearch15:post-avant jazzcore',
490 'title': 'post-avant jazzcore',
492 'playlist_count': 15,
495 _SEARCH_KEY
= 'scsearch'
496 _MAX_RESULTS_PER_PAGE
= 200
497 _DEFAULT_RESULTS_PER_PAGE
= 50
498 _API_V2_BASE
= 'https://api-v2.soundcloud.com'
500 def _get_collection(self
, endpoint
, collection_id
, **query
):
502 query
.get('limit', self
._DEFAULT
_RESULTS
_PER
_PAGE
),
503 self
._MAX
_RESULTS
_PER
_PAGE
)
504 query
['limit'] = limit
505 query
['client_id'] = self
._CLIENT
_ID
506 query
['linked_partitioning'] = '1'
508 data
= compat_urllib_parse_urlencode(query
)
509 next_url
= '{0}{1}?{2}'.format(self
._API
_V
2_BASE
, endpoint
, data
)
511 collected_results
= 0
513 for i
in itertools
.count(1):
514 response
= self
._download
_json
(
515 next_url
, collection_id
, 'Downloading page {0}'.format(i
),
516 'Unable to download API page')
518 collection
= response
.get('collection', [])
522 collection
= list(filter(bool, collection
))
523 collected_results
+= len(collection
)
525 for item
in collection
:
526 yield self
.url_result(item
['uri'], SoundcloudIE
.ie_key())
528 if not collection
or collected_results
>= limit
:
531 next_url
= response
.get('next_href')
535 def _get_n_results(self
, query
, n
):
536 tracks
= self
._get
_collection
('/search/tracks', query
, limit
=n
, q
=query
)
537 return self
.playlist_result(tracks
, playlist_title
=query
)