]> jfr.im git - yt-dlp.git/blob - youtube_dl/extractor/soundcloud.py
Merge branch 'peugeot-tnaflix'
[yt-dlp.git] / youtube_dl / extractor / soundcloud.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import itertools
6
7 from .common import InfoExtractor
8 from ..utils import (
9 compat_str,
10 compat_urlparse,
11 compat_urllib_parse,
12
13 ExtractorError,
14 int_or_none,
15 unified_strdate,
16 )
17
18
19 class SoundcloudIE(InfoExtractor):
20 """Information extractor for soundcloud.com
21 To access the media, the uid of the song and a stream token
22 must be extracted from the page source and the script must make
23 a request to media.soundcloud.com/crossdomain.xml. Then
24 the media can be grabbed by requesting from an url composed
25 of the stream token and uid
26 """
27
28 _VALID_URL = r'''(?x)^(?:https?://)?
29 (?:(?:(?:www\.|m\.)?soundcloud\.com/
30 (?P<uploader>[\w\d-]+)/
31 (?!sets/|likes/?(?:$|[?#]))
32 (?P<title>[\w\d-]+)/?
33 (?P<token>[^?]+?)?(?:[?].*)?$)
34 |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+))
35 |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
36 )
37 '''
38 IE_NAME = 'soundcloud'
39 _TESTS = [
40 {
41 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
42 'file': '62986583.mp3',
43 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
44 'info_dict': {
45 "upload_date": "20121011",
46 "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",
47 "uploader": "E.T. ExTerrestrial Music",
48 "title": "Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1",
49 "duration": 143,
50 }
51 },
52 # not streamable song
53 {
54 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
55 'info_dict': {
56 'id': '47127627',
57 'ext': 'mp3',
58 'title': 'Goldrushed',
59 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
60 'uploader': 'The Royal Concept',
61 'upload_date': '20120521',
62 'duration': 227,
63 },
64 'params': {
65 # rtmp
66 'skip_download': True,
67 },
68 },
69 # private link
70 {
71 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
72 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
73 'info_dict': {
74 'id': '123998367',
75 'ext': 'mp3',
76 'title': 'Youtube - Dl Test Video \'\' Ä↭',
77 'uploader': 'jaimeMF',
78 'description': 'test chars: \"\'/\\ä↭',
79 'upload_date': '20131209',
80 'duration': 9,
81 },
82 },
83 # downloadable song
84 {
85 'url': 'https://soundcloud.com/oddsamples/bus-brakes',
86 'md5': '7624f2351f8a3b2e7cd51522496e7631',
87 'info_dict': {
88 'id': '128590877',
89 'ext': 'mp3',
90 'title': 'Bus Brakes',
91 'description': 'md5:0170be75dd395c96025d210d261c784e',
92 'uploader': 'oddsamples',
93 'upload_date': '20140109',
94 'duration': 17,
95 },
96 },
97 ]
98
99 _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
100 _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
101
102 def report_resolve(self, video_id):
103 """Report information extraction."""
104 self.to_screen('%s: Resolving id' % video_id)
105
106 @classmethod
107 def _resolv_url(cls, url):
108 return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
109
110 def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
111 track_id = compat_str(info['id'])
112 name = full_title or track_id
113 if quiet:
114 self.report_extraction(name)
115
116 thumbnail = info['artwork_url']
117 if thumbnail is not None:
118 thumbnail = thumbnail.replace('-large', '-t500x500')
119 ext = 'mp3'
120 result = {
121 'id': track_id,
122 'uploader': info['user']['username'],
123 'upload_date': unified_strdate(info['created_at']),
124 'title': info['title'],
125 'description': info['description'],
126 'thumbnail': thumbnail,
127 'duration': int_or_none(info.get('duration'), 1000),
128 }
129 formats = []
130 if info.get('downloadable', False):
131 # We can build a direct link to the song
132 format_url = (
133 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
134 track_id, self._CLIENT_ID))
135 formats.append({
136 'format_id': 'download',
137 'ext': info.get('original_format', 'mp3'),
138 'url': format_url,
139 'vcodec': 'none',
140 'preference': 10,
141 })
142
143 # We have to retrieve the url
144 streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
145 'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
146 format_dict = self._download_json(
147 streams_url,
148 track_id, 'Downloading track url')
149
150 for key, stream_url in format_dict.items():
151 if key.startswith('http'):
152 formats.append({
153 'format_id': key,
154 'ext': ext,
155 'url': stream_url,
156 'vcodec': 'none',
157 })
158 elif key.startswith('rtmp'):
159 # The url doesn't have an rtmp app, we have to extract the playpath
160 url, path = stream_url.split('mp3:', 1)
161 formats.append({
162 'format_id': key,
163 'url': url,
164 'play_path': 'mp3:' + path,
165 'ext': ext,
166 'vcodec': 'none',
167 })
168
169 if not formats:
170 # We fallback to the stream_url in the original info, this
171 # cannot be always used, sometimes it can give an HTTP 404 error
172 formats.append({
173 'format_id': 'fallback',
174 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
175 'ext': ext,
176 'vcodec': 'none',
177 })
178
179 for f in formats:
180 if f['format_id'].startswith('http'):
181 f['protocol'] = 'http'
182 if f['format_id'].startswith('rtmp'):
183 f['protocol'] = 'rtmp'
184
185 self._sort_formats(formats)
186 result['formats'] = formats
187
188 return result
189
190 def _real_extract(self, url):
191 mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
192 if mobj is None:
193 raise ExtractorError('Invalid URL: %s' % url)
194
195 track_id = mobj.group('track_id')
196 token = None
197 if track_id is not None:
198 info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
199 full_title = track_id
200 elif mobj.group('player'):
201 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
202 return self.url_result(query['url'][0])
203 else:
204 # extract uploader (which is in the url)
205 uploader = mobj.group('uploader')
206 # extract simple title (uploader + slug of song title)
207 slug_title = mobj.group('title')
208 token = mobj.group('token')
209 full_title = resolve_title = '%s/%s' % (uploader, slug_title)
210 if token:
211 resolve_title += '/%s' % token
212
213 self.report_resolve(full_title)
214
215 url = 'http://soundcloud.com/%s' % resolve_title
216 info_json_url = self._resolv_url(url)
217 info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
218
219 return self._extract_info_dict(info, full_title, secret_token=token)
220
221
222 class SoundcloudSetIE(SoundcloudIE):
223 _VALID_URL = r'https?://(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)'
224 IE_NAME = 'soundcloud:set'
225 _TESTS = [{
226 'url': 'https://soundcloud.com/the-concept-band/sets/the-royal-concept-ep',
227 'info_dict': {
228 'title': 'The Royal Concept EP',
229 },
230 'playlist_mincount': 6,
231 }]
232
233 def _real_extract(self, url):
234 mobj = re.match(self._VALID_URL, url)
235
236 # extract uploader (which is in the url)
237 uploader = mobj.group(1)
238 # extract simple title (uploader + slug of song title)
239 slug_title = mobj.group(2)
240 full_title = '%s/sets/%s' % (uploader, slug_title)
241
242 self.report_resolve(full_title)
243
244 url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
245 resolv_url = self._resolv_url(url)
246 info = self._download_json(resolv_url, full_title)
247
248 if 'errors' in info:
249 for err in info['errors']:
250 self._downloader.report_error('unable to download video webpage: %s' % compat_str(err['error_message']))
251 return
252
253 return {
254 '_type': 'playlist',
255 'entries': [self._extract_info_dict(track) for track in info['tracks']],
256 'id': info['id'],
257 'title': info['title'],
258 }
259
260
261 class SoundcloudUserIE(SoundcloudIE):
262 _VALID_URL = r'https?://(www\.)?soundcloud\.com/(?P<user>[^/]+)/?((?P<rsrc>tracks|likes)/?)?(\?.*)?$'
263 IE_NAME = 'soundcloud:user'
264 _TESTS = [{
265 'url': 'https://soundcloud.com/the-concept-band',
266 'info_dict': {
267 'id': '9615865',
268 'title': 'The Royal Concept',
269 },
270 'playlist_mincount': 12
271 }, {
272 'url': 'https://soundcloud.com/the-concept-band/likes',
273 'info_dict': {
274 'id': '9615865',
275 'title': 'The Royal Concept',
276 },
277 'playlist_mincount': 1,
278 }]
279
280 def _real_extract(self, url):
281 mobj = re.match(self._VALID_URL, url)
282 uploader = mobj.group('user')
283 resource = mobj.group('rsrc')
284 if resource is None:
285 resource = 'tracks'
286 elif resource == 'likes':
287 resource = 'favorites'
288
289 url = 'http://soundcloud.com/%s/' % uploader
290 resolv_url = self._resolv_url(url)
291 user = self._download_json(
292 resolv_url, uploader, 'Downloading user info')
293 base_url = 'http://api.soundcloud.com/users/%s/%s.json?' % (uploader, resource)
294
295 entries = []
296 for i in itertools.count():
297 data = compat_urllib_parse.urlencode({
298 'offset': i * 50,
299 'limit': 50,
300 'client_id': self._CLIENT_ID,
301 })
302 new_entries = self._download_json(
303 base_url + data, uploader, 'Downloading track page %s' % (i + 1))
304 if len(new_entries) == 0:
305 self.to_screen('%s: End page received' % uploader)
306 break
307 entries.extend(self._extract_info_dict(e, quiet=True) for e in new_entries)
308
309 return {
310 '_type': 'playlist',
311 'id': compat_str(user['id']),
312 'title': user['username'],
313 'entries': entries,
314 }
315
316
317 class SoundcloudPlaylistIE(SoundcloudIE):
318 _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)'
319 IE_NAME = 'soundcloud:playlist'
320 _TESTS = [
321
322 {
323 'url': 'http://api.soundcloud.com/playlists/4110309',
324 'info_dict': {
325 'id': '4110309',
326 'title': 'TILT Brass - Bowery Poetry Club, August \'03 [Non-Site SCR 02]',
327 'description': 're:.*?TILT Brass - Bowery Poetry Club',
328 },
329 'playlist_count': 6,
330 }
331 ]
332
333 def _real_extract(self, url):
334 mobj = re.match(self._VALID_URL, url)
335 playlist_id = mobj.group('id')
336 base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
337
338 data = compat_urllib_parse.urlencode({
339 'client_id': self._CLIENT_ID,
340 })
341 data = self._download_json(
342 base_url + data, playlist_id, 'Downloading playlist')
343
344 entries = [
345 self._extract_info_dict(t, quiet=True) for t in data['tracks']]
346
347 return {
348 '_type': 'playlist',
349 'id': playlist_id,
350 'title': data.get('title'),
351 'description': data.get('description'),
352 'entries': entries,
353 }