]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/soundcloud.py
Imported Upstream version 2014.01.17.2
[youtubedl] / youtube_dl / extractor / soundcloud.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import json
5 import re
6 import itertools
7
8 from .common import InfoExtractor
9 from ..utils import (
10 compat_str,
11 compat_urlparse,
12 compat_urllib_parse,
13
14 ExtractorError,
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'''^(?:https?://)?
29 (?:(?:(?:www\.|m\.)?soundcloud\.com/
30 (?P<uploader>[\w\d-]+)/
31 (?!sets/)(?P<title>[\w\d-]+)/?
32 (?P<token>[^?]+?)?(?:[?].*)?$)
33 |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+))
34 |(?P<player>(?:w|player|p.)\.soundcloud\.com/player/?.*?url=.*)
35 )
36 '''
37 IE_NAME = 'soundcloud'
38 _TESTS = [
39 {
40 'url': 'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
41 'file': '62986583.mp3',
42 'md5': 'ebef0a451b909710ed1d7787dddbf0d7',
43 'info_dict': {
44 "upload_date": "20121011",
45 "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",
46 "uploader": "E.T. ExTerrestrial Music",
47 "title": "Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1"
48 }
49 },
50 # not streamable song
51 {
52 'url': 'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
53 'info_dict': {
54 'id': '47127627',
55 'ext': 'mp3',
56 'title': 'Goldrushed',
57 'uploader': 'The Royal Concept',
58 'upload_date': '20120521',
59 },
60 'params': {
61 # rtmp
62 'skip_download': True,
63 },
64 },
65 # private link
66 {
67 'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
68 'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
69 'info_dict': {
70 'id': '123998367',
71 'ext': 'mp3',
72 'title': 'Youtube - Dl Test Video \'\' Ä↭',
73 'uploader': 'jaimeMF',
74 'description': 'test chars: \"\'/\\ä↭',
75 'upload_date': '20131209',
76 },
77 },
78 # downloadable song
79 {
80 'url': 'https://soundcloud.com/simgretina/just-your-problem-baby-1',
81 'md5': '56a8b69568acaa967b4c49f9d1d52d19',
82 'info_dict': {
83 'id': '105614606',
84 'ext': 'wav',
85 'title': 'Just Your Problem Baby (Acapella)',
86 'description': 'Vocals',
87 'uploader': 'Sim Gretina',
88 'upload_date': '20130815',
89 },
90 },
91 ]
92
93 _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
94 _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
95
96 @classmethod
97 def suitable(cls, url):
98 return re.match(cls._VALID_URL, url, flags=re.VERBOSE) is not None
99
100 def report_resolve(self, video_id):
101 """Report information extraction."""
102 self.to_screen(u'%s: Resolving id' % video_id)
103
104 @classmethod
105 def _resolv_url(cls, url):
106 return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
107
108 def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
109 track_id = compat_str(info['id'])
110 name = full_title or track_id
111 if quiet:
112 self.report_extraction(name)
113
114 thumbnail = info['artwork_url']
115 if thumbnail is not None:
116 thumbnail = thumbnail.replace('-large', '-t500x500')
117 ext = 'mp3'
118 result = {
119 'id': track_id,
120 'uploader': info['user']['username'],
121 'upload_date': unified_strdate(info['created_at']),
122 'title': info['title'],
123 'description': info['description'],
124 'thumbnail': thumbnail,
125 }
126 if info.get('downloadable', False):
127 # We can build a direct link to the song
128 format_url = (
129 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
130 track_id, self._CLIENT_ID))
131 result['formats'] = [{
132 'format_id': 'download',
133 'ext': info.get('original_format', 'mp3'),
134 'url': format_url,
135 'vcodec': 'none',
136 }]
137 else:
138 # We have to retrieve the url
139 streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
140 'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
141 stream_json = self._download_webpage(
142 streams_url,
143 track_id, 'Downloading track url')
144
145 formats = []
146 format_dict = json.loads(stream_json)
147 for key, stream_url in format_dict.items():
148 if key.startswith(u'http'):
149 formats.append({
150 'format_id': key,
151 'ext': ext,
152 'url': stream_url,
153 'vcodec': 'none',
154 })
155 elif key.startswith(u'rtmp'):
156 # The url doesn't have an rtmp app, we have to extract the playpath
157 url, path = stream_url.split('mp3:', 1)
158 formats.append({
159 'format_id': key,
160 'url': url,
161 'play_path': 'mp3:' + path,
162 'ext': ext,
163 'vcodec': 'none',
164 })
165
166 if not formats:
167 # We fallback to the stream_url in the original info, this
168 # cannot be always used, sometimes it can give an HTTP 404 error
169 formats.append({
170 'format_id': 'fallback',
171 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
172 'ext': ext,
173 'vcodec': 'none',
174 })
175
176 for f in formats:
177 if f['format_id'].startswith('http'):
178 f['protocol'] = 'http'
179 if f['format_id'].startswith('rtmp'):
180 f['protocol'] = 'rtmp'
181
182 self._sort_formats(formats)
183 result['formats'] = formats
184
185 return result
186
187 def _real_extract(self, url):
188 mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
189 if mobj is None:
190 raise ExtractorError(u'Invalid URL: %s' % url)
191
192 track_id = mobj.group('track_id')
193 token = None
194 if track_id is not None:
195 info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
196 full_title = track_id
197 elif mobj.group('player'):
198 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
199 return self.url_result(query['url'][0], ie='Soundcloud')
200 else:
201 # extract uploader (which is in the url)
202 uploader = mobj.group('uploader')
203 # extract simple title (uploader + slug of song title)
204 slug_title = mobj.group('title')
205 token = mobj.group('token')
206 full_title = resolve_title = '%s/%s' % (uploader, slug_title)
207 if token:
208 resolve_title += '/%s' % token
209
210 self.report_resolve(full_title)
211
212 url = 'http://soundcloud.com/%s' % resolve_title
213 info_json_url = self._resolv_url(url)
214 info_json = self._download_webpage(info_json_url, full_title, 'Downloading info JSON')
215
216 info = json.loads(info_json)
217 return self._extract_info_dict(info, full_title, secret_token=token)
218
219 class SoundcloudSetIE(SoundcloudIE):
220 _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)(?:[?].*)?$'
221 IE_NAME = 'soundcloud:set'
222 # it's in tests/test_playlists.py
223 _TESTS = []
224
225 def _real_extract(self, url):
226 mobj = re.match(self._VALID_URL, url)
227 if mobj is None:
228 raise ExtractorError(u'Invalid URL: %s' % url)
229
230 # extract uploader (which is in the url)
231 uploader = mobj.group(1)
232 # extract simple title (uploader + slug of song title)
233 slug_title = mobj.group(2)
234 full_title = '%s/sets/%s' % (uploader, slug_title)
235
236 self.report_resolve(full_title)
237
238 url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
239 resolv_url = self._resolv_url(url)
240 info_json = self._download_webpage(resolv_url, full_title)
241
242 info = json.loads(info_json)
243 if 'errors' in info:
244 for err in info['errors']:
245 self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err['error_message']))
246 return
247
248 self.report_extraction(full_title)
249 return {'_type': 'playlist',
250 'entries': [self._extract_info_dict(track) for track in info['tracks']],
251 'id': info['id'],
252 'title': info['title'],
253 }
254
255
256 class SoundcloudUserIE(SoundcloudIE):
257 _VALID_URL = r'https?://(www\.)?soundcloud\.com/(?P<user>[^/]+)(/?(tracks/)?)?(\?.*)?$'
258 IE_NAME = 'soundcloud:user'
259
260 # it's in tests/test_playlists.py
261 _TESTS = []
262
263 def _real_extract(self, url):
264 mobj = re.match(self._VALID_URL, url)
265 uploader = mobj.group('user')
266
267 url = 'http://soundcloud.com/%s/' % uploader
268 resolv_url = self._resolv_url(url)
269 user_json = self._download_webpage(resolv_url, uploader,
270 'Downloading user info')
271 user = json.loads(user_json)
272
273 tracks = []
274 for i in itertools.count():
275 data = compat_urllib_parse.urlencode({'offset': i*50,
276 'client_id': self._CLIENT_ID,
277 })
278 tracks_url = 'http://api.soundcloud.com/users/%s/tracks.json?' % user['id'] + data
279 response = self._download_webpage(tracks_url, uploader,
280 'Downloading tracks page %s' % (i+1))
281 new_tracks = json.loads(response)
282 tracks.extend(self._extract_info_dict(track, quiet=True) for track in new_tracks)
283 if len(new_tracks) < 50:
284 break
285
286 return {
287 '_type': 'playlist',
288 'id': compat_str(user['id']),
289 'title': user['username'],
290 'entries': tracks,
291 }