]> Raphaƫl G. Git Repositories - youtubedl/blob - youtube_dl/extractor/mixcloud.py
debian/patches/remove-autoupdate-mechanism.patch: Refresh.
[youtubedl] / youtube_dl / extractor / mixcloud.py
1 from __future__ import unicode_literals
2
3 import functools
4 import itertools
5 import re
6
7 from .common import InfoExtractor
8 from ..compat import (
9 compat_b64decode,
10 compat_chr,
11 compat_ord,
12 compat_str,
13 compat_urllib_parse_unquote,
14 compat_urlparse,
15 compat_zip
16 )
17 from ..utils import (
18 clean_html,
19 ExtractorError,
20 int_or_none,
21 OnDemandPagedList,
22 str_to_int,
23 try_get,
24 urljoin,
25 )
26
27
28 class MixcloudIE(InfoExtractor):
29 _VALID_URL = r'https?://(?:(?:www|beta|m)\.)?mixcloud\.com/([^/]+)/(?!stream|uploads|favorites|listens|playlists)([^/]+)'
30 IE_NAME = 'mixcloud'
31
32 _TESTS = [{
33 'url': 'http://www.mixcloud.com/dholbach/cryptkeeper/',
34 'info_dict': {
35 'id': 'dholbach-cryptkeeper',
36 'ext': 'm4a',
37 'title': 'Cryptkeeper',
38 'description': 'After quite a long silence from myself, finally another Drum\'n\'Bass mix with my favourite current dance floor bangers.',
39 'uploader': 'Daniel Holbach',
40 'uploader_id': 'dholbach',
41 'thumbnail': r're:https?://.*\.jpg',
42 'view_count': int,
43 },
44 }, {
45 'url': 'http://www.mixcloud.com/gillespeterson/caribou-7-inch-vinyl-mix-chat/',
46 'info_dict': {
47 'id': 'gillespeterson-caribou-7-inch-vinyl-mix-chat',
48 'ext': 'mp3',
49 'title': 'Caribou 7 inch Vinyl Mix & Chat',
50 'description': 'md5:2b8aec6adce69f9d41724647c65875e8',
51 'uploader': 'Gilles Peterson Worldwide',
52 'uploader_id': 'gillespeterson',
53 'thumbnail': 're:https?://.*',
54 'view_count': int,
55 },
56 }, {
57 'url': 'https://beta.mixcloud.com/RedLightRadio/nosedrip-15-red-light-radio-01-18-2016/',
58 'only_matching': True,
59 }]
60
61 @staticmethod
62 def _decrypt_xor_cipher(key, ciphertext):
63 """Encrypt/Decrypt XOR cipher. Both ways are possible because it's XOR."""
64 return ''.join([
65 compat_chr(compat_ord(ch) ^ compat_ord(k))
66 for ch, k in compat_zip(ciphertext, itertools.cycle(key))])
67
68 def _real_extract(self, url):
69 mobj = re.match(self._VALID_URL, url)
70 uploader = mobj.group(1)
71 cloudcast_name = mobj.group(2)
72 track_id = compat_urllib_parse_unquote('-'.join((uploader, cloudcast_name)))
73
74 webpage = self._download_webpage(url, track_id)
75
76 # Legacy path
77 encrypted_play_info = self._search_regex(
78 r'm-play-info="([^"]+)"', webpage, 'play info', default=None)
79
80 if encrypted_play_info is not None:
81 # Decode
82 encrypted_play_info = compat_b64decode(encrypted_play_info)
83 else:
84 # New path
85 full_info_json = self._parse_json(self._html_search_regex(
86 r'<script id="relay-data" type="text/x-mixcloud">([^<]+)</script>',
87 webpage, 'play info'), 'play info')
88 for item in full_info_json:
89 item_data = try_get(
90 item, lambda x: x['cloudcast']['data']['cloudcastLookup'],
91 dict)
92 if try_get(item_data, lambda x: x['streamInfo']['url']):
93 info_json = item_data
94 break
95 else:
96 raise ExtractorError('Failed to extract matching stream info')
97
98 message = self._html_search_regex(
99 r'(?s)<div[^>]+class="global-message cloudcast-disabled-notice-light"[^>]*>(.+?)<(?:a|/div)',
100 webpage, 'error message', default=None)
101
102 js_url = self._search_regex(
103 r'<script[^>]+\bsrc=["\"](https://(?:www\.)?mixcloud\.com/media/(?:js2/www_js_4|js/www)\.[^>]+\.js)',
104 webpage, 'js url')
105 js = self._download_webpage(js_url, track_id, 'Downloading JS')
106 # Known plaintext attack
107 if encrypted_play_info:
108 kps = ['{"stream_url":']
109 kpa_target = encrypted_play_info
110 else:
111 kps = ['https://', 'http://']
112 kpa_target = compat_b64decode(info_json['streamInfo']['url'])
113 for kp in kps:
114 partial_key = self._decrypt_xor_cipher(kpa_target, kp)
115 for quote in ["'", '"']:
116 key = self._search_regex(
117 r'{0}({1}[^{0}]*){0}'.format(quote, re.escape(partial_key)),
118 js, 'encryption key', default=None)
119 if key is not None:
120 break
121 else:
122 continue
123 break
124 else:
125 raise ExtractorError('Failed to extract encryption key')
126
127 if encrypted_play_info is not None:
128 play_info = self._parse_json(self._decrypt_xor_cipher(key, encrypted_play_info), 'play info')
129 if message and 'stream_url' not in play_info:
130 raise ExtractorError('%s said: %s' % (self.IE_NAME, message), expected=True)
131 song_url = play_info['stream_url']
132 formats = [{
133 'format_id': 'normal',
134 'url': song_url
135 }]
136
137 title = self._html_search_regex(r'm-title="([^"]+)"', webpage, 'title')
138 thumbnail = self._proto_relative_url(self._html_search_regex(
139 r'm-thumbnail-url="([^"]+)"', webpage, 'thumbnail', fatal=False))
140 uploader = self._html_search_regex(
141 r'm-owner-name="([^"]+)"', webpage, 'uploader', fatal=False)
142 uploader_id = self._search_regex(
143 r'\s+"profile": "([^"]+)",', webpage, 'uploader id', fatal=False)
144 description = self._og_search_description(webpage)
145 view_count = str_to_int(self._search_regex(
146 [r'<meta itemprop="interactionCount" content="UserPlays:([0-9]+)"',
147 r'/listeners/?">([0-9,.]+)</a>',
148 r'(?:m|data)-tooltip=["\']([\d,.]+) plays'],
149 webpage, 'play count', default=None))
150
151 else:
152 title = info_json['name']
153 thumbnail = urljoin(
154 'https://thumbnailer.mixcloud.com/unsafe/600x600/',
155 try_get(info_json, lambda x: x['picture']['urlRoot'], compat_str))
156 uploader = try_get(info_json, lambda x: x['owner']['displayName'])
157 uploader_id = try_get(info_json, lambda x: x['owner']['username'])
158 description = try_get(info_json, lambda x: x['description'])
159 view_count = int_or_none(try_get(info_json, lambda x: x['plays']))
160
161 stream_info = info_json['streamInfo']
162 formats = []
163
164 for url_key in ('url', 'hlsUrl', 'dashUrl'):
165 format_url = stream_info.get(url_key)
166 if not format_url:
167 continue
168 decrypted = self._decrypt_xor_cipher(key, compat_b64decode(format_url))
169 if not decrypted:
170 continue
171 if url_key == 'hlsUrl':
172 formats.extend(self._extract_m3u8_formats(
173 decrypted, track_id, 'mp4', entry_protocol='m3u8_native',
174 m3u8_id='hls', fatal=False))
175 elif url_key == 'dashUrl':
176 formats.extend(self._extract_mpd_formats(
177 decrypted, track_id, mpd_id='dash', fatal=False))
178 else:
179 formats.append({
180 'format_id': 'http',
181 'url': decrypted,
182 })
183 self._sort_formats(formats)
184
185 return {
186 'id': track_id,
187 'title': title,
188 'formats': formats,
189 'description': description,
190 'thumbnail': thumbnail,
191 'uploader': uploader,
192 'uploader_id': uploader_id,
193 'view_count': view_count,
194 }
195
196
197 class MixcloudPlaylistBaseIE(InfoExtractor):
198 _PAGE_SIZE = 24
199
200 def _find_urls_in_page(self, page):
201 for url in re.findall(r'm-play-button m-url="(?P<url>[^"]+)"', page):
202 yield self.url_result(
203 compat_urlparse.urljoin('https://www.mixcloud.com', clean_html(url)),
204 MixcloudIE.ie_key())
205
206 def _fetch_tracks_page(self, path, video_id, page_name, current_page, real_page_number=None):
207 real_page_number = real_page_number or current_page + 1
208 return self._download_webpage(
209 'https://www.mixcloud.com/%s/' % path, video_id,
210 note='Download %s (page %d)' % (page_name, current_page + 1),
211 errnote='Unable to download %s' % page_name,
212 query={'page': real_page_number, 'list': 'main', '_ajax': '1'},
213 headers={'X-Requested-With': 'XMLHttpRequest'})
214
215 def _tracks_page_func(self, page, video_id, page_name, current_page):
216 resp = self._fetch_tracks_page(page, video_id, page_name, current_page)
217
218 for item in self._find_urls_in_page(resp):
219 yield item
220
221 def _get_user_description(self, page_content):
222 return self._html_search_regex(
223 r'<div[^>]+class="profile-bio"[^>]*>(.+?)</div>',
224 page_content, 'user description', fatal=False)
225
226
227 class MixcloudUserIE(MixcloudPlaylistBaseIE):
228 _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/(?P<type>uploads|favorites|listens)?/?$'
229 IE_NAME = 'mixcloud:user'
230
231 _TESTS = [{
232 'url': 'http://www.mixcloud.com/dholbach/',
233 'info_dict': {
234 'id': 'dholbach_uploads',
235 'title': 'Daniel Holbach (uploads)',
236 'description': 'md5:def36060ac8747b3aabca54924897e47',
237 },
238 'playlist_mincount': 11,
239 }, {
240 'url': 'http://www.mixcloud.com/dholbach/uploads/',
241 'info_dict': {
242 'id': 'dholbach_uploads',
243 'title': 'Daniel Holbach (uploads)',
244 'description': 'md5:def36060ac8747b3aabca54924897e47',
245 },
246 'playlist_mincount': 11,
247 }, {
248 'url': 'http://www.mixcloud.com/dholbach/favorites/',
249 'info_dict': {
250 'id': 'dholbach_favorites',
251 'title': 'Daniel Holbach (favorites)',
252 'description': 'md5:def36060ac8747b3aabca54924897e47',
253 },
254 'params': {
255 'playlist_items': '1-100',
256 },
257 'playlist_mincount': 100,
258 }, {
259 'url': 'http://www.mixcloud.com/dholbach/listens/',
260 'info_dict': {
261 'id': 'dholbach_listens',
262 'title': 'Daniel Holbach (listens)',
263 'description': 'md5:def36060ac8747b3aabca54924897e47',
264 },
265 'params': {
266 'playlist_items': '1-100',
267 },
268 'playlist_mincount': 100,
269 }]
270
271 def _real_extract(self, url):
272 mobj = re.match(self._VALID_URL, url)
273 user_id = mobj.group('user')
274 list_type = mobj.group('type')
275
276 # if only a profile URL was supplied, default to download all uploads
277 if list_type is None:
278 list_type = 'uploads'
279
280 video_id = '%s_%s' % (user_id, list_type)
281
282 profile = self._download_webpage(
283 'https://www.mixcloud.com/%s/' % user_id, video_id,
284 note='Downloading user profile',
285 errnote='Unable to download user profile')
286
287 username = self._og_search_title(profile)
288 description = self._get_user_description(profile)
289
290 entries = OnDemandPagedList(
291 functools.partial(
292 self._tracks_page_func,
293 '%s/%s' % (user_id, list_type), video_id, 'list of %s' % list_type),
294 self._PAGE_SIZE)
295
296 return self.playlist_result(
297 entries, video_id, '%s (%s)' % (username, list_type), description)
298
299
300 class MixcloudPlaylistIE(MixcloudPlaylistBaseIE):
301 _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/playlists/(?P<playlist>[^/]+)/?$'
302 IE_NAME = 'mixcloud:playlist'
303
304 _TESTS = [{
305 'url': 'https://www.mixcloud.com/RedBullThre3style/playlists/tokyo-finalists-2015/',
306 'info_dict': {
307 'id': 'RedBullThre3style_tokyo-finalists-2015',
308 'title': 'National Champions 2015',
309 'description': 'md5:6ff5fb01ac76a31abc9b3939c16243a3',
310 },
311 'playlist_mincount': 16,
312 }, {
313 'url': 'https://www.mixcloud.com/maxvibes/playlists/jazzcat-on-ness-radio/',
314 'only_matching': True,
315 }]
316
317 def _real_extract(self, url):
318 mobj = re.match(self._VALID_URL, url)
319 user_id = mobj.group('user')
320 playlist_id = mobj.group('playlist')
321 video_id = '%s_%s' % (user_id, playlist_id)
322
323 webpage = self._download_webpage(
324 url, user_id,
325 note='Downloading playlist page',
326 errnote='Unable to download playlist page')
327
328 title = self._html_search_regex(
329 r'<a[^>]+class="parent active"[^>]*><b>\d+</b><span[^>]*>([^<]+)',
330 webpage, 'playlist title',
331 default=None) or self._og_search_title(webpage, fatal=False)
332 description = self._get_user_description(webpage)
333
334 entries = OnDemandPagedList(
335 functools.partial(
336 self._tracks_page_func,
337 '%s/playlists/%s' % (user_id, playlist_id), video_id, 'tracklist'),
338 self._PAGE_SIZE)
339
340 return self.playlist_result(entries, video_id, title, description)
341
342
343 class MixcloudStreamIE(MixcloudPlaylistBaseIE):
344 _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<id>[^/]+)/stream/?$'
345 IE_NAME = 'mixcloud:stream'
346
347 _TEST = {
348 'url': 'https://www.mixcloud.com/FirstEar/stream/',
349 'info_dict': {
350 'id': 'FirstEar',
351 'title': 'First Ear',
352 'description': 'Curators of good music\nfirstearmusic.com',
353 },
354 'playlist_mincount': 192,
355 }
356
357 def _real_extract(self, url):
358 user_id = self._match_id(url)
359
360 webpage = self._download_webpage(url, user_id)
361
362 entries = []
363 prev_page_url = None
364
365 def _handle_page(page):
366 entries.extend(self._find_urls_in_page(page))
367 return self._search_regex(
368 r'm-next-page-url="([^"]+)"', page,
369 'next page URL', default=None)
370
371 next_page_url = _handle_page(webpage)
372
373 for idx in itertools.count(0):
374 if not next_page_url or prev_page_url == next_page_url:
375 break
376
377 prev_page_url = next_page_url
378 current_page = int(self._search_regex(
379 r'\?page=(\d+)', next_page_url, 'next page number'))
380
381 next_page_url = _handle_page(self._fetch_tracks_page(
382 '%s/stream' % user_id, user_id, 'stream', idx,
383 real_page_number=current_page))
384
385 username = self._og_search_title(webpage)
386 description = self._get_user_description(webpage)
387
388 return self.playlist_result(entries, user_id, username, description)