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