[mixcloud] Fix play info decryption (closes #13885)
[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 )
15 from ..utils import (
16     clean_html,
17     ExtractorError,
18     OnDemandPagedList,
19     str_to_int,
20 )
21
22
23 class MixcloudIE(InfoExtractor):
24     _VALID_URL = r'https?://(?:(?:www|beta|m)\.)?mixcloud\.com/([^/]+)/(?!stream|uploads|favorites|listens|playlists)([^/]+)'
25     IE_NAME = 'mixcloud'
26
27     _TESTS = [{
28         'url': 'http://www.mixcloud.com/dholbach/cryptkeeper/',
29         'info_dict': {
30             'id': 'dholbach-cryptkeeper',
31             'ext': 'm4a',
32             'title': 'Cryptkeeper',
33             'description': 'After quite a long silence from myself, finally another Drum\'n\'Bass mix with my favourite current dance floor bangers.',
34             'uploader': 'Daniel Holbach',
35             'uploader_id': 'dholbach',
36             'thumbnail': r're:https?://.*\.jpg',
37             'view_count': int,
38         },
39     }, {
40         'url': 'http://www.mixcloud.com/gillespeterson/caribou-7-inch-vinyl-mix-chat/',
41         'info_dict': {
42             'id': 'gillespeterson-caribou-7-inch-vinyl-mix-chat',
43             'ext': 'mp3',
44             'title': 'Caribou 7 inch Vinyl Mix & Chat',
45             'description': 'md5:2b8aec6adce69f9d41724647c65875e8',
46             'uploader': 'Gilles Peterson Worldwide',
47             'uploader_id': 'gillespeterson',
48             'thumbnail': 're:https?://.*',
49             'view_count': int,
50         },
51     }, {
52         'url': 'https://beta.mixcloud.com/RedLightRadio/nosedrip-15-red-light-radio-01-18-2016/',
53         'only_matching': True,
54     }]
55
56     # See https://www.mixcloud.com/media/js2/www_js_2.9e23256562c080482435196ca3975ab5.js
57     def _decrypt_play_info(self, play_info, video_id):
58         KEYS = (
59             'pleasedontdownloadourmusictheartistswontgetpaid',
60             'window.addEventListener = window.addEventListener || function() {};',
61             '(function() { return new Date().toLocaleDateString(); })()',
62         )
63         play_info = base64.b64decode(play_info.encode('ascii'))
64         for num, key in enumerate(KEYS, start=1):
65             try:
66                 return self._parse_json(
67                     ''.join([
68                         compat_chr(compat_ord(ch) ^ compat_ord(key[idx % len(key)]))
69                         for idx, ch in enumerate(play_info)]),
70                     video_id)
71             except ExtractorError:
72                 if num == len(KEYS):
73                     raise
74
75     def _real_extract(self, url):
76         mobj = re.match(self._VALID_URL, url)
77         uploader = mobj.group(1)
78         cloudcast_name = mobj.group(2)
79         track_id = compat_urllib_parse_unquote('-'.join((uploader, cloudcast_name)))
80
81         webpage = self._download_webpage(url, track_id)
82
83         message = self._html_search_regex(
84             r'(?s)<div[^>]+class="global-message cloudcast-disabled-notice-light"[^>]*>(.+?)<(?:a|/div)',
85             webpage, 'error message', default=None)
86
87         encrypted_play_info = self._search_regex(
88             r'm-play-info="([^"]+)"', webpage, 'play info')
89
90         play_info = self._decrypt_play_info(encrypted_play_info, track_id)
91
92         if message and 'stream_url' not in play_info:
93             raise ExtractorError('%s said: %s' % (self.IE_NAME, message), expected=True)
94
95         song_url = play_info['stream_url']
96
97         title = self._html_search_regex(r'm-title="([^"]+)"', webpage, 'title')
98         thumbnail = self._proto_relative_url(self._html_search_regex(
99             r'm-thumbnail-url="([^"]+)"', webpage, 'thumbnail', fatal=False))
100         uploader = self._html_search_regex(
101             r'm-owner-name="([^"]+)"', webpage, 'uploader', fatal=False)
102         uploader_id = self._search_regex(
103             r'\s+"profile": "([^"]+)",', webpage, 'uploader id', fatal=False)
104         description = self._og_search_description(webpage)
105         view_count = str_to_int(self._search_regex(
106             [r'<meta itemprop="interactionCount" content="UserPlays:([0-9]+)"',
107              r'/listeners/?">([0-9,.]+)</a>',
108              r'(?:m|data)-tooltip=["\']([\d,.]+) plays'],
109             webpage, 'play count', default=None))
110
111         return {
112             'id': track_id,
113             'title': title,
114             'url': song_url,
115             'description': description,
116             'thumbnail': thumbnail,
117             'uploader': uploader,
118             'uploader_id': uploader_id,
119             'view_count': view_count,
120         }
121
122
123 class MixcloudPlaylistBaseIE(InfoExtractor):
124     _PAGE_SIZE = 24
125
126     def _find_urls_in_page(self, page):
127         for url in re.findall(r'm-play-button m-url="(?P<url>[^"]+)"', page):
128             yield self.url_result(
129                 compat_urlparse.urljoin('https://www.mixcloud.com', clean_html(url)),
130                 MixcloudIE.ie_key())
131
132     def _fetch_tracks_page(self, path, video_id, page_name, current_page, real_page_number=None):
133         real_page_number = real_page_number or current_page + 1
134         return self._download_webpage(
135             'https://www.mixcloud.com/%s/' % path, video_id,
136             note='Download %s (page %d)' % (page_name, current_page + 1),
137             errnote='Unable to download %s' % page_name,
138             query={'page': real_page_number, 'list': 'main', '_ajax': '1'},
139             headers={'X-Requested-With': 'XMLHttpRequest'})
140
141     def _tracks_page_func(self, page, video_id, page_name, current_page):
142         resp = self._fetch_tracks_page(page, video_id, page_name, current_page)
143
144         for item in self._find_urls_in_page(resp):
145             yield item
146
147     def _get_user_description(self, page_content):
148         return self._html_search_regex(
149             r'<div[^>]+class="profile-bio"[^>]*>(.+?)</div>',
150             page_content, 'user description', fatal=False)
151
152
153 class MixcloudUserIE(MixcloudPlaylistBaseIE):
154     _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/(?P<type>uploads|favorites|listens)?/?$'
155     IE_NAME = 'mixcloud:user'
156
157     _TESTS = [{
158         'url': 'http://www.mixcloud.com/dholbach/',
159         'info_dict': {
160             'id': 'dholbach_uploads',
161             'title': 'Daniel Holbach (uploads)',
162             'description': 'md5:def36060ac8747b3aabca54924897e47',
163         },
164         'playlist_mincount': 11,
165     }, {
166         'url': 'http://www.mixcloud.com/dholbach/uploads/',
167         'info_dict': {
168             'id': 'dholbach_uploads',
169             'title': 'Daniel Holbach (uploads)',
170             'description': 'md5:def36060ac8747b3aabca54924897e47',
171         },
172         'playlist_mincount': 11,
173     }, {
174         'url': 'http://www.mixcloud.com/dholbach/favorites/',
175         'info_dict': {
176             'id': 'dholbach_favorites',
177             'title': 'Daniel Holbach (favorites)',
178             'description': 'md5:def36060ac8747b3aabca54924897e47',
179         },
180         'params': {
181             'playlist_items': '1-100',
182         },
183         'playlist_mincount': 100,
184     }, {
185         'url': 'http://www.mixcloud.com/dholbach/listens/',
186         'info_dict': {
187             'id': 'dholbach_listens',
188             'title': 'Daniel Holbach (listens)',
189             'description': 'md5:def36060ac8747b3aabca54924897e47',
190         },
191         'params': {
192             'playlist_items': '1-100',
193         },
194         'playlist_mincount': 100,
195     }]
196
197     def _real_extract(self, url):
198         mobj = re.match(self._VALID_URL, url)
199         user_id = mobj.group('user')
200         list_type = mobj.group('type')
201
202         # if only a profile URL was supplied, default to download all uploads
203         if list_type is None:
204             list_type = 'uploads'
205
206         video_id = '%s_%s' % (user_id, list_type)
207
208         profile = self._download_webpage(
209             'https://www.mixcloud.com/%s/' % user_id, video_id,
210             note='Downloading user profile',
211             errnote='Unable to download user profile')
212
213         username = self._og_search_title(profile)
214         description = self._get_user_description(profile)
215
216         entries = OnDemandPagedList(
217             functools.partial(
218                 self._tracks_page_func,
219                 '%s/%s' % (user_id, list_type), video_id, 'list of %s' % list_type),
220             self._PAGE_SIZE, use_cache=True)
221
222         return self.playlist_result(
223             entries, video_id, '%s (%s)' % (username, list_type), description)
224
225
226 class MixcloudPlaylistIE(MixcloudPlaylistBaseIE):
227     _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/playlists/(?P<playlist>[^/]+)/?$'
228     IE_NAME = 'mixcloud:playlist'
229
230     _TESTS = [{
231         'url': 'https://www.mixcloud.com/RedBullThre3style/playlists/tokyo-finalists-2015/',
232         'info_dict': {
233             'id': 'RedBullThre3style_tokyo-finalists-2015',
234             'title': 'National Champions 2015',
235             'description': 'md5:6ff5fb01ac76a31abc9b3939c16243a3',
236         },
237         'playlist_mincount': 16,
238     }, {
239         'url': 'https://www.mixcloud.com/maxvibes/playlists/jazzcat-on-ness-radio/',
240         'only_matching': True,
241     }]
242
243     def _real_extract(self, url):
244         mobj = re.match(self._VALID_URL, url)
245         user_id = mobj.group('user')
246         playlist_id = mobj.group('playlist')
247         video_id = '%s_%s' % (user_id, playlist_id)
248
249         webpage = self._download_webpage(
250             url, user_id,
251             note='Downloading playlist page',
252             errnote='Unable to download playlist page')
253
254         title = self._html_search_regex(
255             r'<a[^>]+class="parent active"[^>]*><b>\d+</b><span[^>]*>([^<]+)',
256             webpage, 'playlist title',
257             default=None) or self._og_search_title(webpage, fatal=False)
258         description = self._get_user_description(webpage)
259
260         entries = OnDemandPagedList(
261             functools.partial(
262                 self._tracks_page_func,
263                 '%s/playlists/%s' % (user_id, playlist_id), video_id, 'tracklist'),
264             self._PAGE_SIZE)
265
266         return self.playlist_result(entries, video_id, title, description)
267
268
269 class MixcloudStreamIE(MixcloudPlaylistBaseIE):
270     _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<id>[^/]+)/stream/?$'
271     IE_NAME = 'mixcloud:stream'
272
273     _TEST = {
274         'url': 'https://www.mixcloud.com/FirstEar/stream/',
275         'info_dict': {
276             'id': 'FirstEar',
277             'title': 'First Ear',
278             'description': 'Curators of good music\nfirstearmusic.com',
279         },
280         'playlist_mincount': 192,
281     }
282
283     def _real_extract(self, url):
284         user_id = self._match_id(url)
285
286         webpage = self._download_webpage(url, user_id)
287
288         entries = []
289         prev_page_url = None
290
291         def _handle_page(page):
292             entries.extend(self._find_urls_in_page(page))
293             return self._search_regex(
294                 r'm-next-page-url="([^"]+)"', page,
295                 'next page URL', default=None)
296
297         next_page_url = _handle_page(webpage)
298
299         for idx in itertools.count(0):
300             if not next_page_url or prev_page_url == next_page_url:
301                 break
302
303             prev_page_url = next_page_url
304             current_page = int(self._search_regex(
305                 r'\?page=(\d+)', next_page_url, 'next page number'))
306
307             next_page_url = _handle_page(self._fetch_tracks_page(
308                 '%s/stream' % user_id, user_id, 'stream', idx,
309                 real_page_number=current_page))
310
311         username = self._og_search_title(webpage)
312         description = self._get_user_description(webpage)
313
314         return self.playlist_result(entries, user_id, username, description)