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