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',
56 'license': 'all-rights-reserved',
61 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
65 'title': 'Goldrushed',
66 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
67 'uploader': 'The Royal Concept',
68 'upload_date': '20120521',
70 'license': 'all-rights-reserved',
74 'skip_download': True,
79 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
80 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
84 'title': 'Youtube - Dl Test Video \'\' Ä↭',
85 'uploader': 'jaimeMF',
86 'description': 'test chars: \"\'/\\ä↭',
87 'upload_date': '20131209',
89 'license': 'all-rights-reserved',
92 # private link (alt format)
94 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
95 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
99 'title': 'Youtube - Dl Test Video \'\' Ä↭',
100 'uploader': 'jaimeMF',
101 'description': 'test chars: \"\'/\\ä↭',
102 'upload_date': '20131209',
104 'license': 'all-rights-reserved',
109 'url': 'https://soundcloud.com/oddsamples/bus-brakes',
110 'md5': '7624f2351f8a3b2e7cd51522496e7631',
114 'title': 'Bus Brakes',
115 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66',
116 'uploader': 'oddsamples',
117 'upload_date': '20140109',
119 'license': 'cc-by-sa',
124 _CLIENT_ID
= '2t9loNQH90kzJcsFCODdigxfp325aq4z'
125 _IPHONE_CLIENT_ID
= '376f225bf427445fc4bfb6b99b72e0bf'
128 def _extract_urls(webpage
):
129 return [m
.group('url') for m
in re
.finditer(
130 r
'<iframe[^>]+src=(["\'])(?P
<url
>(?
:https?
://)?
(?
:w\
.)?soundcloud\
.com
/player
.+?
)\
1',
133 def report_resolve(self, video_id):
134 """Report information extraction."""
135 self.to_screen('%s: Resolving
id' % video_id)
138 def _resolv_url(cls, url):
139 return 'http
://api
.soundcloud
.com
/resolve
.json?url
=' + url + '&client_id
=' + cls._CLIENT_ID
141 def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
142 track_id = compat_str(info['id'])
143 name = full_title or track_id
145 self.report_extraction(name)
146 thumbnail = info.get('artwork_url
')
147 if isinstance(thumbnail, compat_str):
148 thumbnail = thumbnail.replace('-large
', '-t500x500
')
152 'uploader
': info.get('user
', {}).get('username
'),
153 'upload_date
': unified_strdate(info.get('created_at
')),
154 'title
': info['title
'],
155 'description
': info.get('description
'),
156 'thumbnail
': thumbnail,
157 'duration
': int_or_none(info.get('duration
'), 1000),
158 'webpage_url
': info.get('permalink_url
'),
159 'license
': info.get('license
'),
162 if info.get('downloadable
', False):
163 # We can build a direct link to the song
165 'https
://api
.soundcloud
.com
/tracks
/{0}
/download?client_id
={1}
'.format(
166 track_id, self._CLIENT_ID))
168 'format_id
': 'download
',
169 'ext
': info.get('original_format
', 'mp3
'),
175 # We have to retrieve the url
176 format_dict = self._download_json(
177 'http
://api
.soundcloud
.com
/i1
/tracks
/%s/streams
' % track_id,
178 track_id, 'Downloading track url
', query={
179 'client_id
': self._CLIENT_ID,
180 'secret_token
': secret_token,
183 for key, stream_url in format_dict.items():
184 abr = int_or_none(self._search_regex(
185 r'_(\d
+)_url
', key, 'audio bitrate
', default=None))
186 if key.startswith('http
'):
192 elif key.startswith('rtmp
'):
193 # The url doesn't have an rtmp app
, we have to extract the playpath
194 url
, path
= stream_url
.split('mp3:', 1)
198 'play_path': 'mp3:' + path
,
201 elif key
.startswith('hls'):
202 stream_formats
= self
._extract
_m
3u8_formats
(
203 stream_url
, track_id
, 'mp3', entry_protocol
='m3u8_native',
204 m3u8_id
=key
, fatal
=False)
208 for f
in stream_formats
:
211 formats
.extend(stream_formats
)
214 # We fallback to the stream_url in the original info, this
215 # cannot be always used, sometimes it can give an HTTP 404 error
217 'format_id': 'fallback',
218 'url': info
['stream_url'] + '?client_id=' + self
._CLIENT
_ID
,
225 self
._check
_formats
(formats
, track_id
)
226 self
._sort
_formats
(formats
)
227 result
['formats'] = formats
231 def _real_extract(self
, url
):
232 mobj
= re
.match(self
._VALID
_URL
, url
, flags
=re
.VERBOSE
)
234 raise ExtractorError('Invalid URL: %s' % url
)
236 track_id
= mobj
.group('track_id')
238 if track_id
is not None:
239 info_json_url
= 'http://api.soundcloud.com/tracks/' + track_id
+ '.json?client_id=' + self
._CLIENT
_ID
240 full_title
= track_id
241 token
= mobj
.group('secret_token')
243 info_json_url
+= '&secret_token=' + token
244 elif mobj
.group('player'):
245 query
= compat_urlparse
.parse_qs(compat_urlparse
.urlparse(url
).query
)
246 real_url
= query
['url'][0]
247 # If the token is in the query of the original url we have to
249 if 'secret_token' in query
:
250 real_url
+= '?secret_token=' + query
['secret_token'][0]
251 return self
.url_result(real_url
)
253 # extract uploader (which is in the url)
254 uploader
= mobj
.group('uploader')
255 # extract simple title (uploader + slug of song title)
256 slug_title
= mobj
.group('title')
257 token
= mobj
.group('token')
258 full_title
= resolve_title
= '%s/%s' % (uploader
, slug_title
)
260 resolve_title
+= '/%s' % token
262 self
.report_resolve(full_title
)
264 url
= 'http://soundcloud.com/%s' % resolve_title
265 info_json_url
= self
._resolv
_url
(url
)
266 info
= self
._download
_json
(info_json_url
, full_title
, 'Downloading info JSON')
268 return self
._extract
_info
_dict
(info
, full_title
, secret_token
=token
)
271 class SoundcloudPlaylistBaseIE(SoundcloudIE
):
274 return compat_str(e
['id']) if e
.get('id') else None
276 def _extract_track_entries(self
, tracks
):
279 track
['permalink_url'], SoundcloudIE
.ie_key(),
280 video_id
=self
._extract
_id
(track
))
281 for track
in tracks
if track
.get('permalink_url')]
284 class SoundcloudSetIE(SoundcloudPlaylistBaseIE
):
285 _VALID_URL
= r
'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
286 IE_NAME
= 'soundcloud:set'
288 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
291 'title': 'The Royal Concept EP',
293 'playlist_mincount': 6,
295 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
296 'only_matching': True,
299 def _real_extract(self
, url
):
300 mobj
= re
.match(self
._VALID
_URL
, url
)
302 # extract uploader (which is in the url)
303 uploader
= mobj
.group('uploader')
304 # extract simple title (uploader + slug of song title)
305 slug_title
= mobj
.group('slug_title')
306 full_title
= '%s/sets/%s' % (uploader
, slug_title
)
307 url
= 'http://soundcloud.com/%s/sets/%s' % (uploader
, slug_title
)
309 token
= mobj
.group('token')
311 full_title
+= '/' + token
314 self
.report_resolve(full_title
)
316 resolv_url
= self
._resolv
_url
(url
)
317 info
= self
._download
_json
(resolv_url
, full_title
)
320 msgs
= (compat_str(err
['error_message']) for err
in info
['errors'])
321 raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs
))
323 entries
= self
._extract
_track
_entries
(info
['tracks'])
328 'id': '%s' % info
['id'],
329 'title': info
['title'],
333 class SoundcloudUserIE(SoundcloudPlaylistBaseIE
):
334 _VALID_URL
= r
'''(?x)
336 (?:(?:www|m)\.)?soundcloud\.com/
339 (?P<rsrc>tracks|sets|reposts|likes|spotlight)
343 IE_NAME
= 'soundcloud:user'
345 'url': 'https://soundcloud.com/the-akashic-chronicler',
348 'title': 'The Akashic Chronicler (All)',
350 'playlist_mincount': 74,
352 'url': 'https://soundcloud.com/the-akashic-chronicler/tracks',
355 'title': 'The Akashic Chronicler (Tracks)',
357 'playlist_mincount': 37,
359 'url': 'https://soundcloud.com/the-akashic-chronicler/sets',
362 'title': 'The Akashic Chronicler (Playlists)',
364 'playlist_mincount': 2,
366 'url': 'https://soundcloud.com/the-akashic-chronicler/reposts',
369 'title': 'The Akashic Chronicler (Reposts)',
371 'playlist_mincount': 7,
373 'url': 'https://soundcloud.com/the-akashic-chronicler/likes',
376 'title': 'The Akashic Chronicler (Likes)',
378 'playlist_mincount': 321,
380 'url': 'https://soundcloud.com/grynpyret/spotlight',
383 'title': 'GRYNPYRET (Spotlight)',
385 'playlist_mincount': 1,
388 _API_BASE
= 'https://api.soundcloud.com'
389 _API_V2_BASE
= 'https://api-v2.soundcloud.com'
392 'all': '%s/profile/soundcloud:users:%%s' % _API_V2_BASE
,
393 'tracks': '%s/users/%%s/tracks' % _API_BASE
,
394 'sets': '%s/users/%%s/playlists' % _API_V2_BASE
,
395 'reposts': '%s/profile/soundcloud:users:%%s/reposts' % _API_V2_BASE
,
396 'likes': '%s/users/%%s/likes' % _API_V2_BASE
,
397 'spotlight': '%s/users/%%s/spotlight' % _API_V2_BASE
,
404 'reposts': 'Reposts',
406 'spotlight': 'Spotlight',
409 def _real_extract(self
, url
):
410 mobj
= re
.match(self
._VALID
_URL
, url
)
411 uploader
= mobj
.group('user')
413 url
= 'http://soundcloud.com/%s/' % uploader
414 resolv_url
= self
._resolv
_url
(url
)
415 user
= self
._download
_json
(
416 resolv_url
, uploader
, 'Downloading user info')
418 resource
= mobj
.group('rsrc') or 'all'
419 base_url
= self
._BASE
_URL
_MAP
[resource
] % user
['id']
423 'client_id': self
._CLIENT
_ID
,
424 'linked_partitioning': '1',
427 query
= COMMON_QUERY
.copy()
430 next_href
= base_url
+ '?' + compat_urllib_parse_urlencode(query
)
433 for i
in itertools
.count():
434 response
= self
._download
_json
(
435 next_href
, uploader
, 'Downloading track page %s' % (i
+ 1))
437 collection
= response
['collection']
441 def resolve_permalink_url(candidates
):
442 for cand
in candidates
:
443 if isinstance(cand
, dict):
444 permalink_url
= cand
.get('permalink_url')
445 entry_id
= self
._extract
_id
(cand
)
446 if permalink_url
and permalink_url
.startswith('http'):
447 return permalink_url
, entry_id
450 permalink_url
, entry_id
= resolve_permalink_url((e
, e
.get('track'), e
.get('playlist')))
452 entries
.append(self
.url_result(permalink_url
, video_id
=entry_id
))
454 next_href
= response
.get('next_href')
458 parsed_next_href
= compat_urlparse
.urlparse(response
['next_href'])
459 qs
= compat_urlparse
.parse_qs(parsed_next_href
.query
)
460 qs
.update(COMMON_QUERY
)
461 next_href
= compat_urlparse
.urlunparse(
462 parsed_next_href
._replace
(query
=compat_urllib_parse_urlencode(qs
, True)))
466 'id': compat_str(user
['id']),
467 'title': '%s (%s)' % (user
['username'], self
._TITLE
_MAP
[resource
]),
472 class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE
):
473 _VALID_URL
= r
'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
474 IE_NAME
= 'soundcloud:playlist'
476 'url': 'http://api.soundcloud.com/playlists/4110309',
479 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
480 'description': 're:.*?TILT Brass - Bowery Poetry Club',
485 def _real_extract(self
, url
):
486 mobj
= re
.match(self
._VALID
_URL
, url
)
487 playlist_id
= mobj
.group('id')
488 base_url
= '%s//api.soundcloud.com/playlists/%s.json?' % (self
.http_scheme(), playlist_id
)
491 'client_id': self
._CLIENT
_ID
,
493 token
= mobj
.group('token')
496 data_dict
['secret_token'] = token
498 data
= compat_urllib_parse_urlencode(data_dict
)
499 data
= self
._download
_json
(
500 base_url
+ data
, playlist_id
, 'Downloading playlist')
502 entries
= self
._extract
_track
_entries
(data
['tracks'])
507 'title': data
.get('title'),
508 'description': data
.get('description'),
513 class SoundcloudSearchIE(SearchInfoExtractor
, SoundcloudIE
):
514 IE_NAME
= 'soundcloud:search'
515 IE_DESC
= 'Soundcloud search'
516 _MAX_RESULTS
= float('inf')
518 'url': 'scsearch15:post-avant jazzcore',
520 'title': 'post-avant jazzcore',
522 'playlist_count': 15,
525 _SEARCH_KEY
= 'scsearch'
526 _MAX_RESULTS_PER_PAGE
= 200
527 _DEFAULT_RESULTS_PER_PAGE
= 50
528 _API_V2_BASE
= 'https://api-v2.soundcloud.com'
530 def _get_collection(self
, endpoint
, collection_id
, **query
):
532 query
.get('limit', self
._DEFAULT
_RESULTS
_PER
_PAGE
),
533 self
._MAX
_RESULTS
_PER
_PAGE
)
534 query
['limit'] = limit
535 query
['client_id'] = self
._CLIENT
_ID
536 query
['linked_partitioning'] = '1'
538 data
= compat_urllib_parse_urlencode(query
)
539 next_url
= '{0}{1}?{2}'.format(self
._API
_V
2_BASE
, endpoint
, data
)
541 collected_results
= 0
543 for i
in itertools
.count(1):
544 response
= self
._download
_json
(
545 next_url
, collection_id
, 'Downloading page {0}'.format(i
),
546 'Unable to download API page')
548 collection
= response
.get('collection', [])
552 collection
= list(filter(bool, collection
))
553 collected_results
+= len(collection
)
555 for item
in collection
:
556 yield self
.url_result(item
['uri'], SoundcloudIE
.ie_key())
558 if not collection
or collected_results
>= limit
:
561 next_url
= response
.get('next_href')
565 def _get_n_results(self
, query
, n
):
566 tracks
= self
._get
_collection
('/search/tracks', query
, limit
=n
, q
=query
)
567 return self
.playlist_result(tracks
, playlist_title
=query
)