]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/mixcloud.py
[cleanup] Remove unused code paths (#2173)
[yt-dlp.git] / yt_dlp / extractor / mixcloud.py
CommitLineData
d0390a0c
PH
1from __future__ import unicode_literals
2
e6da9240 3import itertools
80cbb6dd
PH
4
5from .common import InfoExtractor
c96eca42 6from ..compat import (
5d7d805c 7 compat_b64decode,
dd91dfcd
YCH
8 compat_chr,
9 compat_ord,
095774e5 10 compat_str,
c96eca42 11 compat_urllib_parse_unquote,
2384f5a6 12 compat_zip
c96eca42 13)
1cc79574 14from ..utils import (
9040e2d6 15 ExtractorError,
095774e5 16 int_or_none,
5d92b407
RA
17 parse_iso8601,
18 strip_or_none,
095774e5 19 try_get,
095774e5 20)
80cbb6dd
PH
21
22
5d92b407
RA
23class MixcloudBaseIE(InfoExtractor):
24 def _call_api(self, object_type, object_fields, display_id, username, slug=None):
25 lookup_key = object_type + 'Lookup'
26 return self._download_json(
27 'https://www.mixcloud.com/graphql', display_id, query={
28 'query': '''{
29 %s(lookup: {username: "%s"%s}) {
30 %s
31 }
32}''' % (lookup_key, username, ', slug: "%s"' % slug if slug else '', object_fields)
33 })['data'][lookup_key]
34
35
36class MixcloudIE(MixcloudBaseIE):
655cb545 37 _VALID_URL = r'https?://(?:(?:www|beta|m)\.)?mixcloud\.com/([^/]+)/(?!stream|uploads|favorites|listens|playlists)([^/]+)'
d0390a0c 38 IE_NAME = 'mixcloud'
80cbb6dd 39
58ba6c01 40 _TESTS = [{
d0390a0c 41 'url': 'http://www.mixcloud.com/dholbach/cryptkeeper/',
d0390a0c 42 'info_dict': {
5d92b407 43 'id': 'dholbach_cryptkeeper',
f896e1cc 44 'ext': 'm4a',
d0390a0c
PH
45 'title': 'Cryptkeeper',
46 'description': 'After quite a long silence from myself, finally another Drum\'n\'Bass mix with my favourite current dance floor bangers.',
47 'uploader': 'Daniel Holbach',
48 'uploader_id': 'dholbach',
ec85ded8 49 'thumbnail': r're:https?://.*\.jpg',
57c7411f 50 'view_count': int,
5d92b407
RA
51 'timestamp': 1321359578,
52 'upload_date': '20111115',
19e1d359 53 },
58ba6c01
S
54 }, {
55 'url': 'http://www.mixcloud.com/gillespeterson/caribou-7-inch-vinyl-mix-chat/',
56 'info_dict': {
5d92b407 57 'id': 'gillespeterson_caribou-7-inch-vinyl-mix-chat',
7a757b71
JMF
58 'ext': 'mp3',
59 'title': 'Caribou 7 inch Vinyl Mix & Chat',
58ba6c01 60 'description': 'md5:2b8aec6adce69f9d41724647c65875e8',
7a757b71 61 'uploader': 'Gilles Peterson Worldwide',
58ba6c01 62 'uploader_id': 'gillespeterson',
dd91dfcd 63 'thumbnail': 're:https?://.*',
58ba6c01 64 'view_count': int,
5d92b407
RA
65 'timestamp': 1422987057,
66 'upload_date': '20150203',
58ba6c01 67 },
655cb545
S
68 }, {
69 'url': 'https://beta.mixcloud.com/RedLightRadio/nosedrip-15-red-light-radio-01-18-2016/',
70 'only_matching': True,
58ba6c01 71 }]
5d92b407 72 _DECRYPTION_KEY = 'IFYOUWANTTHEARTISTSTOGETPAIDDONOTDOWNLOADFROMMIXCLOUD'
80cbb6dd 73
2384f5a6
TI
74 @staticmethod
75 def _decrypt_xor_cipher(key, ciphertext):
76 """Encrypt/Decrypt XOR cipher. Both ways are possible because it's XOR."""
77 return ''.join([
78 compat_chr(compat_ord(ch) ^ compat_ord(k))
79 for ch, k in compat_zip(ciphertext, itertools.cycle(key))])
80
80cbb6dd 81 def _real_extract(self, url):
5ad28e7f 82 username, slug = self._match_valid_url(url).groups()
5d92b407
RA
83 username, slug = compat_urllib_parse_unquote(username), compat_urllib_parse_unquote(slug)
84 track_id = '%s_%s' % (username, slug)
85
86 cloudcast = self._call_api('cloudcast', '''audioLength
87 comments(first: 100) {
88 edges {
89 node {
90 comment
91 created
92 user {
93 displayName
94 username
95 }
96 }
97 }
98 totalCount
99 }
100 description
101 favorites {
102 totalCount
103 }
104 featuringArtistList
105 isExclusive
106 name
107 owner {
108 displayName
109 url
110 username
111 }
112 picture(width: 1024, height: 1024) {
113 url
114 }
115 plays
116 publishDate
117 reposts {
118 totalCount
119 }
120 streamInfo {
121 dashUrl
122 hlsUrl
123 url
124 }
125 tags {
126 tag {
127 name
128 }
9040e2d6
L
129 }
130 restrictedReason
131 id''', track_id, username, slug)
132
133 if not cloudcast:
134 raise ExtractorError('Track not found', expected=True)
135
136 reason = cloudcast.get('restrictedReason')
137 if reason == 'tracklist':
138 raise ExtractorError('Track unavailable in your country due to licensing restrictions', expected=True)
139 elif reason == 'repeat_play':
140 raise ExtractorError('You have reached your play limit for this track', expected=True)
141 elif reason:
142 raise ExtractorError('Track is restricted', expected=True)
dd2535c3 143
5d92b407 144 title = cloudcast['name']
19e1d359 145
5d92b407
RA
146 stream_info = cloudcast['streamInfo']
147 formats = []
2384f5a6 148
5d92b407
RA
149 for url_key in ('url', 'hlsUrl', 'dashUrl'):
150 format_url = stream_info.get(url_key)
151 if not format_url:
152 continue
153 decrypted = self._decrypt_xor_cipher(
154 self._DECRYPTION_KEY, compat_b64decode(format_url))
155 if url_key == 'hlsUrl':
156 formats.extend(self._extract_m3u8_formats(
157 decrypted, track_id, 'mp4', entry_protocol='m3u8_native',
158 m3u8_id='hls', fatal=False))
159 elif url_key == 'dashUrl':
160 formats.extend(self._extract_mpd_formats(
161 decrypted, track_id, mpd_id='dash', fatal=False))
2384f5a6 162 else:
5d92b407
RA
163 formats.append({
164 'format_id': 'http',
165 'url': decrypted,
166 'downloader_options': {
167 # Mixcloud starts throttling at >~5M
168 'http_chunk_size': 5242880,
169 },
170 })
171
172 if not formats and cloudcast.get('isExclusive'):
b7da73eb 173 self.raise_login_required(metadata_available=True)
5d92b407
RA
174
175 self._sort_formats(formats)
176
177 comments = []
178 for edge in (try_get(cloudcast, lambda x: x['comments']['edges']) or []):
179 node = edge.get('node') or {}
180 text = strip_or_none(node.get('comment'))
181 if not text:
2384f5a6 182 continue
5d92b407
RA
183 user = node.get('user') or {}
184 comments.append({
185 'author': user.get('displayName'),
186 'author_id': user.get('username'),
187 'text': text,
188 'timestamp': parse_iso8601(node.get('created')),
189 })
2384f5a6 190
5d92b407
RA
191 tags = []
192 for t in cloudcast.get('tags'):
193 tag = try_get(t, lambda x: x['tag']['name'], compat_str)
194 if not tag:
195 tags.append(tag)
196
197 get_count = lambda x: int_or_none(try_get(cloudcast, lambda y: y[x]['totalCount']))
198
199 owner = cloudcast.get('owner') or {}
19e1d359
JMF
200
201 return {
202 'id': track_id,
57c7411f 203 'title': title,
2384f5a6 204 'formats': formats,
5d92b407
RA
205 'description': cloudcast.get('description'),
206 'thumbnail': try_get(cloudcast, lambda x: x['picture']['url'], compat_str),
207 'uploader': owner.get('displayName'),
208 'timestamp': parse_iso8601(cloudcast.get('publishDate')),
209 'uploader_id': owner.get('username'),
210 'uploader_url': owner.get('url'),
211 'duration': int_or_none(cloudcast.get('audioLength')),
212 'view_count': int_or_none(cloudcast.get('plays')),
213 'like_count': get_count('favorites'),
214 'repost_count': get_count('reposts'),
215 'comment_count': get_count('comments'),
216 'comments': comments,
217 'tags': tags,
218 'artist': ', '.join(cloudcast.get('featuringArtistList') or []) or None,
19e1d359 219 }
c96eca42
PH
220
221
5d92b407
RA
222class MixcloudPlaylistBaseIE(MixcloudBaseIE):
223 def _get_cloudcast(self, node):
224 return node
c96eca42 225
5d92b407
RA
226 def _get_playlist_title(self, title, slug):
227 return title
228
229 def _real_extract(self, url):
5ad28e7f 230 username, slug = self._match_valid_url(url).groups()
5d92b407
RA
231 username = compat_urllib_parse_unquote(username)
232 if not slug:
233 slug = 'uploads'
234 else:
235 slug = compat_urllib_parse_unquote(slug)
236 playlist_id = '%s_%s' % (username, slug)
e6da9240 237
5d92b407
RA
238 is_playlist_type = self._ROOT_TYPE == 'playlist'
239 playlist_type = 'items' if is_playlist_type else slug
240 list_filter = ''
9c250931 241
5d92b407
RA
242 has_next_page = True
243 entries = []
244 while has_next_page:
245 playlist = self._call_api(
246 self._ROOT_TYPE, '''%s
247 %s
248 %s(first: 100%s) {
249 edges {
250 node {
251 %s
252 }
253 }
254 pageInfo {
255 endCursor
256 hasNextPage
257 }
258 }''' % (self._TITLE_KEY, self._DESCRIPTION_KEY, playlist_type, list_filter, self._NODE_TEMPLATE),
259 playlist_id, username, slug if is_playlist_type else None)
260
261 items = playlist.get(playlist_type) or {}
262 for edge in items.get('edges', []):
263 cloudcast = self._get_cloudcast(edge.get('node') or {})
264 cloudcast_url = cloudcast.get('url')
265 if not cloudcast_url:
266 continue
30a074c2 267 slug = try_get(cloudcast, lambda x: x['slug'], compat_str)
268 owner_username = try_get(cloudcast, lambda x: x['owner']['username'], compat_str)
269 video_id = '%s_%s' % (owner_username, slug) if slug and owner_username else None
5d92b407 270 entries.append(self.url_result(
30a074c2 271 cloudcast_url, MixcloudIE.ie_key(), video_id))
e6da9240 272
5d92b407
RA
273 page_info = items['pageInfo']
274 has_next_page = page_info['hasNextPage']
275 list_filter = ', after: "%s"' % page_info['endCursor']
9c250931 276
5d92b407
RA
277 return self.playlist_result(
278 entries, playlist_id,
279 self._get_playlist_title(playlist[self._TITLE_KEY], slug),
280 playlist.get(self._DESCRIPTION_KEY))
9c250931
YCH
281
282
283class MixcloudUserIE(MixcloudPlaylistBaseIE):
5d92b407 284 _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<id>[^/]+)/(?P<type>uploads|favorites|listens|stream)?/?$'
c96eca42
PH
285 IE_NAME = 'mixcloud:user'
286
287 _TESTS = [{
288 'url': 'http://www.mixcloud.com/dholbach/',
289 'info_dict': {
9c250931 290 'id': 'dholbach_uploads',
c96eca42 291 'title': 'Daniel Holbach (uploads)',
5d92b407 292 'description': 'md5:b60d776f0bab534c5dabe0a34e47a789',
c96eca42 293 },
5d92b407 294 'playlist_mincount': 36,
c96eca42
PH
295 }, {
296 'url': 'http://www.mixcloud.com/dholbach/uploads/',
297 'info_dict': {
9c250931 298 'id': 'dholbach_uploads',
c96eca42 299 'title': 'Daniel Holbach (uploads)',
5d92b407 300 'description': 'md5:b60d776f0bab534c5dabe0a34e47a789',
c96eca42 301 },
5d92b407 302 'playlist_mincount': 36,
c96eca42
PH
303 }, {
304 'url': 'http://www.mixcloud.com/dholbach/favorites/',
305 'info_dict': {
9c250931 306 'id': 'dholbach_favorites',
c96eca42 307 'title': 'Daniel Holbach (favorites)',
5d92b407 308 'description': 'md5:b60d776f0bab534c5dabe0a34e47a789',
9c250931 309 },
5d92b407
RA
310 # 'params': {
311 # 'playlist_items': '1-100',
312 # },
313 'playlist_mincount': 396,
c96eca42
PH
314 }, {
315 'url': 'http://www.mixcloud.com/dholbach/listens/',
316 'info_dict': {
9c250931 317 'id': 'dholbach_listens',
c96eca42 318 'title': 'Daniel Holbach (listens)',
5d92b407 319 'description': 'md5:b60d776f0bab534c5dabe0a34e47a789',
c96eca42 320 },
5d92b407
RA
321 # 'params': {
322 # 'playlist_items': '1-100',
323 # },
324 'playlist_mincount': 1623,
325 'skip': 'Large list',
326 }, {
327 'url': 'https://www.mixcloud.com/FirstEar/stream/',
328 'info_dict': {
329 'id': 'FirstEar_stream',
330 'title': 'First Ear (stream)',
331 'description': 'Curators of good music\r\n\r\nfirstearmusic.com',
9c250931 332 },
5d92b407 333 'playlist_mincount': 271,
c96eca42
PH
334 }]
335
5d92b407
RA
336 _TITLE_KEY = 'displayName'
337 _DESCRIPTION_KEY = 'biog'
338 _ROOT_TYPE = 'user'
339 _NODE_TEMPLATE = '''slug
30a074c2 340 url
341 owner { username }'''
c96eca42 342
5d92b407
RA
343 def _get_playlist_title(self, title, slug):
344 return '%s (%s)' % (title, slug)
c96eca42 345
c96eca42 346
9c250931 347class MixcloudPlaylistIE(MixcloudPlaylistBaseIE):
29c67266 348 _VALID_URL = r'https?://(?:www\.)?mixcloud\.com/(?P<user>[^/]+)/playlists/(?P<playlist>[^/]+)/?$'
c96eca42
PH
349 IE_NAME = 'mixcloud:playlist'
350
351 _TESTS = [{
c96eca42 352 'url': 'https://www.mixcloud.com/maxvibes/playlists/jazzcat-on-ness-radio/',
e6da9240 353 'info_dict': {
5d92b407
RA
354 'id': 'maxvibes_jazzcat-on-ness-radio',
355 'title': 'Ness Radio sessions',
e6da9240 356 },
5d92b407
RA
357 'playlist_mincount': 59,
358 }]
359 _TITLE_KEY = 'name'
360 _DESCRIPTION_KEY = 'description'
361 _ROOT_TYPE = 'playlist'
362 _NODE_TEMPLATE = '''cloudcast {
363 slug
364 url
30a074c2 365 owner { username }
5d92b407
RA
366 }'''
367
368 def _get_cloudcast(self, node):
369 return node.get('cloudcast') or {}