]>
Commit | Line | Data |
---|---|---|
1 | # coding: utf-8 | |
2 | from __future__ import unicode_literals | |
3 | ||
4 | import itertools | |
5 | import re | |
6 | import json | |
7 | import random | |
8 | ||
9 | from .common import ( | |
10 | InfoExtractor, | |
11 | SearchInfoExtractor | |
12 | ) | |
13 | from ..compat import ( | |
14 | compat_HTTPError, | |
15 | compat_kwargs, | |
16 | compat_str, | |
17 | compat_urlparse, | |
18 | ) | |
19 | from ..utils import ( | |
20 | error_to_compat_str, | |
21 | ExtractorError, | |
22 | float_or_none, | |
23 | HEADRequest, | |
24 | int_or_none, | |
25 | KNOWN_EXTENSIONS, | |
26 | mimetype2ext, | |
27 | str_or_none, | |
28 | try_get, | |
29 | unified_timestamp, | |
30 | update_url_query, | |
31 | url_or_none, | |
32 | urlhandle_detect_ext, | |
33 | sanitized_Request, | |
34 | ) | |
35 | ||
36 | ||
37 | class SoundcloudEmbedIE(InfoExtractor): | |
38 | _VALID_URL = r'https?://(?:w|player|p)\.soundcloud\.com/player/?.*?\burl=(?P<id>.+)' | |
39 | _TEST = { | |
40 | # from https://www.soundi.fi/uutiset/ennakkokuuntelussa-timo-kaukolammen-station-to-station-to-station-julkaisua-juhlitaan-tanaan-g-livelabissa/ | |
41 | 'url': 'https://w.soundcloud.com/player/?visual=true&url=https%3A%2F%2Fapi.soundcloud.com%2Fplaylists%2F922213810&show_artwork=true&maxwidth=640&maxheight=960&dnt=1&secret_token=s-ziYey', | |
42 | 'only_matching': True, | |
43 | } | |
44 | ||
45 | @staticmethod | |
46 | def _extract_urls(webpage): | |
47 | return [m.group('url') for m in re.finditer( | |
48 | r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?(?:w\.)?soundcloud\.com/player.+?)\1', | |
49 | webpage)] | |
50 | ||
51 | def _real_extract(self, url): | |
52 | query = compat_urlparse.parse_qs( | |
53 | compat_urlparse.urlparse(url).query) | |
54 | api_url = query['url'][0] | |
55 | secret_token = query.get('secret_token') | |
56 | if secret_token: | |
57 | api_url = update_url_query(api_url, {'secret_token': secret_token[0]}) | |
58 | return self.url_result(api_url) | |
59 | ||
60 | ||
61 | class SoundcloudIE(InfoExtractor): | |
62 | """Information extractor for soundcloud.com | |
63 | To access the media, the uid of the song and a stream token | |
64 | must be extracted from the page source and the script must make | |
65 | a request to media.soundcloud.com/crossdomain.xml. Then | |
66 | the media can be grabbed by requesting from an url composed | |
67 | of the stream token and uid | |
68 | """ | |
69 | ||
70 | _VALID_URL = r'''(?x)^(?:https?://)? | |
71 | (?:(?:(?:www\.|m\.)?soundcloud\.com/ | |
72 | (?!stations/track) | |
73 | (?P<uploader>[\w\d-]+)/ | |
74 | (?!(?:tracks|albums|sets(?:/.+?)?|reposts|likes|spotlight)/?(?:$|[?#])) | |
75 | (?P<title>[\w\d-]+)/? | |
76 | (?P<token>[^?]+?)?(?:[?].*)?$) | |
77 | |(?:api(?:-v2)?\.soundcloud\.com/tracks/(?P<track_id>\d+) | |
78 | (?:/?\?secret_token=(?P<secret_token>[^&]+))?) | |
79 | ) | |
80 | ''' | |
81 | IE_NAME = 'soundcloud' | |
82 | _TESTS = [ | |
83 | { | |
84 | 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy', | |
85 | 'md5': 'ebef0a451b909710ed1d7787dddbf0d7', | |
86 | 'info_dict': { | |
87 | 'id': '62986583', | |
88 | 'ext': 'mp3', | |
89 | 'title': 'Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1', | |
90 | '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', | |
91 | 'uploader': 'E.T. ExTerrestrial Music', | |
92 | 'uploader_id': '1571244', | |
93 | 'timestamp': 1349920598, | |
94 | 'upload_date': '20121011', | |
95 | 'duration': 143.216, | |
96 | 'license': 'all-rights-reserved', | |
97 | 'view_count': int, | |
98 | 'like_count': int, | |
99 | 'comment_count': int, | |
100 | 'repost_count': int, | |
101 | } | |
102 | }, | |
103 | # geo-restricted | |
104 | { | |
105 | 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep', | |
106 | 'info_dict': { | |
107 | 'id': '47127627', | |
108 | 'ext': 'mp3', | |
109 | 'title': 'Goldrushed', | |
110 | 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com', | |
111 | 'uploader': 'The Royal Concept', | |
112 | 'uploader_id': '9615865', | |
113 | 'timestamp': 1337635207, | |
114 | 'upload_date': '20120521', | |
115 | 'duration': 227.155, | |
116 | 'license': 'all-rights-reserved', | |
117 | 'view_count': int, | |
118 | 'like_count': int, | |
119 | 'comment_count': int, | |
120 | 'repost_count': int, | |
121 | }, | |
122 | }, | |
123 | # private link | |
124 | { | |
125 | 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp', | |
126 | 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604', | |
127 | 'info_dict': { | |
128 | 'id': '123998367', | |
129 | 'ext': 'mp3', | |
130 | 'title': 'Youtube - Dl Test Video \'\' Ä↭', | |
131 | 'description': 'test chars: \"\'/\\ä↭', | |
132 | 'uploader': 'jaimeMF', | |
133 | 'uploader_id': '69767071', | |
134 | 'timestamp': 1386604920, | |
135 | 'upload_date': '20131209', | |
136 | 'duration': 9.927, | |
137 | 'license': 'all-rights-reserved', | |
138 | 'view_count': int, | |
139 | 'like_count': int, | |
140 | 'comment_count': int, | |
141 | 'repost_count': int, | |
142 | }, | |
143 | }, | |
144 | # private link (alt format) | |
145 | { | |
146 | 'url': 'https://api.soundcloud.com/tracks/123998367?secret_token=s-8Pjrp', | |
147 | 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604', | |
148 | 'info_dict': { | |
149 | 'id': '123998367', | |
150 | 'ext': 'mp3', | |
151 | 'title': 'Youtube - Dl Test Video \'\' Ä↭', | |
152 | 'description': 'test chars: \"\'/\\ä↭', | |
153 | 'uploader': 'jaimeMF', | |
154 | 'uploader_id': '69767071', | |
155 | 'timestamp': 1386604920, | |
156 | 'upload_date': '20131209', | |
157 | 'duration': 9.927, | |
158 | 'license': 'all-rights-reserved', | |
159 | 'view_count': int, | |
160 | 'like_count': int, | |
161 | 'comment_count': int, | |
162 | 'repost_count': int, | |
163 | }, | |
164 | }, | |
165 | # downloadable song | |
166 | { | |
167 | 'url': 'https://soundcloud.com/oddsamples/bus-brakes', | |
168 | 'md5': '7624f2351f8a3b2e7cd51522496e7631', | |
169 | 'info_dict': { | |
170 | 'id': '128590877', | |
171 | 'ext': 'mp3', | |
172 | 'title': 'Bus Brakes', | |
173 | 'description': 'md5:0053ca6396e8d2fd7b7e1595ef12ab66', | |
174 | 'uploader': 'oddsamples', | |
175 | 'uploader_id': '73680509', | |
176 | 'timestamp': 1389232924, | |
177 | 'upload_date': '20140109', | |
178 | 'duration': 17.346, | |
179 | 'license': 'cc-by-sa', | |
180 | 'view_count': int, | |
181 | 'like_count': int, | |
182 | 'comment_count': int, | |
183 | 'repost_count': int, | |
184 | }, | |
185 | }, | |
186 | # private link, downloadable format | |
187 | { | |
188 | 'url': 'https://soundcloud.com/oriuplift/uponly-238-no-talking-wav/s-AyZUd', | |
189 | 'md5': '64a60b16e617d41d0bef032b7f55441e', | |
190 | 'info_dict': { | |
191 | 'id': '340344461', | |
192 | 'ext': 'wav', | |
193 | 'title': 'Uplifting Only 238 [No Talking] (incl. Alex Feed Guestmix) (Aug 31, 2017) [wav]', | |
194 | 'description': 'md5:fa20ee0fca76a3d6df8c7e57f3715366', | |
195 | 'uploader': 'Ori Uplift Music', | |
196 | 'uploader_id': '12563093', | |
197 | 'timestamp': 1504206263, | |
198 | 'upload_date': '20170831', | |
199 | 'duration': 7449.096, | |
200 | 'license': 'all-rights-reserved', | |
201 | 'view_count': int, | |
202 | 'like_count': int, | |
203 | 'comment_count': int, | |
204 | 'repost_count': int, | |
205 | }, | |
206 | }, | |
207 | # no album art, use avatar pic for thumbnail | |
208 | { | |
209 | 'url': 'https://soundcloud.com/garyvee/sideways-prod-mad-real', | |
210 | 'md5': '59c7872bc44e5d99b7211891664760c2', | |
211 | 'info_dict': { | |
212 | 'id': '309699954', | |
213 | 'ext': 'mp3', | |
214 | 'title': 'Sideways (Prod. Mad Real)', | |
215 | 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e', | |
216 | 'uploader': 'garyvee', | |
217 | 'uploader_id': '2366352', | |
218 | 'timestamp': 1488152409, | |
219 | 'upload_date': '20170226', | |
220 | 'duration': 207.012, | |
221 | 'thumbnail': r're:https?://.*\.jpg', | |
222 | 'license': 'all-rights-reserved', | |
223 | 'view_count': int, | |
224 | 'like_count': int, | |
225 | 'comment_count': int, | |
226 | 'repost_count': int, | |
227 | }, | |
228 | 'params': { | |
229 | 'skip_download': True, | |
230 | }, | |
231 | }, | |
232 | { | |
233 | 'url': 'https://soundcloud.com/giovannisarani/mezzo-valzer', | |
234 | 'md5': 'e22aecd2bc88e0e4e432d7dcc0a1abf7', | |
235 | 'info_dict': { | |
236 | 'id': '583011102', | |
237 | 'ext': 'mp3', | |
238 | 'title': 'Mezzo Valzer', | |
239 | 'description': 'md5:4138d582f81866a530317bae316e8b61', | |
240 | 'uploader': 'Micronie', | |
241 | 'uploader_id': '3352531', | |
242 | 'timestamp': 1551394171, | |
243 | 'upload_date': '20190228', | |
244 | 'duration': 180.157, | |
245 | 'thumbnail': r're:https?://.*\.jpg', | |
246 | 'license': 'all-rights-reserved', | |
247 | 'view_count': int, | |
248 | 'like_count': int, | |
249 | 'comment_count': int, | |
250 | 'repost_count': int, | |
251 | }, | |
252 | }, | |
253 | { | |
254 | # AAC HQ format available (account with active subscription needed) | |
255 | 'url': 'https://soundcloud.com/wandw/the-chainsmokers-ft-daya-dont-let-me-down-ww-remix-1', | |
256 | 'only_matching': True, | |
257 | }, | |
258 | { | |
259 | # Go+ (account with active subscription needed) | |
260 | 'url': 'https://soundcloud.com/taylorswiftofficial/look-what-you-made-me-do', | |
261 | 'only_matching': True, | |
262 | }, | |
263 | ] | |
264 | ||
265 | _API_V2_BASE = 'https://api-v2.soundcloud.com/' | |
266 | _BASE_URL = 'https://soundcloud.com/' | |
267 | _IMAGE_REPL_RE = r'-([0-9a-z]+)\.jpg' | |
268 | ||
269 | _ARTWORK_MAP = { | |
270 | 'mini': 16, | |
271 | 'tiny': 20, | |
272 | 'small': 32, | |
273 | 'badge': 47, | |
274 | 't67x67': 67, | |
275 | 'large': 100, | |
276 | 't300x300': 300, | |
277 | 'crop': 400, | |
278 | 't500x500': 500, | |
279 | 'original': 0, | |
280 | } | |
281 | ||
282 | def _store_client_id(self, client_id): | |
283 | self._downloader.cache.store('soundcloud', 'client_id', client_id) | |
284 | ||
285 | def _update_client_id(self): | |
286 | webpage = self._download_webpage('https://soundcloud.com/', None) | |
287 | for src in reversed(re.findall(r'<script[^>]+src="([^"]+)"', webpage)): | |
288 | script = self._download_webpage(src, None, fatal=False) | |
289 | if script: | |
290 | client_id = self._search_regex( | |
291 | r'client_id\s*:\s*"([0-9a-zA-Z]{32})"', | |
292 | script, 'client id', default=None) | |
293 | if client_id: | |
294 | self._CLIENT_ID = client_id | |
295 | self._store_client_id(client_id) | |
296 | return | |
297 | raise ExtractorError('Unable to extract client id') | |
298 | ||
299 | def _download_json(self, *args, **kwargs): | |
300 | non_fatal = kwargs.get('fatal') is False | |
301 | if non_fatal: | |
302 | del kwargs['fatal'] | |
303 | query = kwargs.get('query', {}).copy() | |
304 | for _ in range(2): | |
305 | query['client_id'] = self._CLIENT_ID | |
306 | kwargs['query'] = query | |
307 | try: | |
308 | return super(SoundcloudIE, self)._download_json(*args, **compat_kwargs(kwargs)) | |
309 | except ExtractorError as e: | |
310 | if isinstance(e.cause, compat_HTTPError) and e.cause.code == 401: | |
311 | self._store_client_id(None) | |
312 | self._update_client_id() | |
313 | continue | |
314 | elif non_fatal: | |
315 | self._downloader.report_warning(error_to_compat_str(e)) | |
316 | return False | |
317 | raise | |
318 | ||
319 | def _real_initialize(self): | |
320 | self._CLIENT_ID = self._downloader.cache.load('soundcloud', 'client_id') or "T5R4kgWS2PRf6lzLyIravUMnKlbIxQag" # 'EXLwg5lHTO2dslU5EePe3xkw0m1h86Cd' # 'YUKXoArFcqrlQn9tfNHvvyfnDISj04zk' | |
321 | self._login() | |
322 | ||
323 | _USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36" | |
324 | _API_AUTH_QUERY_TEMPLATE = '?client_id=%s' | |
325 | _API_AUTH_URL_PW = 'https://api-auth.soundcloud.com/web-auth/sign-in/password%s' | |
326 | _access_token = None | |
327 | _HEADERS = {} | |
328 | _NETRC_MACHINE = 'soundcloud' | |
329 | ||
330 | def _login(self): | |
331 | username, password = self._get_login_info() | |
332 | if username is None: | |
333 | return | |
334 | ||
335 | def genDevId(): | |
336 | def genNumBlock(): | |
337 | return ''.join([str(random.randrange(10)) for i in range(6)]) | |
338 | return '-'.join([genNumBlock() for i in range(4)]) | |
339 | ||
340 | payload = { | |
341 | 'client_id': self._CLIENT_ID, | |
342 | 'recaptcha_pubkey': 'null', | |
343 | 'recaptcha_response': 'null', | |
344 | 'credentials': { | |
345 | 'identifier': username, | |
346 | 'password': password | |
347 | }, | |
348 | 'signature': self.sign(username, password, self._CLIENT_ID), | |
349 | 'device_id': genDevId(), | |
350 | 'user_agent': self._USER_AGENT | |
351 | } | |
352 | ||
353 | query = self._API_AUTH_QUERY_TEMPLATE % self._CLIENT_ID | |
354 | login = sanitized_Request(self._API_AUTH_URL_PW % query, json.dumps(payload).encode('utf-8')) | |
355 | response = self._download_json(login, None) | |
356 | self._access_token = response.get('session').get('access_token') | |
357 | if not self._access_token: | |
358 | self.report_warning('Unable to get access token, login may has failed') | |
359 | else: | |
360 | self._HEADERS = {'Authorization': 'OAuth ' + self._access_token} | |
361 | ||
362 | # signature generation | |
363 | def sign(self, user, pw, clid): | |
364 | a = 33 | |
365 | i = 1 | |
366 | s = 440123 | |
367 | w = 117 | |
368 | u = 1800000 | |
369 | l = 1042 | |
370 | b = 37 | |
371 | k = 37 | |
372 | c = 5 | |
373 | n = "0763ed7314c69015fd4a0dc16bbf4b90" # _KEY | |
374 | y = "8" # _REV | |
375 | r = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36" # _USER_AGENT | |
376 | e = user # _USERNAME | |
377 | t = clid # _CLIENT_ID | |
378 | ||
379 | d = '-'.join([str(mInt) for mInt in [a, i, s, w, u, l, b, k]]) | |
380 | p = n + y + d + r + e + t + d + n | |
381 | h = p | |
382 | ||
383 | m = 8011470 | |
384 | f = 0 | |
385 | ||
386 | for f in range(f, len(h)): | |
387 | m = (m >> 1) + ((1 & m) << 23) | |
388 | m += ord(h[f]) | |
389 | m &= 16777215 | |
390 | ||
391 | # c is not even needed | |
392 | out = str(y) + ':' + str(d) + ':' + format(m, 'x') + ':' + str(c) | |
393 | ||
394 | return out | |
395 | ||
396 | @classmethod | |
397 | def _resolv_url(cls, url): | |
398 | return SoundcloudIE._API_V2_BASE + 'resolve?url=' + url | |
399 | ||
400 | def _extract_info_dict(self, info, full_title=None, secret_token=None): | |
401 | track_id = compat_str(info['id']) | |
402 | title = info['title'] | |
403 | ||
404 | format_urls = set() | |
405 | formats = [] | |
406 | query = {'client_id': self._CLIENT_ID} | |
407 | if secret_token: | |
408 | query['secret_token'] = secret_token | |
409 | ||
410 | if info.get('downloadable') and info.get('has_downloads_left'): | |
411 | download_url = update_url_query( | |
412 | self._API_V2_BASE + 'tracks/' + track_id + '/download', query) | |
413 | redirect_url = (self._download_json(download_url, track_id, fatal=False) or {}).get('redirectUri') | |
414 | if redirect_url: | |
415 | urlh = self._request_webpage( | |
416 | HEADRequest(redirect_url), track_id, fatal=False) | |
417 | if urlh: | |
418 | format_url = urlh.geturl() | |
419 | format_urls.add(format_url) | |
420 | formats.append({ | |
421 | 'format_id': 'download', | |
422 | 'ext': urlhandle_detect_ext(urlh) or 'mp3', | |
423 | 'filesize': int_or_none(urlh.headers.get('Content-Length')), | |
424 | 'url': format_url, | |
425 | 'quality': 10, | |
426 | }) | |
427 | ||
428 | def invalid_url(url): | |
429 | return not url or url in format_urls | |
430 | ||
431 | def add_format(f, protocol, is_preview=False): | |
432 | mobj = re.search(r'\.(?P<abr>\d+)\.(?P<ext>[0-9a-z]{3,4})(?=[/?])', stream_url) | |
433 | if mobj: | |
434 | for k, v in mobj.groupdict().items(): | |
435 | if not f.get(k): | |
436 | f[k] = v | |
437 | format_id_list = [] | |
438 | if protocol: | |
439 | format_id_list.append(protocol) | |
440 | ext = f.get('ext') | |
441 | if ext == 'aac': | |
442 | f['abr'] = '256' | |
443 | for k in ('ext', 'abr'): | |
444 | v = f.get(k) | |
445 | if v: | |
446 | format_id_list.append(v) | |
447 | preview = is_preview or re.search(r'/(?:preview|playlist)/0/30/', f['url']) | |
448 | if preview: | |
449 | format_id_list.append('preview') | |
450 | abr = f.get('abr') | |
451 | if abr: | |
452 | f['abr'] = int(abr) | |
453 | if protocol == 'hls': | |
454 | protocol = 'm3u8' if ext == 'aac' else 'm3u8_native' | |
455 | else: | |
456 | protocol = 'http' | |
457 | f.update({ | |
458 | 'format_id': '_'.join(format_id_list), | |
459 | 'protocol': protocol, | |
460 | 'preference': -10 if preview else None, | |
461 | }) | |
462 | formats.append(f) | |
463 | ||
464 | # New API | |
465 | transcodings = try_get( | |
466 | info, lambda x: x['media']['transcodings'], list) or [] | |
467 | for t in transcodings: | |
468 | if not isinstance(t, dict): | |
469 | continue | |
470 | format_url = url_or_none(t.get('url')) | |
471 | if not format_url: | |
472 | continue | |
473 | stream = self._download_json( | |
474 | format_url, track_id, query=query, fatal=False, headers=self._HEADERS) | |
475 | if not isinstance(stream, dict): | |
476 | continue | |
477 | stream_url = url_or_none(stream.get('url')) | |
478 | if invalid_url(stream_url): | |
479 | continue | |
480 | format_urls.add(stream_url) | |
481 | stream_format = t.get('format') or {} | |
482 | protocol = stream_format.get('protocol') | |
483 | if protocol != 'hls' and '/hls' in format_url: | |
484 | protocol = 'hls' | |
485 | ext = None | |
486 | preset = str_or_none(t.get('preset')) | |
487 | if preset: | |
488 | ext = preset.split('_')[0] | |
489 | if ext not in KNOWN_EXTENSIONS: | |
490 | ext = mimetype2ext(stream_format.get('mime_type')) | |
491 | add_format({ | |
492 | 'url': stream_url, | |
493 | 'ext': ext, | |
494 | }, 'http' if protocol == 'progressive' else protocol, | |
495 | t.get('snipped') or '/preview/' in format_url) | |
496 | ||
497 | for f in formats: | |
498 | f['vcodec'] = 'none' | |
499 | ||
500 | if not formats and info.get('policy') == 'BLOCK': | |
501 | self.raise_geo_restricted() | |
502 | self._sort_formats(formats) | |
503 | ||
504 | user = info.get('user') or {} | |
505 | ||
506 | thumbnails = [] | |
507 | artwork_url = info.get('artwork_url') | |
508 | thumbnail = artwork_url or user.get('avatar_url') | |
509 | if isinstance(thumbnail, compat_str): | |
510 | if re.search(self._IMAGE_REPL_RE, thumbnail): | |
511 | for image_id, size in self._ARTWORK_MAP.items(): | |
512 | i = { | |
513 | 'id': image_id, | |
514 | 'url': re.sub(self._IMAGE_REPL_RE, '-%s.jpg' % image_id, thumbnail), | |
515 | } | |
516 | if image_id == 'tiny' and not artwork_url: | |
517 | size = 18 | |
518 | elif image_id == 'original': | |
519 | i['preference'] = 10 | |
520 | if size: | |
521 | i.update({ | |
522 | 'width': size, | |
523 | 'height': size, | |
524 | }) | |
525 | thumbnails.append(i) | |
526 | else: | |
527 | thumbnails = [{'url': thumbnail}] | |
528 | ||
529 | def extract_count(key): | |
530 | return int_or_none(info.get('%s_count' % key)) | |
531 | ||
532 | return { | |
533 | 'id': track_id, | |
534 | 'uploader': user.get('username'), | |
535 | 'uploader_id': str_or_none(user.get('id')) or user.get('permalink'), | |
536 | 'uploader_url': user.get('permalink_url'), | |
537 | 'timestamp': unified_timestamp(info.get('created_at')), | |
538 | 'title': title, | |
539 | 'description': info.get('description'), | |
540 | 'thumbnails': thumbnails, | |
541 | 'duration': float_or_none(info.get('duration'), 1000), | |
542 | 'webpage_url': info.get('permalink_url'), | |
543 | 'license': info.get('license'), | |
544 | 'view_count': extract_count('playback'), | |
545 | 'like_count': extract_count('favoritings') or extract_count('likes'), | |
546 | 'comment_count': extract_count('comment'), | |
547 | 'repost_count': extract_count('reposts'), | |
548 | 'genre': info.get('genre'), | |
549 | 'formats': formats | |
550 | } | |
551 | ||
552 | def _real_extract(self, url): | |
553 | mobj = re.match(self._VALID_URL, url) | |
554 | ||
555 | track_id = mobj.group('track_id') | |
556 | ||
557 | query = {} | |
558 | if track_id: | |
559 | info_json_url = self._API_V2_BASE + 'tracks/' + track_id | |
560 | full_title = track_id | |
561 | token = mobj.group('secret_token') | |
562 | if token: | |
563 | query['secret_token'] = token | |
564 | else: | |
565 | full_title = resolve_title = '%s/%s' % mobj.group('uploader', 'title') | |
566 | token = mobj.group('token') | |
567 | if token: | |
568 | resolve_title += '/%s' % token | |
569 | info_json_url = self._resolv_url(self._BASE_URL + resolve_title) | |
570 | ||
571 | info = self._download_json( | |
572 | info_json_url, full_title, 'Downloading info JSON', query=query, headers=self._HEADERS) | |
573 | ||
574 | return self._extract_info_dict(info, full_title, token) | |
575 | ||
576 | ||
577 | class SoundcloudPlaylistBaseIE(SoundcloudIE): | |
578 | def _extract_set(self, playlist, token=None): | |
579 | playlist_id = compat_str(playlist['id']) | |
580 | tracks = playlist.get('tracks') or [] | |
581 | if not all([t.get('permalink_url') for t in tracks]) and token: | |
582 | tracks = self._download_json( | |
583 | self._API_V2_BASE + 'tracks', playlist_id, | |
584 | 'Downloading tracks', query={ | |
585 | 'ids': ','.join([compat_str(t['id']) for t in tracks]), | |
586 | 'playlistId': playlist_id, | |
587 | 'playlistSecretToken': token, | |
588 | }, headers=self._HEADERS) | |
589 | entries = [] | |
590 | for track in tracks: | |
591 | track_id = str_or_none(track.get('id')) | |
592 | url = track.get('permalink_url') | |
593 | if not url: | |
594 | if not track_id: | |
595 | continue | |
596 | url = self._API_V2_BASE + 'tracks/' + track_id | |
597 | if token: | |
598 | url += '?secret_token=' + token | |
599 | entries.append(self.url_result( | |
600 | url, SoundcloudIE.ie_key(), track_id)) | |
601 | return self.playlist_result( | |
602 | entries, playlist_id, | |
603 | playlist.get('title'), | |
604 | playlist.get('description')) | |
605 | ||
606 | ||
607 | class SoundcloudSetIE(SoundcloudPlaylistBaseIE): | |
608 | _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/(?P<uploader>[\w\d-]+)/sets/(?P<slug_title>[:\w\d-]+)(?:/(?P<token>[^?/]+))?' | |
609 | IE_NAME = 'soundcloud:set' | |
610 | _TESTS = [{ | |
611 | 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep', | |
612 | 'info_dict': { | |
613 | 'id': '2284613', | |
614 | 'title': 'The Royal Concept EP', | |
615 | 'description': 'md5:71d07087c7a449e8941a70a29e34671e', | |
616 | }, | |
617 | 'playlist_mincount': 5, | |
618 | }, { | |
619 | 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep/token', | |
620 | 'only_matching': True, | |
621 | }, { | |
622 | 'url': 'https://soundcloud.com/discover/sets/weekly::flacmatic', | |
623 | 'only_matching': True, | |
624 | }, { | |
625 | 'url': 'https://soundcloud.com/discover/sets/charts-top:all-music:de', | |
626 | 'only_matching': True, | |
627 | }, { | |
628 | 'url': 'https://soundcloud.com/discover/sets/charts-top:hiphoprap:kr', | |
629 | 'only_matching': True, | |
630 | }] | |
631 | ||
632 | def _real_extract(self, url): | |
633 | mobj = re.match(self._VALID_URL, url) | |
634 | ||
635 | full_title = '%s/sets/%s' % mobj.group('uploader', 'slug_title') | |
636 | token = mobj.group('token') | |
637 | if token: | |
638 | full_title += '/' + token | |
639 | ||
640 | info = self._download_json(self._resolv_url( | |
641 | self._BASE_URL + full_title), full_title, headers=self._HEADERS) | |
642 | ||
643 | if 'errors' in info: | |
644 | msgs = (compat_str(err['error_message']) for err in info['errors']) | |
645 | raise ExtractorError('unable to download video webpage: %s' % ','.join(msgs)) | |
646 | ||
647 | return self._extract_set(info, token) | |
648 | ||
649 | ||
650 | class SoundcloudPagedPlaylistBaseIE(SoundcloudIE): | |
651 | def _extract_playlist(self, base_url, playlist_id, playlist_title): | |
652 | # Per the SoundCloud documentation, the maximum limit for a linked partitioning query is 200. | |
653 | # https://developers.soundcloud.com/blog/offset-pagination-deprecated | |
654 | COMMON_QUERY = { | |
655 | 'limit': 200, | |
656 | 'linked_partitioning': '1', | |
657 | } | |
658 | ||
659 | query = COMMON_QUERY.copy() | |
660 | query['offset'] = 0 | |
661 | ||
662 | next_href = base_url | |
663 | ||
664 | entries = [] | |
665 | for i in itertools.count(): | |
666 | response = self._download_json( | |
667 | next_href, playlist_id, | |
668 | 'Downloading track page %s' % (i + 1), query=query, headers=self._HEADERS) | |
669 | ||
670 | collection = response['collection'] | |
671 | ||
672 | if not isinstance(collection, list): | |
673 | collection = [] | |
674 | ||
675 | # Empty collection may be returned, in this case we proceed | |
676 | # straight to next_href | |
677 | ||
678 | def resolve_entry(candidates): | |
679 | for cand in candidates: | |
680 | if not isinstance(cand, dict): | |
681 | continue | |
682 | permalink_url = url_or_none(cand.get('permalink_url')) | |
683 | if not permalink_url: | |
684 | continue | |
685 | return self.url_result( | |
686 | permalink_url, | |
687 | SoundcloudIE.ie_key() if SoundcloudIE.suitable(permalink_url) else None, | |
688 | str_or_none(cand.get('id')), cand.get('title')) | |
689 | ||
690 | for e in collection: | |
691 | entry = resolve_entry((e, e.get('track'), e.get('playlist'))) | |
692 | if entry: | |
693 | entries.append(entry) | |
694 | ||
695 | next_href = response.get('next_href') | |
696 | if not next_href: | |
697 | break | |
698 | ||
699 | next_href = response['next_href'] | |
700 | parsed_next_href = compat_urlparse.urlparse(next_href) | |
701 | query = compat_urlparse.parse_qs(parsed_next_href.query) | |
702 | query.update(COMMON_QUERY) | |
703 | ||
704 | return { | |
705 | '_type': 'playlist', | |
706 | 'id': playlist_id, | |
707 | 'title': playlist_title, | |
708 | 'entries': entries, | |
709 | } | |
710 | ||
711 | ||
712 | class SoundcloudUserIE(SoundcloudPagedPlaylistBaseIE): | |
713 | _VALID_URL = r'''(?x) | |
714 | https?:// | |
715 | (?:(?:www|m)\.)?soundcloud\.com/ | |
716 | (?P<user>[^/]+) | |
717 | (?:/ | |
718 | (?P<rsrc>tracks|albums|sets|reposts|likes|spotlight) | |
719 | )? | |
720 | /?(?:[?#].*)?$ | |
721 | ''' | |
722 | IE_NAME = 'soundcloud:user' | |
723 | _TESTS = [{ | |
724 | 'url': 'https://soundcloud.com/soft-cell-official', | |
725 | 'info_dict': { | |
726 | 'id': '207965082', | |
727 | 'title': 'Soft Cell (All)', | |
728 | }, | |
729 | 'playlist_mincount': 28, | |
730 | }, { | |
731 | 'url': 'https://soundcloud.com/soft-cell-official/tracks', | |
732 | 'info_dict': { | |
733 | 'id': '207965082', | |
734 | 'title': 'Soft Cell (Tracks)', | |
735 | }, | |
736 | 'playlist_mincount': 27, | |
737 | }, { | |
738 | 'url': 'https://soundcloud.com/soft-cell-official/albums', | |
739 | 'info_dict': { | |
740 | 'id': '207965082', | |
741 | 'title': 'Soft Cell (Albums)', | |
742 | }, | |
743 | 'playlist_mincount': 1, | |
744 | }, { | |
745 | 'url': 'https://soundcloud.com/jcv246/sets', | |
746 | 'info_dict': { | |
747 | 'id': '12982173', | |
748 | 'title': 'Jordi / cv (Sets)', | |
749 | }, | |
750 | 'playlist_mincount': 2, | |
751 | }, { | |
752 | 'url': 'https://soundcloud.com/jcv246/reposts', | |
753 | 'info_dict': { | |
754 | 'id': '12982173', | |
755 | 'title': 'Jordi / cv (Reposts)', | |
756 | }, | |
757 | 'playlist_mincount': 6, | |
758 | }, { | |
759 | 'url': 'https://soundcloud.com/clalberg/likes', | |
760 | 'info_dict': { | |
761 | 'id': '11817582', | |
762 | 'title': 'clalberg (Likes)', | |
763 | }, | |
764 | 'playlist_mincount': 5, | |
765 | }, { | |
766 | 'url': 'https://soundcloud.com/grynpyret/spotlight', | |
767 | 'info_dict': { | |
768 | 'id': '7098329', | |
769 | 'title': 'Grynpyret (Spotlight)', | |
770 | }, | |
771 | 'playlist_mincount': 1, | |
772 | }] | |
773 | ||
774 | _BASE_URL_MAP = { | |
775 | 'all': 'stream/users/%s', | |
776 | 'tracks': 'users/%s/tracks', | |
777 | 'albums': 'users/%s/albums', | |
778 | 'sets': 'users/%s/playlists', | |
779 | 'reposts': 'stream/users/%s/reposts', | |
780 | 'likes': 'users/%s/likes', | |
781 | 'spotlight': 'users/%s/spotlight', | |
782 | } | |
783 | ||
784 | def _real_extract(self, url): | |
785 | mobj = re.match(self._VALID_URL, url) | |
786 | uploader = mobj.group('user') | |
787 | ||
788 | user = self._download_json( | |
789 | self._resolv_url(self._BASE_URL + uploader), | |
790 | uploader, 'Downloading user info', headers=self._HEADERS) | |
791 | ||
792 | resource = mobj.group('rsrc') or 'all' | |
793 | ||
794 | return self._extract_playlist( | |
795 | self._API_V2_BASE + self._BASE_URL_MAP[resource] % user['id'], | |
796 | str_or_none(user.get('id')), | |
797 | '%s (%s)' % (user['username'], resource.capitalize())) | |
798 | ||
799 | ||
800 | class SoundcloudTrackStationIE(SoundcloudPagedPlaylistBaseIE): | |
801 | _VALID_URL = r'https?://(?:(?:www|m)\.)?soundcloud\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)' | |
802 | IE_NAME = 'soundcloud:trackstation' | |
803 | _TESTS = [{ | |
804 | 'url': 'https://soundcloud.com/stations/track/officialsundial/your-text', | |
805 | 'info_dict': { | |
806 | 'id': '286017854', | |
807 | 'title': 'Track station: your text', | |
808 | }, | |
809 | 'playlist_mincount': 47, | |
810 | }] | |
811 | ||
812 | def _real_extract(self, url): | |
813 | track_name = self._match_id(url) | |
814 | ||
815 | track = self._download_json(self._resolv_url(url), track_name, headers=self._HEADERS) | |
816 | track_id = self._search_regex( | |
817 | r'soundcloud:track-stations:(\d+)', track['id'], 'track id') | |
818 | ||
819 | return self._extract_playlist( | |
820 | self._API_V2_BASE + 'stations/%s/tracks' % track['id'], | |
821 | track_id, 'Track station: %s' % track['title']) | |
822 | ||
823 | ||
824 | class SoundcloudPlaylistIE(SoundcloudPlaylistBaseIE): | |
825 | _VALID_URL = r'https?://api(?:-v2)?\.soundcloud\.com/playlists/(?P<id>[0-9]+)(?:/?\?secret_token=(?P<token>[^&]+?))?$' | |
826 | IE_NAME = 'soundcloud:playlist' | |
827 | _TESTS = [{ | |
828 | 'url': 'https://api.soundcloud.com/playlists/4110309', | |
829 | 'info_dict': { | |
830 | 'id': '4110309', | |
831 | 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]', | |
832 | 'description': 're:.*?TILT Brass - Bowery Poetry Club', | |
833 | }, | |
834 | 'playlist_count': 6, | |
835 | }] | |
836 | ||
837 | def _real_extract(self, url): | |
838 | mobj = re.match(self._VALID_URL, url) | |
839 | playlist_id = mobj.group('id') | |
840 | ||
841 | query = {} | |
842 | token = mobj.group('token') | |
843 | if token: | |
844 | query['secret_token'] = token | |
845 | ||
846 | data = self._download_json( | |
847 | self._API_V2_BASE + 'playlists/' + playlist_id, | |
848 | playlist_id, 'Downloading playlist', query=query, headers=self._HEADERS) | |
849 | ||
850 | return self._extract_set(data, token) | |
851 | ||
852 | ||
853 | class SoundcloudSearchIE(SearchInfoExtractor, SoundcloudIE): | |
854 | IE_NAME = 'soundcloud:search' | |
855 | IE_DESC = 'Soundcloud search' | |
856 | _MAX_RESULTS = float('inf') | |
857 | _TESTS = [{ | |
858 | 'url': 'scsearch15:post-avant jazzcore', | |
859 | 'info_dict': { | |
860 | 'title': 'post-avant jazzcore', | |
861 | }, | |
862 | 'playlist_count': 15, | |
863 | }] | |
864 | ||
865 | _SEARCH_KEY = 'scsearch' | |
866 | _MAX_RESULTS_PER_PAGE = 200 | |
867 | _DEFAULT_RESULTS_PER_PAGE = 50 | |
868 | ||
869 | def _get_collection(self, endpoint, collection_id, **query): | |
870 | limit = min( | |
871 | query.get('limit', self._DEFAULT_RESULTS_PER_PAGE), | |
872 | self._MAX_RESULTS_PER_PAGE) | |
873 | query.update({ | |
874 | 'limit': limit, | |
875 | 'linked_partitioning': 1, | |
876 | 'offset': 0, | |
877 | }) | |
878 | next_url = update_url_query(self._API_V2_BASE + endpoint, query) | |
879 | ||
880 | collected_results = 0 | |
881 | ||
882 | for i in itertools.count(1): | |
883 | response = self._download_json( | |
884 | next_url, collection_id, 'Downloading page {0}'.format(i), | |
885 | 'Unable to download API page', headers=self._HEADERS) | |
886 | ||
887 | collection = response.get('collection', []) | |
888 | if not collection: | |
889 | break | |
890 | ||
891 | collection = list(filter(bool, collection)) | |
892 | collected_results += len(collection) | |
893 | ||
894 | for item in collection: | |
895 | yield self.url_result(item['uri'], SoundcloudIE.ie_key()) | |
896 | ||
897 | if not collection or collected_results >= limit: | |
898 | break | |
899 | ||
900 | next_url = response.get('next_href') | |
901 | if not next_url: | |
902 | break | |
903 | ||
904 | def _get_n_results(self, query, n): | |
905 | tracks = self._get_collection('search/tracks', query, limit=n, q=query) | |
906 | return self.playlist_result(tracks, playlist_title=query) |