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