]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/soundcloud.py
Prepare for upload.
[youtubedl] / youtube_dl / extractor / soundcloud.py
1 import json
2 import re
3 import itertools
4
5 from .common import InfoExtractor
6 from ..utils import (
7 compat_str,
8 compat_urlparse,
9 compat_urllib_parse,
10
11 ExtractorError,
12 unified_strdate,
13 )
14
15
16 class SoundcloudIE(InfoExtractor):
17 """Information extractor for soundcloud.com
18 To access the media, the uid of the song and a stream token
19 must be extracted from the page source and the script must make
20 a request to media.soundcloud.com/crossdomain.xml. Then
21 the media can be grabbed by requesting from an url composed
22 of the stream token and uid
23 """
24
25 _VALID_URL = r'''^(?:https?://)?
26 (?:(?:(?:www\.)?soundcloud\.com/([\w\d-]+)/([\w\d-]+)/?(?:[?].*)?$)
27 |(?:api\.soundcloud\.com/tracks/(?P<track_id>\d+))
28 |(?P<widget>w.soundcloud.com/player/?.*?url=.*)
29 )
30 '''
31 IE_NAME = u'soundcloud'
32 _TESTS = [
33 {
34 u'url': u'http://soundcloud.com/ethmusic/lostin-powers-she-so-heavy',
35 u'file': u'62986583.mp3',
36 u'md5': u'ebef0a451b909710ed1d7787dddbf0d7',
37 u'info_dict': {
38 u"upload_date": u"20121011",
39 u"description": u"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",
40 u"uploader": u"E.T. ExTerrestrial Music",
41 u"title": u"Lostin Powers - She so Heavy (SneakPreview) Adrian Ackers Blueprint 1"
42 }
43 },
44 # not streamable song
45 {
46 u'url': u'https://soundcloud.com/the-concept-band/goldrushed-mastered?in=the-concept-band/sets/the-royal-concept-ep',
47 u'info_dict': {
48 u'id': u'47127627',
49 u'ext': u'mp3',
50 u'title': u'Goldrushed',
51 u'uploader': u'The Royal Concept',
52 u'upload_date': u'20120521',
53 },
54 u'params': {
55 # rtmp
56 u'skip_download': True,
57 },
58 },
59 ]
60
61 _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
62
63 @classmethod
64 def suitable(cls, url):
65 return re.match(cls._VALID_URL, url, flags=re.VERBOSE) is not None
66
67 def report_resolve(self, video_id):
68 """Report information extraction."""
69 self.to_screen(u'%s: Resolving id' % video_id)
70
71 @classmethod
72 def _resolv_url(cls, url):
73 return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
74
75 def _extract_info_dict(self, info, full_title=None, quiet=False):
76 track_id = compat_str(info['id'])
77 name = full_title or track_id
78 if quiet == False:
79 self.report_extraction(name)
80
81 thumbnail = info['artwork_url']
82 if thumbnail is not None:
83 thumbnail = thumbnail.replace('-large', '-t500x500')
84 result = {
85 'id': track_id,
86 'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
87 'uploader': info['user']['username'],
88 'upload_date': unified_strdate(info['created_at']),
89 'title': info['title'],
90 'ext': u'mp3',
91 'description': info['description'],
92 'thumbnail': thumbnail,
93 }
94 if info.get('downloadable', False):
95 result['url'] = 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(track_id, self._CLIENT_ID)
96 if not info.get('streamable', False):
97 # We have to get the rtmp url
98 stream_json = self._download_webpage(
99 'http://api.soundcloud.com/i1/tracks/{0}/streams?client_id={1}'.format(track_id, self._CLIENT_ID),
100 track_id, u'Downloading track url')
101 rtmp_url = json.loads(stream_json)['rtmp_mp3_128_url']
102 # The url doesn't have an rtmp app, we have to extract the playpath
103 url, path = rtmp_url.split('mp3:', 1)
104 result.update({
105 'url': url,
106 'play_path': 'mp3:' + path,
107 })
108 return result
109
110 def _real_extract(self, url):
111 mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
112 if mobj is None:
113 raise ExtractorError(u'Invalid URL: %s' % url)
114
115 track_id = mobj.group('track_id')
116 if track_id is not None:
117 info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
118 full_title = track_id
119 elif mobj.group('widget'):
120 query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
121 return self.url_result(query['url'][0], ie='Soundcloud')
122 else:
123 # extract uploader (which is in the url)
124 uploader = mobj.group(1)
125 # extract simple title (uploader + slug of song title)
126 slug_title = mobj.group(2)
127 full_title = '%s/%s' % (uploader, slug_title)
128
129 self.report_resolve(full_title)
130
131 url = 'http://soundcloud.com/%s/%s' % (uploader, slug_title)
132 info_json_url = self._resolv_url(url)
133 info_json = self._download_webpage(info_json_url, full_title, u'Downloading info JSON')
134
135 info = json.loads(info_json)
136 return self._extract_info_dict(info, full_title)
137
138 class SoundcloudSetIE(SoundcloudIE):
139 _VALID_URL = r'^(?:https?://)?(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)(?:[?].*)?$'
140 IE_NAME = u'soundcloud:set'
141 # it's in tests/test_playlists.py
142 _TESTS = []
143
144 def _real_extract(self, url):
145 mobj = re.match(self._VALID_URL, url)
146 if mobj is None:
147 raise ExtractorError(u'Invalid URL: %s' % url)
148
149 # extract uploader (which is in the url)
150 uploader = mobj.group(1)
151 # extract simple title (uploader + slug of song title)
152 slug_title = mobj.group(2)
153 full_title = '%s/sets/%s' % (uploader, slug_title)
154
155 self.report_resolve(full_title)
156
157 url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
158 resolv_url = self._resolv_url(url)
159 info_json = self._download_webpage(resolv_url, full_title)
160
161 videos = []
162 info = json.loads(info_json)
163 if 'errors' in info:
164 for err in info['errors']:
165 self._downloader.report_error(u'unable to download video webpage: %s' % compat_str(err['error_message']))
166 return
167
168 self.report_extraction(full_title)
169 return {'_type': 'playlist',
170 'entries': [self._extract_info_dict(track) for track in info['tracks']],
171 'id': info['id'],
172 'title': info['title'],
173 }
174
175
176 class SoundcloudUserIE(SoundcloudIE):
177 _VALID_URL = r'https?://(www\.)?soundcloud.com/(?P<user>[^/]+)(/?(tracks/)?)?(\?.*)?$'
178 IE_NAME = u'soundcloud:user'
179
180 # it's in tests/test_playlists.py
181 _TESTS = []
182
183 def _real_extract(self, url):
184 mobj = re.match(self._VALID_URL, url)
185 uploader = mobj.group('user')
186
187 url = 'http://soundcloud.com/%s/' % uploader
188 resolv_url = self._resolv_url(url)
189 user_json = self._download_webpage(resolv_url, uploader,
190 u'Downloading user info')
191 user = json.loads(user_json)
192
193 tracks = []
194 for i in itertools.count():
195 data = compat_urllib_parse.urlencode({'offset': i*50,
196 'client_id': self._CLIENT_ID,
197 })
198 tracks_url = 'http://api.soundcloud.com/users/%s/tracks.json?' % user['id'] + data
199 response = self._download_webpage(tracks_url, uploader,
200 u'Downloading tracks page %s' % (i+1))
201 new_tracks = json.loads(response)
202 tracks.extend(self._extract_info_dict(track, quiet=True) for track in new_tracks)
203 if len(new_tracks) < 50:
204 break
205
206 return {
207 '_type': 'playlist',
208 'id': compat_str(user['id']),
209 'title': user['username'],
210 'entries': tracks,
211 }