[mixcloud] Fix extraction by decrypting play info
[youtube-dl] / youtube_dl / extractor / mixcloud.py
1 from __future__ import unicode_literals
2
3 import base64
4 import functools
5 import re
6
7 from .common import InfoExtractor
8 from ..compat import (
9     compat_chr,
10     compat_ord,
11     compat_urllib_parse_unquote,
12     compat_urlparse,
13 )
14 from ..utils import (
15     clean_html,
16     ExtractorError,
17     OnDemandPagedList,
18     parse_count,
19     str_to_int,
20 )
21
22
23 class MixcloudIE(InfoExtractor):
24     _VALID_URL = r'^(?:https?://)?(?:www\.)?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': 're:https?://.*\.jpg',
37             'view_count': int,
38             'like_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             'like_count': int,
52         },
53     }]
54
55     # See https://www.mixcloud.com/media/js2/www_js_2.9e23256562c080482435196ca3975ab5.js
56     @staticmethod
57     def _decrypt_play_info(play_info):
58         KEY = 'pleasedontdownloadourmusictheartistswontgetpaid'
59
60         play_info = base64.b64decode(play_info.encode('ascii'))
61
62         return ''.join([
63             compat_chr(compat_ord(ch) ^ compat_ord(KEY[idx % len(KEY)]))
64             for idx, ch in enumerate(play_info)])
65
66     def _real_extract(self, url):
67         mobj = re.match(self._VALID_URL, url)
68         uploader = mobj.group(1)
69         cloudcast_name = mobj.group(2)
70         track_id = compat_urllib_parse_unquote('-'.join((uploader, cloudcast_name)))
71
72         webpage = self._download_webpage(url, track_id)
73
74         message = self._html_search_regex(
75             r'(?s)<div[^>]+class="global-message cloudcast-disabled-notice-light"[^>]*>(.+?)<(?:a|/div)',
76             webpage, 'error message', default=None)
77
78         encrypted_play_info = self._search_regex(
79             r'm-play-info="([^"]+)"', webpage, 'play info')
80         play_info = self._parse_json(
81             self._decrypt_play_info(encrypted_play_info), track_id)
82
83         if message and 'stream_url' not in play_info:
84             raise ExtractorError('%s said: %s' % (self.IE_NAME, message), expected=True)
85
86         song_url = play_info['stream_url']
87
88         PREFIX = (
89             r'm-play-on-spacebar[^>]+'
90             r'(?:\s+[a-zA-Z0-9-]+(?:="[^"]+")?)*?\s+')
91         title = self._html_search_regex(
92             PREFIX + r'm-title="([^"]+)"', webpage, 'title')
93         thumbnail = self._proto_relative_url(self._html_search_regex(
94             PREFIX + r'm-thumbnail-url="([^"]+)"', webpage, 'thumbnail',
95             fatal=False))
96         uploader = self._html_search_regex(
97             PREFIX + r'm-owner-name="([^"]+)"',
98             webpage, 'uploader', fatal=False)
99         uploader_id = self._search_regex(
100             r'\s+"profile": "([^"]+)",', webpage, 'uploader id', fatal=False)
101         description = self._og_search_description(webpage)
102         like_count = parse_count(self._search_regex(
103             r'\bbutton-favorite[^>]+>.*?<span[^>]+class=["\']toggle-number[^>]+>\s*([^<]+)',
104             webpage, 'like count', fatal=False))
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             webpage, 'play count', fatal=False))
109
110         return {
111             'id': track_id,
112             'title': title,
113             'url': song_url,
114             'description': description,
115             'thumbnail': thumbnail,
116             'uploader': uploader,
117             'uploader_id': uploader_id,
118             'view_count': view_count,
119             'like_count': like_count,
120         }
121
122
123 class MixcloudPlaylistBaseIE(InfoExtractor):
124     _PAGE_SIZE = 24
125
126     def _fetch_tracks_page(self, path, video_id, page_name, current_page):
127         resp = self._download_webpage(
128             'https://www.mixcloud.com/%s/' % path, video_id,
129             note='Download %s (page %d)' % (page_name, current_page + 1),
130             errnote='Unable to download %s' % page_name,
131             query={'page': (current_page + 1), 'list': 'main', '_ajax': '1'},
132             headers={'X-Requested-With': 'XMLHttpRequest'})
133
134         for url in re.findall(r'm-play-button m-url="(?P<url>[^"]+)"', resp):
135             yield self.url_result(
136                 compat_urlparse.urljoin('https://www.mixcloud.com', clean_html(url)),
137                 MixcloudIE.ie_key())
138
139     def _get_user_description(self, page_content):
140         return self._html_search_regex(
141             r'<div[^>]+class="description-text"[^>]*>(.+?)</div>',
142             page_content, 'user description', fatal=False)
143
144
145 class MixcloudUserIE(MixcloudPlaylistBaseIE):
146     _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/(?P<type>uploads|favorites|listens)?/?$'
147     IE_NAME = 'mixcloud:user'
148
149     _TESTS = [{
150         'url': 'http://www.mixcloud.com/dholbach/',
151         'info_dict': {
152             'id': 'dholbach_uploads',
153             'title': 'Daniel Holbach (uploads)',
154             'description': 'md5:327af72d1efeb404a8216c27240d1370',
155         },
156         'playlist_mincount': 11,
157     }, {
158         'url': 'http://www.mixcloud.com/dholbach/uploads/',
159         'info_dict': {
160             'id': 'dholbach_uploads',
161             'title': 'Daniel Holbach (uploads)',
162             'description': 'md5:327af72d1efeb404a8216c27240d1370',
163         },
164         'playlist_mincount': 11,
165     }, {
166         'url': 'http://www.mixcloud.com/dholbach/favorites/',
167         'info_dict': {
168             'id': 'dholbach_favorites',
169             'title': 'Daniel Holbach (favorites)',
170             'description': 'md5:327af72d1efeb404a8216c27240d1370',
171         },
172         'params': {
173             'playlist_items': '1-100',
174         },
175         'playlist_mincount': 100,
176     }, {
177         'url': 'http://www.mixcloud.com/dholbach/listens/',
178         'info_dict': {
179             'id': 'dholbach_listens',
180             'title': 'Daniel Holbach (listens)',
181             'description': 'md5:327af72d1efeb404a8216c27240d1370',
182         },
183         'params': {
184             'playlist_items': '1-100',
185         },
186         'playlist_mincount': 100,
187     }]
188
189     def _real_extract(self, url):
190         mobj = re.match(self._VALID_URL, url)
191         user_id = mobj.group('user')
192         list_type = mobj.group('type')
193
194         # if only a profile URL was supplied, default to download all uploads
195         if list_type is None:
196             list_type = 'uploads'
197
198         video_id = '%s_%s' % (user_id, list_type)
199
200         profile = self._download_webpage(
201             'https://www.mixcloud.com/%s/' % user_id, video_id,
202             note='Downloading user profile',
203             errnote='Unable to download user profile')
204
205         username = self._og_search_title(profile)
206         description = self._get_user_description(profile)
207
208         entries = OnDemandPagedList(
209             functools.partial(
210                 self._fetch_tracks_page,
211                 '%s/%s' % (user_id, list_type), video_id, 'list of %s' % list_type),
212             self._PAGE_SIZE, use_cache=True)
213
214         return self.playlist_result(
215             entries, video_id, '%s (%s)' % (username, list_type), description)
216
217
218 class MixcloudPlaylistIE(MixcloudPlaylistBaseIE):
219     _VALID_URL = r'^(?:https?://)?(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/playlists/(?P<playlist>[^/]+)/?$'
220     IE_NAME = 'mixcloud:playlist'
221
222     _TESTS = [{
223         'url': 'https://www.mixcloud.com/RedBullThre3style/playlists/tokyo-finalists-2015/',
224         'info_dict': {
225             'id': 'RedBullThre3style_tokyo-finalists-2015',
226             'title': 'National Champions 2015',
227             'description': 'md5:6ff5fb01ac76a31abc9b3939c16243a3',
228         },
229         'playlist_mincount': 16,
230     }, {
231         'url': 'https://www.mixcloud.com/maxvibes/playlists/jazzcat-on-ness-radio/',
232         'info_dict': {
233             'id': 'maxvibes_jazzcat-on-ness-radio',
234             'title': 'Jazzcat on Ness Radio',
235             'description': 'md5:7bbbf0d6359a0b8cda85224be0f8f263',
236         },
237         'playlist_mincount': 23
238     }]
239
240     def _real_extract(self, url):
241         mobj = re.match(self._VALID_URL, url)
242         user_id = mobj.group('user')
243         playlist_id = mobj.group('playlist')
244         video_id = '%s_%s' % (user_id, playlist_id)
245
246         profile = self._download_webpage(
247             url, user_id,
248             note='Downloading playlist page',
249             errnote='Unable to download playlist page')
250
251         description = self._get_user_description(profile)
252         playlist_title = self._html_search_regex(
253             r'<span[^>]+class="[^"]*list-playlist-title[^"]*"[^>]*>(.*?)</span>',
254             profile, 'playlist title')
255
256         entries = OnDemandPagedList(
257             functools.partial(
258                 self._fetch_tracks_page,
259                 '%s/playlists/%s' % (user_id, playlist_id), video_id, 'tracklist'),
260             self._PAGE_SIZE)
261
262         return self.playlist_result(entries, video_id, playlist_title, description)