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
= 'fDoItMDbsbZz8dY16ZzARCZmzgHBPotA'
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 streams_url = ('http
://api
.soundcloud
.com
/i1
/tracks
/{0}
/streams?
'
177 'client_id
={1}
&secret_token
={2}
'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
178 format_dict = self._download_json(
180 track_id, 'Downloading track url
')
182 for key, stream_url in format_dict.items():
183 if key.startswith('http
'):
190 elif key.startswith('rtmp
'):
191 # The url doesn't have an rtmp app
, we have to extract the playpath
192 url
, path
= stream_url
.split('mp3:', 1)
196 'play_path': 'mp3:' + path
,
202 # We fallback to the stream_url in the original info, this
203 # cannot be always used, sometimes it can give an HTTP 404 error
205 'format_id': 'fallback',
206 'url': info
['stream_url'] + '?client_id=' + self
._CLIENT
_ID
,
212 if f
['format_id'].startswith('http'):
213 f
['protocol'] = 'http'
214 if f
['format_id'].startswith('rtmp'):
215 f
['protocol'] = 'rtmp'
217 self
._check
_formats
(formats
, track_id
)
218 self
._sort
_formats
(formats
)
219 result
['formats'] = formats
223 def _real_extract(self
, url
):
224 mobj
= re
.match(self
._VALID
_URL
, url
, flags
=re
.VERBOSE
)
226 raise ExtractorError('Invalid URL: %s' % url
)
228 track_id
= mobj
.group('track_id')
230 if track_id
is not None:
231 info_json_url
= 'http://api.soundcloud.com/tracks/' + track_id
+ '.json?client_id=' + self
._CLIENT
_ID
232 full_title
= track_id
233 token
= mobj
.group('secret_token')
235 info_json_url
+= '&secret_token=' + token
236 elif mobj
.group('player'):
237 query
= compat_urlparse
.parse_qs(compat_urlparse
.urlparse(url
).query
)
238 real_url
= query
['url'][0]
239 # If the token is in the query of the original url we have to
241 if 'secret_token' in query
:
242 real_url
+= '?secret_token=' + query
['secret_token'][0]
243 return self
.url_result(real_url
)
245 # extract uploader (which is in the url)
246 uploader
= mobj
.group('uploader')
247 # extract simple title (uploader + slug of song title)
248 slug_title
= mobj
.group('title')
249 token
= mobj
.group('token')
250 full_title
= resolve_title
= '%s/%s' % (uploader
, slug_title
)
252 resolve_title
+= '/%s' % token
254 self
.report_resolve(full_title
)
256 url
= 'http://soundcloud.com/%s' % resolve_title
257 info_json_url
= self
._resolv
_url
(url
)
258 info
= self
._download
_json
(info_json_url
, full_title
, 'Downloading info JSON')
260 return self
._extract
_info
_dict
(info
, full_title
, secret_token
=token
)
263 class SoundcloudPlaylistBaseIE(SoundcloudIE
):
266 return compat_str(e
['id']) if e
.get('id') else None
268 def _extract_track_entries(self
, tracks
):
271 track
['permalink_url'], SoundcloudIE
.ie_key(),
272 video_id
=self
._extract
_id
(track
))
273 for track
in tracks
if track
.get('permalink_url')]
276 class SoundcloudSetIE(SoundcloudPlaylistBaseIE
):
277 _VALID_URL
= r
'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
278 IE_NAME
= 'soundcloud:set'
280 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
283 'title': 'The Royal Concept EP',
285 'playlist_mincount': 6,
287 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
288 'only_matching': True,
291 def _real_extract(self
, url
):
292 mobj
= re
.match(self
._VALID
_URL
, url
)
294 # extract uploader (which is in the url)
295 uploader
= mobj
.group('uploader')
296 # extract simple title (uploader + slug of song title)
297 slug_title
= mobj
.group('slug_title')
298 full_title
= '%s/sets/%s' % (uploader
, slug_title
)
299 url
= 'http://soundcloud.com/%s/sets/%s' % (uploader
, slug_title
)
301 token
= mobj
.group('token')
303 full_title
+= '/' + token
306 self
.report_resolve(full_title
)
308 resolv_url
= self
._resolv
_url
(url
)
309 info
= self
._download
_json
(resolv_url
, full_title
)
312 msgs
= (compat_str(err
['error_message']) for err
in info
['errors'])
313 raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs
))
315 entries
= self
._extract
_track
_entries
(info
['tracks'])
320 'id': '%s' % info
['id'],
321 'title': info
['title'],
325 class SoundcloudUserIE(SoundcloudPlaylistBaseIE
):
326 _VALID_URL
= r
'''(?x)
328 (?:(?:www|m)\.)?soundcloud\.com/
331 (?P<rsrc>tracks|sets|reposts|likes|spotlight)
335 IE_NAME
= 'soundcloud:user'
337 'url': 'https://soundcloud.com/the-akashic-chronicler',
340 'title': 'The Akashic Chronicler (All)',
342 'playlist_mincount': 74,
344 'url': 'https://soundcloud.com/the-akashic-chronicler/tracks',
347 'title': 'The Akashic Chronicler (Tracks)',
349 'playlist_mincount': 37,
351 'url': 'https://soundcloud.com/the-akashic-chronicler/sets',
354 'title': 'The Akashic Chronicler (Playlists)',
356 'playlist_mincount': 2,
358 'url': 'https://soundcloud.com/the-akashic-chronicler/reposts',
361 'title': 'The Akashic Chronicler (Reposts)',
363 'playlist_mincount': 7,
365 'url': 'https://soundcloud.com/the-akashic-chronicler/likes',
368 'title': 'The Akashic Chronicler (Likes)',
370 'playlist_mincount': 321,
372 'url': 'https://soundcloud.com/grynpyret/spotlight',
375 'title': 'GRYNPYRET (Spotlight)',
377 'playlist_mincount': 1,
380 _API_BASE
= 'https://api.soundcloud.com'
381 _API_V2_BASE
= 'https://api-v2.soundcloud.com'
384 'all': '%s/profile/soundcloud:users:%%s' % _API_V2_BASE
,
385 'tracks': '%s/users/%%s/tracks' % _API_BASE
,
386 'sets': '%s/users/%%s/playlists' % _API_V2_BASE
,
387 'reposts': '%s/profile/soundcloud:users:%%s/reposts' % _API_V2_BASE
,
388 'likes': '%s/users/%%s/likes' % _API_V2_BASE
,
389 'spotlight': '%s/users/%%s/spotlight' % _API_V2_BASE
,
396 'reposts': 'Reposts',
398 'spotlight': 'Spotlight',
401 def _real_extract(self
, url
):
402 mobj
= re
.match(self
._VALID
_URL
, url
)
403 uploader
= mobj
.group('user')
405 url
= 'http://soundcloud.com/%s/' % uploader
406 resolv_url
= self
._resolv
_url
(url
)
407 user
= self
._download
_json
(
408 resolv_url
, uploader
, 'Downloading user info')
410 resource
= mobj
.group('rsrc') or 'all'
411 base_url
= self
._BASE
_URL
_MAP
[resource
] % user
['id']
415 'client_id': self
._CLIENT
_ID
,
416 'linked_partitioning': '1',
419 query
= COMMON_QUERY
.copy()
422 next_href
= base_url
+ '?' + compat_urllib_parse_urlencode(query
)
425 for i
in itertools
.count():
426 response
= self
._download
_json
(
427 next_href
, uploader
, 'Downloading track page %s' % (i
+ 1))
429 collection
= response
['collection']
433 def resolve_permalink_url(candidates
):
434 for cand
in candidates
:
435 if isinstance(cand
, dict):
436 permalink_url
= cand
.get('permalink_url')
437 entry_id
= self
._extract
_id
(cand
)
438 if permalink_url
and permalink_url
.startswith('http'):
439 return permalink_url
, entry_id
442 permalink_url
, entry_id
= resolve_permalink_url((e
, e
.get('track'), e
.get('playlist')))
444 entries
.append(self
.url_result(permalink_url
, video_id
=entry_id
))
446 next_href
= response
.get('next_href')
450 parsed_next_href
= compat_urlparse
.urlparse(response
['next_href'])
451 qs
= compat_urlparse
.parse_qs(parsed_next_href
.query
)
452 qs
.update(COMMON_QUERY
)
453 next_href
= compat_urlparse
.urlunparse(
454 parsed_next_href
._replace
(query
=compat_urllib_parse_urlencode(qs
, True)))
458 'id': compat_str(user
['id']),
459 'title': '%s (%s)' % (user
['username'], self
._TITLE
_MAP
[resource
]),
464 class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE
):
465 _VALID_URL
= r
'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
466 IE_NAME
= 'soundcloud:playlist'
468 'url': 'http://api.soundcloud.com/playlists/4110309',
471 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
472 'description': 're:.*?TILT Brass - Bowery Poetry Club',
477 def _real_extract(self
, url
):
478 mobj
= re
.match(self
._VALID
_URL
, url
)
479 playlist_id
= mobj
.group('id')
480 base_url
= '%s//api.soundcloud.com/playlists/%s.json?' % (self
.http_scheme(), playlist_id
)
483 'client_id': self
._CLIENT
_ID
,
485 token
= mobj
.group('token')
488 data_dict
['secret_token'] = token
490 data
= compat_urllib_parse_urlencode(data_dict
)
491 data
= self
._download
_json
(
492 base_url
+ data
, playlist_id
, 'Downloading playlist')
494 entries
= self
._extract
_track
_entries
(data
['tracks'])
499 'title': data
.get('title'),
500 'description': data
.get('description'),
505 class SoundcloudSearchIE(SearchInfoExtractor
, SoundcloudIE
):
506 IE_NAME
= 'soundcloud:search'
507 IE_DESC
= 'Soundcloud search'
508 _MAX_RESULTS
= float('inf')
510 'url': 'scsearch15:post-avant jazzcore',
512 'title': 'post-avant jazzcore',
514 'playlist_count': 15,
517 _SEARCH_KEY
= 'scsearch'
518 _MAX_RESULTS_PER_PAGE
= 200
519 _DEFAULT_RESULTS_PER_PAGE
= 50
520 _API_V2_BASE
= 'https://api-v2.soundcloud.com'
522 def _get_collection(self
, endpoint
, collection_id
, **query
):
524 query
.get('limit', self
._DEFAULT
_RESULTS
_PER
_PAGE
),
525 self
._MAX
_RESULTS
_PER
_PAGE
)
526 query
['limit'] = limit
527 query
['client_id'] = self
._CLIENT
_ID
528 query
['linked_partitioning'] = '1'
530 data
= compat_urllib_parse_urlencode(query
)
531 next_url
= '{0}{1}?{2}'.format(self
._API
_V
2_BASE
, endpoint
, data
)
533 collected_results
= 0
535 for i
in itertools
.count(1):
536 response
= self
._download
_json
(
537 next_url
, collection_id
, 'Downloading page {0}'.format(i
),
538 'Unable to download API page')
540 collection
= response
.get('collection', [])
544 collection
= list(filter(bool, collection
))
545 collected_results
+= len(collection
)
547 for item
in collection
:
548 yield self
.url_result(item
['uri'], SoundcloudIE
.ie_key())
550 if not collection
or collected_results
>= limit
:
553 next_url
= response
.get('next_href')
557 def _get_n_results(self
, query
, n
):
558 tracks
= self
._get
_collection
('/search/tracks', query
, limit
=n
, q
=query
)
559 return self
.playlist_result(tracks
, playlist_title
=query
)