]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/soundcloud.py
[soundcloud:pagedplaylist] Add ie and title to entries (#19022)
[yt-dlp.git] / youtube_dl / extractor / soundcloud.py
CommitLineData
dcdb292f 1# coding: utf-8
fbcd7b5f
PH
2from __future__ import unicode_literals
3
92790f4e 4import itertools
73602bcd 5import re
aad0d6d5 6
2abf7cab 7from .common import (
8 InfoExtractor,
9 SearchInfoExtractor
10)
1cc79574 11from ..compat import (
aad0d6d5 12 compat_str,
668de34c 13 compat_urlparse,
15707c7e 14 compat_urllib_parse_urlencode,
1cc79574
PH
15)
16from ..utils import (
aad0d6d5 17 ExtractorError,
eb920777 18 int_or_none,
aad0d6d5 19 unified_strdate,
d7c7100e
S
20 update_url_query,
21)
aad0d6d5
PH
22
23
24class SoundcloudIE(InfoExtractor):
25 """Information extractor for soundcloud.com
26 To access the media, the uid of the song and a stream token
27 must be extracted from the page source and the script must make
28 a request to media.soundcloud.com/crossdomain.xml. Then
29 the media can be grabbed by requesting from an url composed
30 of the stream token and uid
31 """
32
20991253 33 _VALID_URL = r'''(?x)^(?:https?://)?
71507a11 34 (?:(?:(?:www\.|m\.)?soundcloud\.com/
836ef264 35 (?!stations/track)
4ff50ef8 36 (?P<uploader>[\w\d-]+)/
3ef2da2d 37 (?!(?:tracks|albums|sets(?:/.+?)?|reposts|likes|spotlight)/?(?:$|[?#]))
22a6f150 38 (?P<title>[\w\d-]+)/?
de2dd4c5 39 (?P<token>[^?]+?)?(?:[?].*)?$)
9296738f 40 |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+)
0403b069 41 (?:/?\?secret_token=(?P<secret_token>[^&]+))?)
31c1cf5a 42 |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
eb6a41ba
JMF
43 )
44 '''
fbcd7b5f 45 IE_NAME = 'soundcloud'
12c167c8
JMF
46 _TESTS = [
47 {
fbcd7b5f 48 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
fbcd7b5f
PH
49 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
50 'info_dict': {
0eb9fb9f
JMF
51 'id': '62986583',
52 'ext': 'mp3',
53 'upload_date': '20121011',
54 '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',
55 'uploader': 'E.T. ExTerrestrial Music',
56 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1',
57 'duration': 143,
4bfd294e 58 'license': 'all-rights-reserved',
12c167c8
JMF
59 }
60 },
61 # not streamable song
62 {
fbcd7b5f
PH
63 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
64 'info_dict': {
65 'id': '47127627',
66 'ext': 'mp3',
67 'title': 'Goldrushed',
63ad0315 68 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
fbcd7b5f
PH
69 'uploader': 'The Royal Concept',
70 'upload_date': '20120521',
eb920777 71 'duration': 227,
4bfd294e 72 'license': 'all-rights-reserved',
12c167c8 73 },
fbcd7b5f 74 'params': {
12c167c8 75 # rtmp
fbcd7b5f 76 'skip_download': True,
12c167c8
JMF
77 },
78 },
de2dd4c5
JMF
79 # private link
80 {
fbcd7b5f
PH
81 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
82 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
83 'info_dict': {
84 'id': '123998367',
85 'ext': 'mp3',
86 'title': 'Youtube - Dl Test Video \'\' Ä↭',
87 'uploader': 'jaimeMF',
88 'description': 'test chars: \"\'/\\ä↭',
89 'upload_date': '20131209',
eb920777 90 'duration': 9,
4bfd294e 91 'license': 'all-rights-reserved',
de2dd4c5
JMF
92 },
93 },
9296738f 94 # private link (alt format)
95 {
96 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp',
97 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
98 'info_dict': {
99 'id': '123998367',
100 'ext': 'mp3',
101 'title': 'Youtube - Dl Test Video \'\' Ä↭',
102 'uploader': 'jaimeMF',
103 'description': 'test chars: \"\'/\\ä↭',
104 'upload_date': '20131209',
105 'duration': 9,
4bfd294e 106 'license': 'all-rights-reserved',
9296738f 107 },
108 },
f67ca84d
JMF
109 # downloadable song
110 {
00a82ea8 111 'url': 'https://soundcloud.com/oddsamples/bus-brakes',
eae12e3f 112 'md5': '7624f2351f8a3b2e7cd51522496e7631',
fbcd7b5f 113 'info_dict': {
00a82ea8 114 'id': '128590877',
eae12e3f 115 'ext': 'mp3',
00a82ea8 116 'title': 'Bus Brakes',
0eb9fb9f 117 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66',
00a82ea8
S
118 'uploader': 'oddsamples',
119 'upload_date': '20140109',
120 'duration': 17,
4bfd294e 121 'license': 'cc-by-sa',
f67ca84d
JMF
122 },
123 },
d7c7100e
S
124 # private link, downloadable format
125 {
126 'url': 'https://soundcloud.com/oriuplift/uponly-238-no-talking-wav/s-AyZUd',
127 'md5': '64a60b16e617d41d0bef032b7f55441e',
128 'info_dict': {
129 'id': '340344461',
130 'ext': 'wav',
131 'title': 'Uplifting Only 238 [No Talking] (incl. Alex Feed Guestmix) (Aug 31, 2017) [wav]',
132 'description': 'md5:fa20ee0fca76a3d6df8c7e57f3715366',
133 'uploader': 'Ori Uplift Music',
134 'upload_date': '20170831',
135 'duration': 7449,
136 'license': 'all-rights-reserved',
137 },
138 },
0b0870f9
PV
139 # no album art, use avatar pic for thumbnail
140 {
141 'url': 'https://soundcloud.com/garyvee/sideways-prod-mad-real',
142 'md5': '59c7872bc44e5d99b7211891664760c2',
143 'info_dict': {
144 'id': '309699954',
145 'ext': 'mp3',
146 'title': 'Sideways (Prod. Mad Real)',
147 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
148 'uploader': 'garyvee',
149 'upload_date': '20170226',
150 'duration': 207,
151 'thumbnail': r're:https?://.*\.jpg',
152 'license': 'all-rights-reserved',
153 },
154 'params': {
155 'skip_download': True,
156 },
157 },
12c167c8 158 ]
aad0d6d5 159
3ef2da2d 160 _CLIENT_ID = 'NmW1FlPaiL94ueEu7oziOWjYEzZzQDcK'
7d239269 161
fbdf8d15
S
162 @staticmethod
163 def _extract_urls(webpage):
164 return [m.group('url') for m in re.finditer(
165 r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?(?:w\.)?soundcloud\.com/player.+?)\1',
166 webpage)]
167
aad0d6d5
PH
168 def report_resolve(self, video_id):
169 """Report information extraction."""
83622b6d 170 self.to_screen('%s: Resolving id' % video_id)
aad0d6d5 171
7d239269
JMF
172 @classmethod
173 def _resolv_url(cls, url):
f1c05100 174 return 'https://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
7d239269 175
de2dd4c5 176 def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
12c167c8
JMF
177 track_id = compat_str(info['id'])
178 name = full_title or track_id
2a15e706 179 if quiet:
92790f4e 180 self.report_extraction(name)
0b0870f9 181 thumbnail = info.get('artwork_url') or info.get('user', {}).get('avatar_url')
f62a77b9 182 if isinstance(thumbnail, compat_str):
7d239269 183 thumbnail = thumbnail.replace('-large', '-t500x500')
12c167c8 184 result = {
2a15e706 185 'id': track_id,
f62a77b9
S
186 'uploader': info.get('user', {}).get('username'),
187 'upload_date': unified_strdate(info.get('created_at')),
2a15e706 188 'title': info['title'],
f62a77b9 189 'description': info.get('description'),
7d239269 190 'thumbnail': thumbnail,
eb920777 191 'duration': int_or_none(info.get('duration'), 1000),
579657ad 192 'webpage_url': info.get('permalink_url'),
f62a77b9 193 'license': info.get('license'),
7d239269 194 }
5e114e4b 195 formats = []
73602bcd
TI
196 query = {'client_id': self._CLIENT_ID}
197 if secret_token is not None:
198 query['secret_token'] = secret_token
12c167c8 199 if info.get('downloadable', False):
64bb5187 200 # We can build a direct link to the song
73602bcd 201 format_url = update_url_query(
d7c7100e 202 'https://api.soundcloud.com/tracks/%s/download' % track_id, query)
5e114e4b 203 formats.append({
2a15e706 204 'format_id': 'download',
fbcd7b5f 205 'ext': info.get('original_format', 'mp3'),
2a15e706 206 'url': format_url,
fb04e403 207 'vcodec': 'none',
5e114e4b
PH
208 'preference': 10,
209 })
210
211 # We have to retrieve the url
20991253 212 format_dict = self._download_json(
f1c05100 213 'https://api.soundcloud.com/i1/tracks/%s/streams' % track_id,
73602bcd 214 track_id, 'Downloading track url', query=query)
5e114e4b 215
5e114e4b 216 for key, stream_url in format_dict.items():
c0fd20ab
RA
217 ext, abr = 'mp3', None
218 mobj = re.search(r'_([^_]+)_(\d+)_url', key)
219 if mobj:
220 ext, abr = mobj.groups()
221 abr = int(abr)
5e114e4b 222 if key.startswith('http'):
3a194cb4 223 stream_formats = [{
5e114e4b
PH
224 'format_id': key,
225 'ext': ext,
226 'url': stream_url,
3a194cb4 227 }]
5e114e4b
PH
228 elif key.startswith('rtmp'):
229 # The url doesn't have an rtmp app, we have to extract the playpath
230 url, path = stream_url.split('mp3:', 1)
3a194cb4 231 stream_formats = [{
5e114e4b
PH
232 'format_id': key,
233 'url': url,
234 'play_path': 'mp3:' + path,
295df4ed 235 'ext': 'flv',
3a194cb4 236 }]
9b734718 237 elif key.startswith('hls'):
3a194cb4 238 stream_formats = self._extract_m3u8_formats(
c0fd20ab 239 stream_url, track_id, ext, entry_protocol='m3u8_native',
9b734718 240 m3u8_id=key, fatal=False)
3a194cb4
S
241 else:
242 continue
243
c0fd20ab
RA
244 if abr:
245 for f in stream_formats:
246 f['abr'] = abr
3a194cb4
S
247
248 formats.extend(stream_formats)
249
250 if not formats:
251 # We fallback to the stream_url in the original info, this
252 # cannot be always used, sometimes it can give an HTTP 404 error
253 formats.append({
254 'format_id': 'fallback',
73602bcd 255 'url': update_url_query(info['stream_url'], query),
c0fd20ab 256 'ext': 'mp3',
3a194cb4
S
257 })
258
259 for f in formats:
260 f['vcodec'] = 'none'
2a15e706 261
562ceab1
S
262 self._check_formats(formats, track_id)
263 self._sort_formats(formats)
264 result['formats'] = formats
64bb5187 265
12c167c8 266 return result
7d239269 267
aad0d6d5 268 def _real_extract(self, url):
eb6a41ba 269 mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
aad0d6d5 270 if mobj is None:
83622b6d 271 raise ExtractorError('Invalid URL: %s' % url)
aad0d6d5 272
eb6a41ba 273 track_id = mobj.group('track_id')
4bfd294e 274
eb6a41ba 275 if track_id is not None:
f1c05100 276 info_json_url = 'https://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
eb6a41ba 277 full_title = track_id
9296738f 278 token = mobj.group('secret_token')
279 if token:
611c1dd9 280 info_json_url += '&secret_token=' + token
31c1cf5a 281 elif mobj.group('player'):
668de34c 282 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
024ebb27
JMF
283 real_url = query['url'][0]
284 # If the token is in the query of the original url we have to
285 # manually add it
286 if 'secret_token' in query:
287 real_url += '?secret_token=' + query['secret_token'][0]
288 return self.url_result(real_url)
eb6a41ba
JMF
289 else:
290 # extract uploader (which is in the url)
de2dd4c5 291 uploader = mobj.group('uploader')
eb6a41ba 292 # extract simple title (uploader + slug of song title)
8bcc8756 293 slug_title = mobj.group('title')
de2dd4c5
JMF
294 token = mobj.group('token')
295 full_title = resolve_title = '%s/%s' % (uploader, slug_title)
296 if token:
297 resolve_title += '/%s' % token
5f6a1245 298
eb6a41ba 299 self.report_resolve(full_title)
5f6a1245 300
f1c05100 301 url = 'https://soundcloud.com/%s' % resolve_title
eb6a41ba 302 info_json_url = self._resolv_url(url)
20991253 303 info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
aad0d6d5 304
de2dd4c5 305 return self._extract_info_dict(info, full_title, secret_token=token)
aad0d6d5 306
20991253 307
7518a61d 308class SoundcloudPlaylistBaseIE(SoundcloudIE):
8e45e1cc
S
309 @staticmethod
310 def _extract_id(e):
311 return compat_str(e['id']) if e.get('id') else None
312
313 def _extract_track_entries(self, tracks):
314 return [
315 self.url_result(
316 track['permalink_url'], SoundcloudIE.ie_key(),
317 video_id=self._extract_id(track))
318 for track in tracks if track.get('permalink_url')]
319
320
7518a61d 321class SoundcloudSetIE(SoundcloudPlaylistBaseIE):
c808ef81 322 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[\w\d-]+)(?:/(?P<token>[^?/]+))?'
fbcd7b5f 323 IE_NAME = 'soundcloud:set'
22a6f150
PH
324 _TESTS = [{
325 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
326 'info_dict': {
a9551e90 327 'id': '2284613',
22a6f150
PH
328 'title': 'The Royal Concept EP',
329 },
bf2dc9cc 330 'playlist_mincount': 5,
f7043ef3
S
331 }, {
332 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token',
333 'only_matching': True,
22a6f150 334 }]
aad0d6d5 335
aad0d6d5
PH
336 def _real_extract(self, url):
337 mobj = re.match(self._VALID_URL, url)
aad0d6d5
PH
338
339 # extract uploader (which is in the url)
2f834e93 340 uploader = mobj.group('uploader')
aad0d6d5 341 # extract simple title (uploader + slug of song title)
2f834e93 342 slug_title = mobj.group('slug_title')
aad0d6d5 343 full_title = '%s/sets/%s' % (uploader, slug_title)
f1c05100 344 url = 'https://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
2f834e93 345
346 token = mobj.group('token')
347 if token:
348 full_title += '/' + token
349 url += '/' + token
aad0d6d5
PH
350
351 self.report_resolve(full_title)
352
7d239269 353 resolv_url = self._resolv_url(url)
20991253 354 info = self._download_json(resolv_url, full_title)
aad0d6d5 355
aad0d6d5 356 if 'errors' in info:
214e74bf
JMF
357 msgs = (compat_str(err['error_message']) for err in info['errors'])
358 raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs))
aad0d6d5 359
8e45e1cc 360 entries = self._extract_track_entries(info['tracks'])
b14fa8e6 361
22a6f150
PH
362 return {
363 '_type': 'playlist',
b14fa8e6 364 'entries': entries,
a9551e90 365 'id': '%s' % info['id'],
22a6f150
PH
366 'title': info['title'],
367 }
92790f4e
JMF
368
369
836ef264 370class SoundcloudPagedPlaylistBaseIE(SoundcloudPlaylistBaseIE):
836ef264
S
371 _API_V2_BASE = 'https://api-v2.soundcloud.com'
372
373 def _extract_playlist(self, base_url, playlist_id, playlist_title):
374 COMMON_QUERY = {
375 'limit': 50,
376 'client_id': self._CLIENT_ID,
377 'linked_partitioning': '1',
378 }
379
380 query = COMMON_QUERY.copy()
381 query['offset'] = 0
382
383 next_href = base_url + '?' + compat_urllib_parse_urlencode(query)
384
385 entries = []
386 for i in itertools.count():
387 response = self._download_json(
388 next_href, playlist_id, 'Downloading track page %s' % (i + 1))
389
390 collection = response['collection']
3ef2da2d
S
391
392 if not isinstance(collection, list):
393 collection = []
394
395 # Empty collection may be returned, in this case we proceed
396 # straight to next_href
836ef264 397
6cc6e0c3
CH
398 def append_url_result(entries, item):
399 for cand in (item, item.get('track'), item.get('playlist')):
836ef264
S
400 if isinstance(cand, dict):
401 permalink_url = cand.get('permalink_url')
836ef264 402 if permalink_url and permalink_url.startswith('http'):
6cc6e0c3
CH
403 return entries.append(
404 self.url_result(
405 permalink_url,
406 ie=SoundcloudIE.ie_key() if SoundcloudIE.suitable(permalink_url) else None,
407 video_id=self._extract_id(cand),
408 video_title=cand.get('title')))
836ef264
S
409
410 for e in collection:
6cc6e0c3 411 append_url_result(entries, e)
836ef264
S
412
413 next_href = response.get('next_href')
414 if not next_href:
415 break
416
417 parsed_next_href = compat_urlparse.urlparse(response['next_href'])
418 qs = compat_urlparse.parse_qs(parsed_next_href.query)
419 qs.update(COMMON_QUERY)
420 next_href = compat_urlparse.urlunparse(
421 parsed_next_href._replace(query=compat_urllib_parse_urlencode(qs, True)))
422
423 return {
424 '_type': 'playlist',
425 'id': playlist_id,
426 'title': playlist_title,
427 'entries': entries,
428 }
429
430
431class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE):
16a08978
S
432 _VALID_URL = r'''(?x)
433 https?://
434 (?:(?:www|m)\.)?soundcloud\.com/
435 (?P<user>[^/]+)
436 (?:/
3ef2da2d 437 (?P<rsrc>tracks|albums|sets|reposts|likes|spotlight)
16a08978
S
438 )?
439 /?(?:[?#].*)?$
440 '''
fbcd7b5f 441 IE_NAME = 'soundcloud:user'
22a6f150 442 _TESTS = [{
b6423e6c 443 'url': 'https://soundcloud.com/soft-cell-official',
22a6f150 444 'info_dict': {
b6423e6c
S
445 'id': '207965082',
446 'title': 'Soft Cell (All)',
22a6f150 447 },
b6423e6c 448 'playlist_mincount': 28,
22a6f150 449 }, {
b6423e6c 450 'url': 'https://soundcloud.com/soft-cell-official/tracks',
22a6f150 451 'info_dict': {
b6423e6c
S
452 'id': '207965082',
453 'title': 'Soft Cell (Tracks)',
22a6f150 454 },
b6423e6c 455 'playlist_mincount': 27,
03b9c944 456 }, {
b6423e6c
S
457 'url': 'https://soundcloud.com/soft-cell-official/albums',
458 'info_dict': {
459 'id': '207965082',
460 'title': 'Soft Cell (Albums)',
461 },
462 'playlist_mincount': 1,
463 }, {
464 'url': 'https://soundcloud.com/jcv246/sets',
80fb6d4a 465 'info_dict': {
b6423e6c
S
466 'id': '12982173',
467 'title': 'Jordi / cv (Playlists)',
80fb6d4a 468 },
8e45e1cc 469 'playlist_mincount': 2,
80fb6d4a 470 }, {
b6423e6c 471 'url': 'https://soundcloud.com/jcv246/reposts',
80fb6d4a 472 'info_dict': {
b6423e6c
S
473 'id': '12982173',
474 'title': 'Jordi / cv (Reposts)',
80fb6d4a 475 },
b6423e6c 476 'playlist_mincount': 6,
80fb6d4a 477 }, {
b6423e6c 478 'url': 'https://soundcloud.com/clalberg/likes',
80fb6d4a 479 'info_dict': {
b6423e6c
S
480 'id': '11817582',
481 'title': 'clalberg (Likes)',
80fb6d4a 482 },
b6423e6c 483 'playlist_mincount': 5,
80fb6d4a
S
484 }, {
485 'url': 'https://soundcloud.com/grynpyret/spotlight',
486 'info_dict': {
487 'id': '7098329',
bf2dc9cc 488 'title': 'Grynpyret (Spotlight)',
80fb6d4a
S
489 },
490 'playlist_mincount': 1,
22a6f150 491 }]
92790f4e 492
80fb6d4a 493 _BASE_URL_MAP = {
3ef2da2d
S
494 'all': '%s/stream/users/%%s' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
495 'tracks': '%s/users/%%s/tracks' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
496 'albums': '%s/users/%%s/albums' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
836ef264 497 'sets': '%s/users/%%s/playlists' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
3ef2da2d 498 'reposts': '%s/stream/users/%%s/reposts' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
836ef264
S
499 'likes': '%s/users/%%s/likes' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
500 'spotlight': '%s/users/%%s/spotlight' % SoundcloudPagedPlaylistBaseIE._API_V2_BASE,
80fb6d4a
S
501 }
502
503 _TITLE_MAP = {
504 'all': 'All',
505 'tracks': 'Tracks',
3ef2da2d 506 'albums': 'Albums',
80fb6d4a
S
507 'sets': 'Playlists',
508 'reposts': 'Reposts',
509 'likes': 'Likes',
510 'spotlight': 'Spotlight',
511 }
512
92790f4e
JMF
513 def _real_extract(self, url):
514 mobj = re.match(self._VALID_URL, url)
515 uploader = mobj.group('user')
516
f1c05100 517 url = 'https://soundcloud.com/%s/' % uploader
92790f4e 518 resolv_url = self._resolv_url(url)
20991253
PH
519 user = self._download_json(
520 resolv_url, uploader, 'Downloading user info')
80fb6d4a
S
521
522 resource = mobj.group('rsrc') or 'all'
80fb6d4a 523
836ef264
S
524 return self._extract_playlist(
525 self._BASE_URL_MAP[resource] % user['id'], compat_str(user['id']),
526 '%s (%s)' % (user['username'], self._TITLE_MAP[resource]))
97afd99a 527
92790f4e 528
836ef264
S
529class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE):
530 _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)'
531 IE_NAME = 'soundcloud:trackstation'
532 _TESTS = [{
533 'url': 'https://soundcloud.com/stations/track/officialsundial/your-text',
534 'info_dict': {
535 'id': '286017854',
536 'title': 'Track station: your-text',
537 },
538 'playlist_mincount': 47,
539 }]
80fb6d4a 540
836ef264
S
541 def _real_extract(self, url):
542 track_name = self._match_id(url)
80fb6d4a 543
836ef264 544 webpage = self._download_webpage(url, track_name)
97afd99a 545
836ef264
S
546 track_id = self._search_regex(
547 r'soundcloud:track-stations:(\d+)', webpage, 'track id')
92790f4e 548
836ef264
S
549 return self._extract_playlist(
550 '%s/stations/soundcloud:track-stations:%s/tracks'
551 % (self._API_V2_BASE, track_id),
552 track_id, 'Track station: %s' % track_name)
20991253
PH
553
554
7518a61d 555class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE):
46f74bcf 556 _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$'
20991253 557 IE_NAME = 'soundcloud:playlist'
46f74bcf 558 _TESTS = [{
f1c05100 559 'url': 'https://api.soundcloud.com/playlists/4110309',
46f74bcf
PH
560 'info_dict': {
561 'id': '4110309',
562 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
563 'description': 're:.*?TILT Brass - Bowery Poetry Club',
564 },
565 'playlist_count': 6,
566 }]
20991253
PH
567
568 def _real_extract(self, url):
569 mobj = re.match(self._VALID_URL, url)
570 playlist_id = mobj.group('id')
571 base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
572
2f834e93 573 data_dict = {
20991253 574 'client_id': self._CLIENT_ID,
2f834e93 575 }
576 token = mobj.group('token')
577
578 if token:
579 data_dict['secret_token'] = token
580
15707c7e 581 data = compat_urllib_parse_urlencode(data_dict)
20991253
PH
582 data = self._download_json(
583 base_url + data, playlist_id, 'Downloading playlist')
584
8e45e1cc 585 entries = self._extract_track_entries(data['tracks'])
20991253
PH
586
587 return {
588 '_type': 'playlist',
589 'id': playlist_id,
590 'title': data.get('title'),
591 'description': data.get('description'),
592 'entries': entries,
92790f4e 593 }
2abf7cab 594
595
596class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE):
597 IE_NAME = 'soundcloud:search'
598 IE_DESC = 'Soundcloud search'
328a22e1 599 _MAX_RESULTS = float('inf')
2abf7cab 600 _TESTS = [{
601 'url': 'scsearch15:post-avant jazzcore',
602 'info_dict': {
603 'title': 'post-avant jazzcore',
604 },
605 'playlist_count': 15,
606 }]
607
608 _SEARCH_KEY = 'scsearch'
328a22e1 609 _MAX_RESULTS_PER_PAGE = 200
610 _DEFAULT_RESULTS_PER_PAGE = 50
c30943b1 611 _API_V2_BASE = 'https://api-v2.soundcloud.com'
2abf7cab 612
613 def _get_collection(self, endpoint, collection_id, **query):
a3372437 614 limit = min(
328a22e1 615 query.get('limit', self._DEFAULT_RESULTS_PER_PAGE),
616 self._MAX_RESULTS_PER_PAGE)
f6c903e7 617 query['limit'] = limit
2abf7cab 618 query['client_id'] = self._CLIENT_ID
619 query['linked_partitioning'] = '1'
f6c903e7 620 query['offset'] = 0
15707c7e 621 data = compat_urllib_parse_urlencode(query)
f6c903e7 622 next_url = '{0}{1}?{2}'.format(self._API_V2_BASE, endpoint, data)
2abf7cab 623
2abf7cab 624 collected_results = 0
625
f6c903e7 626 for i in itertools.count(1):
7e347275 627 response = self._download_json(
f6c903e7 628 next_url, collection_id, 'Downloading page {0}'.format(i),
7e347275 629 'Unable to download API page')
2abf7cab 630
f6c903e7
S
631 collection = response.get('collection', [])
632 if not collection:
633 break
2abf7cab 634
f6c903e7 635 collection = list(filter(bool, collection))
2abf7cab 636 collected_results += len(collection)
637
f6c903e7
S
638 for item in collection:
639 yield self.url_result(item['uri'], SoundcloudIE.ie_key())
2abf7cab 640
f6c903e7 641 if not collection or collected_results >= limit:
2abf7cab 642 break
643
7e347275 644 next_url = response.get('next_href')
f6c903e7
S
645 if not next_url:
646 break
2abf7cab 647
648 def _get_n_results(self, query, n):
f6c903e7
S
649 tracks = self._get_collection('/search/tracks', query, limit=n, q=query)
650 return self.playlist_result(tracks, playlist_title=query)