]> git.bitcoin.ninja Git - youtube-dl/blob - youtube_dl/extractor/soundcloud.py
Merge branch 'ustream-embed-recorded2' of https://github.com/anovicecodemonkey/youtub...
[youtube-dl] / 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'''(?x)^(?: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                 'description': 'From Stockholm Sweden\r\nPovel / Magnus / Filip / David\r\nwww.theroyalconcept.com',
58                 'uploader': 'The Royal Concept',
59                 'upload_date': '20120521',
60             },
61             'params': {
62                 # rtmp
63                 'skip_download': True,
64             },
65         },
66         # private link
67         {
68             'url': 'https://soundcloud.com/jaimemf/youtube-dl-test-video-a-y-baw/s-8Pjrp',
69             'md5': 'aa0dd32bfea9b0c5ef4f02aacd080604',
70             'info_dict': {
71                 'id': '123998367',
72                 'ext': 'mp3',
73                 'title': 'Youtube - Dl Test Video \'\' Ä↭',
74                 'uploader': 'jaimeMF',
75                 'description': 'test chars:  \"\'/\\ä↭',
76                 'upload_date': '20131209',
77             },
78         },
79         # downloadable song
80         {
81             'url': 'https://soundcloud.com/simgretina/just-your-problem-baby-1',
82             'md5': '56a8b69568acaa967b4c49f9d1d52d19',
83             'info_dict': {
84                 'id': '105614606',
85                 'ext': 'wav',
86                 'title': 'Just Your Problem Baby (Acapella)',
87                 'description': 'Vocals',
88                 'uploader': 'Sim Gretina',
89                 'upload_date': '20130815',
90             },
91         },
92     ]
93
94     _CLIENT_ID = 'b45b1aa10f1ac2941910a7f0d10f8e28'
95     _IPHONE_CLIENT_ID = '376f225bf427445fc4bfb6b99b72e0bf'
96
97     def report_resolve(self, video_id):
98         """Report information extraction."""
99         self.to_screen('%s: Resolving id' % video_id)
100
101     @classmethod
102     def _resolv_url(cls, url):
103         return 'http://api.soundcloud.com/resolve.json?url=' + url + '&client_id=' + cls._CLIENT_ID
104
105     def _extract_info_dict(self, info, full_title=None, quiet=False, secret_token=None):
106         track_id = compat_str(info['id'])
107         name = full_title or track_id
108         if quiet:
109             self.report_extraction(name)
110
111         thumbnail = info['artwork_url']
112         if thumbnail is not None:
113             thumbnail = thumbnail.replace('-large', '-t500x500')
114         ext = 'mp3'
115         result = {
116             'id': track_id,
117             'uploader': info['user']['username'],
118             'upload_date': unified_strdate(info['created_at']),
119             'title': info['title'],
120             'description': info['description'],
121             'thumbnail': thumbnail,
122         }
123         formats = []
124         if info.get('downloadable', False):
125             # We can build a direct link to the song
126             format_url = (
127                 'https://api.soundcloud.com/tracks/{0}/download?client_id={1}'.format(
128                     track_id, self._CLIENT_ID))
129             formats.append({
130                 'format_id': 'download',
131                 'ext': info.get('original_format', 'mp3'),
132                 'url': format_url,
133                 'vcodec': 'none',
134                 'preference': 10,
135             })
136
137         # We have to retrieve the url
138         streams_url = ('http://api.soundcloud.com/i1/tracks/{0}/streams?'
139             'client_id={1}&secret_token={2}'.format(track_id, self._IPHONE_CLIENT_ID, secret_token))
140         format_dict = self._download_json(
141             streams_url,
142             track_id, 'Downloading track url')
143
144         for key, stream_url in format_dict.items():
145             if key.startswith('http'):
146                 formats.append({
147                     'format_id': key,
148                     'ext': ext,
149                     'url': stream_url,
150                     'vcodec': 'none',
151                 })
152             elif key.startswith('rtmp'):
153                 # The url doesn't have an rtmp app, we have to extract the playpath
154                 url, path = stream_url.split('mp3:', 1)
155                 formats.append({
156                     'format_id': key,
157                     'url': url,
158                     'play_path': 'mp3:' + path,
159                     'ext': ext,
160                     'vcodec': 'none',
161                 })
162
163             if not formats:
164                 # We fallback to the stream_url in the original info, this
165                 # cannot be always used, sometimes it can give an HTTP 404 error
166                 formats.append({
167                     'format_id': 'fallback',
168                     'url': info['stream_url'] + '?client_id=' + self._CLIENT_ID,
169                     'ext': ext,
170                     'vcodec': 'none',
171                 })
172
173             for f in formats:
174                 if f['format_id'].startswith('http'):
175                     f['protocol'] = 'http'
176                 if f['format_id'].startswith('rtmp'):
177                     f['protocol'] = 'rtmp'
178
179             self._sort_formats(formats)
180             result['formats'] = formats
181
182         return result
183
184     def _real_extract(self, url):
185         mobj = re.match(self._VALID_URL, url, flags=re.VERBOSE)
186         if mobj is None:
187             raise ExtractorError('Invalid URL: %s' % url)
188
189         track_id = mobj.group('track_id')
190         token = None
191         if track_id is not None:
192             info_json_url = 'http://api.soundcloud.com/tracks/' + track_id + '.json?client_id=' + self._CLIENT_ID
193             full_title = track_id
194         elif mobj.group('player'):
195             query = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
196             return self.url_result(query['url'][0])
197         else:
198             # extract uploader (which is in the url)
199             uploader = mobj.group('uploader')
200             # extract simple title (uploader + slug of song title)
201             slug_title =  mobj.group('title')
202             token = mobj.group('token')
203             full_title = resolve_title = '%s/%s' % (uploader, slug_title)
204             if token:
205                 resolve_title += '/%s' % token
206     
207             self.report_resolve(full_title)
208     
209             url = 'http://soundcloud.com/%s' % resolve_title
210             info_json_url = self._resolv_url(url)
211         info = self._download_json(info_json_url, full_title, 'Downloading info JSON')
212
213         return self._extract_info_dict(info, full_title, secret_token=token)
214
215
216 class SoundcloudSetIE(SoundcloudIE):
217     _VALID_URL = r'https?://(?:www\.)?soundcloud\.com/([\w\d-]+)/sets/([\w\d-]+)'
218     IE_NAME = 'soundcloud:set'
219     # it's in tests/test_playlists.py
220     _TESTS = []
221
222     def _real_extract(self, url):
223         mobj = re.match(self._VALID_URL, url)
224         if mobj is None:
225             raise ExtractorError('Invalid URL: %s' % url)
226
227         # extract uploader (which is in the url)
228         uploader = mobj.group(1)
229         # extract simple title (uploader + slug of song title)
230         slug_title = mobj.group(2)
231         full_title = '%s/sets/%s' % (uploader, slug_title)
232
233         self.report_resolve(full_title)
234
235         url = 'http://soundcloud.com/%s/sets/%s' % (uploader, slug_title)
236         resolv_url = self._resolv_url(url)
237         info = self._download_json(resolv_url, full_title)
238
239         if 'errors' in info:
240             for err in info['errors']:
241                 self._downloader.report_error('unable to download video webpage: %s' % compat_str(err['error_message']))
242             return
243
244         self.report_extraction(full_title)
245         return {'_type': 'playlist',
246                 'entries': [self._extract_info_dict(track) for track in info['tracks']],
247                 'id': info['id'],
248                 'title': info['title'],
249                 }
250
251
252 class SoundcloudUserIE(SoundcloudIE):
253     _VALID_URL = r'https?://(www\.)?soundcloud\.com/(?P<user>[^/]+)(/?(tracks/)?)?(\?.*)?$'
254     IE_NAME = 'soundcloud:user'
255
256     # it's in tests/test_playlists.py
257     _TESTS = []
258
259     def _real_extract(self, url):
260         mobj = re.match(self._VALID_URL, url)
261         uploader = mobj.group('user')
262
263         url = 'http://soundcloud.com/%s/' % uploader
264         resolv_url = self._resolv_url(url)
265         user = self._download_json(
266             resolv_url, uploader, 'Downloading user info')
267         base_url = 'http://api.soundcloud.com/users/%s/tracks.json?' % uploader
268
269         entries = []
270         for i in itertools.count():
271             data = compat_urllib_parse.urlencode({
272                 'offset': i * 50,
273                 'client_id': self._CLIENT_ID,
274             })
275             new_entries = self._download_json(
276                 base_url + data, uploader, 'Downloading track page %s' % (i + 1))
277             entries.extend(self._extract_info_dict(e, quiet=True) for e in new_entries)
278             if len(new_entries) < 50:
279                 break
280
281         return {
282             '_type': 'playlist',
283             'id': compat_str(user['id']),
284             'title': user['username'],
285             'entries': entries,
286         }
287
288
289 class SoundcloudPlaylistIE(SoundcloudIE):
290     _VALID_URL = r'https?://api\.soundcloud\.com/playlists/(?P<id>[0-9]+)'
291     IE_NAME = 'soundcloud:playlist'
292
293      # it's in tests/test_playlists.py
294     _TESTS = []
295
296     def _real_extract(self, url):
297         mobj = re.match(self._VALID_URL, url)
298         playlist_id = mobj.group('id')
299         base_url = '%s//api.soundcloud.com/playlists/%s.json?' % (self.http_scheme(), playlist_id)
300
301         data = compat_urllib_parse.urlencode({
302             'client_id': self._CLIENT_ID,
303         })
304         data = self._download_json(
305             base_url + data, playlist_id, 'Downloading playlist')
306
307         entries = [
308             self._extract_info_dict(t, quiet=True) for t in data['tracks']]
309
310         return {
311             '_type': 'playlist',
312             'id': playlist_id,
313             'title': data.get('title'),
314             'description': data.get('description'),
315             'entries': entries,
316         }