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