]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/bandcamp.py
[ThumbnailsConvertor] Allow conditional conversion
[yt-dlp.git] / yt_dlp / extractor / bandcamp.py
CommitLineData
0aacd2de 1import random
45aef472 2import re
0aacd2de 3import time
45aef472
PH
4
5from .common import InfoExtractor
8bdd16b4 6from ..compat import compat_str
1cc79574 7from ..utils import (
45aef472 8 ExtractorError,
ba717dca
S
9 float_or_none,
10 int_or_none,
6d923aab 11 KNOWN_EXTENSIONS,
0aacd2de 12 parse_filesize,
4991e16c
S
13 str_or_none,
14 try_get,
0aacd2de 15 update_url_query,
62bafabc 16 unified_strdate,
4991e16c 17 unified_timestamp,
3052a30d 18 url_or_none,
8bdd16b4 19 urljoin,
45aef472
PH
20)
21
22
8bdd16b4 23class BandcampIE(InfoExtractor):
24 _VALID_URL = r'https?://[^/]+\.bandcamp\.com/track/(?P<id>[^/?#&]+)'
cffa6aa1 25 _TESTS = [{
3467b3e2 26 'url': 'http://youtube-dl.bandcamp.com/track/youtube-dl-test-song',
3798eadc
PH
27 'md5': 'c557841d5e50261777a6585648adf439',
28 'info_dict': {
d9bf4652
S
29 'id': '1812978515',
30 'ext': 'mp3',
8bdd16b4 31 'title': "youtube-dl \"'/\\ä↭ - youtube-dl \"'/\\ä↭ - youtube-dl test song \"'/\\ä↭",
d9bf4652 32 'duration': 9.8485,
8bdd16b4 33 'uploader': 'youtube-dl "\'/\\ä↭',
3a379e5e 34 'upload_date': '20121129',
8bdd16b4 35 'timestamp': 1354224127,
6f5ac90c 36 },
3798eadc 37 '_skip': 'There is a limit of 200 free downloads / month for the test song'
d9bf4652 38 }, {
4991e16c 39 # free download
d9bf4652 40 'url': 'http://benprunty.bandcamp.com/track/lanius-battle',
d9bf4652
S
41 'info_dict': {
42 'id': '2650410135',
0f63dc24
TF
43 'ext': 'aiff',
44 'title': 'Ben Prunty - Lanius (Battle)',
4991e16c 45 'thumbnail': r're:^https?://.*\.jpg$',
0f63dc24 46 'uploader': 'Ben Prunty',
4991e16c
S
47 'timestamp': 1396508491,
48 'upload_date': '20140403',
10db0d2f 49 'release_timestamp': 1396483200,
4991e16c
S
50 'release_date': '20140403',
51 'duration': 260.877,
52 'track': 'Lanius (Battle)',
53 'track_number': 1,
54 'track_id': '2650410135',
55 'artist': 'Ben Prunty',
56 'album': 'FTL: Advanced Edition Soundtrack',
d9bf4652 57 },
14b7a24c 58 }, {
4991e16c 59 # no free download, mp3 128
14b7a24c 60 'url': 'https://relapsealumni.bandcamp.com/track/hail-to-fire',
4991e16c 61 'md5': 'fec12ff55e804bb7f7ebeb77a800c8b7',
14b7a24c
PV
62 'info_dict': {
63 'id': '2584466013',
64 'ext': 'mp3',
4991e16c
S
65 'title': 'Mastodon - Hail to Fire',
66 'thumbnail': r're:^https?://.*\.jpg$',
67 'uploader': 'Mastodon',
68 'timestamp': 1322005399,
69 'upload_date': '20111122',
10db0d2f 70 'release_timestamp': 1076112000,
4991e16c
S
71 'release_date': '20040207',
72 'duration': 120.79,
73 'track': 'Hail to Fire',
14b7a24c 74 'track_number': 5,
4991e16c
S
75 'track_id': '2584466013',
76 'artist': 'Mastodon',
77 'album': 'Call of the Mastodon',
14b7a24c 78 },
cffa6aa1 79 }]
45aef472 80
8bdd16b4 81 def _extract_data_attr(self, webpage, video_id, attr='tralbum', fatal=True):
82 return self._parse_json(self._html_search_regex(
83 r'data-%s=(["\'])({.+?})\1' % attr, webpage,
84 attr + ' data', group=2), video_id, fatal=fatal)
85
45aef472 86 def _real_extract(self, url):
8bdd16b4 87 title = self._match_id(url)
45aef472 88 webpage = self._download_webpage(url, title)
8bdd16b4 89 tralbum = self._extract_data_attr(webpage, title)
90 thumbnail = self._og_search_thumbnail(webpage)
91
92 track_id = None
93 track = None
94 track_number = None
95 duration = None
96
97 formats = []
98 track_info = try_get(tralbum, lambda x: x['trackinfo'][0], dict)
99 if track_info:
100 file_ = track_info.get('file')
101 if isinstance(file_, dict):
102 for format_id, format_url in file_.items():
103 if not url_or_none(format_url):
104 continue
105 ext, abr_str = format_id.split('-', 1)
106 formats.append({
107 'format_id': format_id,
108 'url': self._proto_relative_url(format_url, 'http:'),
109 'ext': ext,
110 'vcodec': 'none',
111 'acodec': ext,
112 'abr': int_or_none(abr_str),
113 })
114 track = track_info.get('title')
115 track_id = str_or_none(
116 track_info.get('track_id') or track_info.get('id'))
117 track_number = int_or_none(track_info.get('track_num'))
118 duration = float_or_none(track_info.get('duration'))
119
120 embed = self._extract_data_attr(webpage, title, 'embed', False)
121 current = tralbum.get('current') or {}
122 artist = embed.get('artist') or current.get('artist') or tralbum.get('artist')
123 timestamp = unified_timestamp(
124 current.get('publish_date') or tralbum.get('album_publish_date'))
125
126 download_link = tralbum.get('freeDownloadPage')
4991e16c 127 if download_link:
8bdd16b4 128 track_id = compat_str(tralbum['id'])
4991e16c
S
129
130 download_webpage = self._download_webpage(
131 download_link, track_id, 'Downloading free downloads page')
132
8bdd16b4 133 blob = self._extract_data_attr(download_webpage, track_id, 'blob')
4991e16c
S
134
135 info = try_get(
136 blob, (lambda x: x['digital_items'][0],
137 lambda x: x['download_items'][0]), dict)
138 if info:
139 downloads = info.get('downloads')
140 if isinstance(downloads, dict):
8bdd16b4 141 if not track:
142 track = info.get('title')
4991e16c
S
143 if not artist:
144 artist = info.get('artist')
145 if not thumbnail:
146 thumbnail = info.get('thumb_url')
147
148 download_formats = {}
149 download_formats_list = blob.get('download_formats')
150 if isinstance(download_formats_list, list):
151 for f in blob['download_formats']:
152 name, ext = f.get('name'), f.get('file_extension')
153 if all(isinstance(x, compat_str) for x in (name, ext)):
154 download_formats[name] = ext.strip('.')
155
156 for format_id, f in downloads.items():
157 format_url = f.get('url')
158 if not format_url:
159 continue
160 # Stat URL generation algorithm is reverse engineered from
161 # download_*_bundle_*.js
162 stat_url = update_url_query(
163 format_url.replace('/download/', '/statdownload/'), {
164 '.rand': int(time.time() * 1000 * random.random()),
165 })
166 format_id = f.get('encoding_name') or format_id
167 stat = self._download_json(
168 stat_url, track_id, 'Downloading %s JSON' % format_id,
169 transform_source=lambda s: s[s.index('{'):s.rindex('}') + 1],
170 fatal=False)
171 if not stat:
172 continue
173 retry_url = url_or_none(stat.get('retry_url'))
174 if not retry_url:
175 continue
8bdd16b4 176 formats.append({
4991e16c
S
177 'url': self._proto_relative_url(retry_url, 'http:'),
178 'ext': download_formats.get(format_id),
179 'format_id': format_id,
180 'format_note': f.get('description'),
181 'filesize': parse_filesize(f.get('size_mb')),
182 'vcodec': 'none',
933dbf5a 183 'acodec': format_id.split('-')[0],
4991e16c 184 })
5ecd3c6a 185
8bdd16b4 186 self._sort_formats(formats)
0aacd2de 187
8bdd16b4 188 title = '%s - %s' % (artist, track) if artist else track
189
190 if not duration:
191 duration = float_or_none(self._html_search_meta(
192 'duration', webpage, default=None))
45aef472 193
5ecd3c6a 194 return {
8bdd16b4 195 'id': track_id,
196 'title': title,
4991e16c 197 'thumbnail': thumbnail,
8bdd16b4 198 'uploader': artist,
4991e16c 199 'timestamp': timestamp,
10db0d2f 200 'release_timestamp': unified_timestamp(tralbum.get('album_release_date')),
8bdd16b4 201 'duration': duration,
202 'track': track,
203 'track_number': track_number,
204 'track_id': track_id,
205 'artist': artist,
206 'album': embed.get('album_title'),
207 'formats': formats,
5ecd3c6a 208 }
09804265
JMF
209
210
8bdd16b4 211class BandcampAlbumIE(BandcampIE):
3798eadc 212 IE_NAME = 'Bandcamp:album'
85a0ad01 213 _VALID_URL = r'https?://(?:(?P<subdomain>[^.]+)\.)?bandcamp\.com/album/(?P<id>[^/?#&]+)'
09804265 214
22a6f150 215 _TESTS = [{
3798eadc
PH
216 'url': 'http://blazo.bandcamp.com/album/jazz-format-mixtape-vol-1',
217 'playlist': [
d35dc6d3 218 {
3798eadc
PH
219 'md5': '39bc1eded3476e927c724321ddf116cf',
220 'info_dict': {
13ba3a64
PH
221 'id': '1353101989',
222 'ext': 'mp3',
8bdd16b4 223 'title': 'Blazo - Intro',
224 'timestamp': 1311756226,
225 'upload_date': '20110727',
226 'uploader': 'Blazo',
d35dc6d3
JMF
227 }
228 },
229 {
3798eadc
PH
230 'md5': '1a2c32e2691474643e912cc6cd4bffaa',
231 'info_dict': {
13ba3a64
PH
232 'id': '38097443',
233 'ext': 'mp3',
8bdd16b4 234 'title': 'Blazo - Kero One - Keep It Alive (Blazo remix)',
235 'timestamp': 1311757238,
236 'upload_date': '20110727',
237 'uploader': 'Blazo',
d35dc6d3
JMF
238 }
239 },
240 ],
13ba3a64
PH
241 'info_dict': {
242 'title': 'Jazz Format Mixtape vol.1',
72c1f8de
PH
243 'id': 'jazz-format-mixtape-vol-1',
244 'uploader_id': 'blazo',
13ba3a64 245 },
3798eadc
PH
246 'params': {
247 'playlistend': 2
d35dc6d3 248 },
72c1f8de 249 'skip': 'Bandcamp imposes download limits.'
22a6f150
PH
250 }, {
251 'url': 'http://nightbringer.bandcamp.com/album/hierophany-of-the-open-grave',
252 'info_dict': {
253 'title': 'Hierophany of the Open Grave',
72c1f8de
PH
254 'uploader_id': 'nightbringer',
255 'id': 'hierophany-of-the-open-grave',
22a6f150
PH
256 },
257 'playlist_mincount': 9,
64fc49ab
S
258 }, {
259 # with escaped quote in title
260 'url': 'https://jstrecords.bandcamp.com/album/entropy-ep',
261 'info_dict': {
262 'title': '"Entropy" EP',
263 'uploader_id': 'jstrecords',
264 'id': 'entropy-ep',
8bdd16b4 265 'description': 'md5:0ff22959c943622972596062f2f366a5',
64fc49ab
S
266 },
267 'playlist_mincount': 3,
019f4c03
YCH
268 }, {
269 # not all tracks have songs
270 'url': 'https://insulters.bandcamp.com/album/we-are-the-plague',
271 'info_dict': {
272 'id': 'we-are-the-plague',
273 'title': 'WE ARE THE PLAGUE',
274 'uploader_id': 'insulters',
8bdd16b4 275 'description': 'md5:b3cf845ee41b2b1141dc7bde9237255f',
019f4c03
YCH
276 },
277 'playlist_count': 2,
22a6f150 278 }]
d35dc6d3 279
62bafabc
AV
280 @classmethod
281 def suitable(cls, url):
6d923aab
S
282 return (False
283 if BandcampWeeklyIE.suitable(url) or BandcampIE.suitable(url)
284 else super(BandcampAlbumIE, cls).suitable(url))
62bafabc 285
09804265 286 def _real_extract(self, url):
5ad28e7f 287 uploader_id, album_id = self._match_valid_url(url).groups()
72c1f8de
PH
288 playlist_id = album_id or uploader_id
289 webpage = self._download_webpage(url, playlist_id)
8bdd16b4 290 tralbum = self._extract_data_attr(webpage, playlist_id)
291 track_info = tralbum.get('trackinfo')
292 if not track_info:
293 raise ExtractorError('The page doesn\'t contain any tracks')
019f4c03 294 # Only tracks with duration info have songs
09804265 295 entries = [
8239c679 296 self.url_result(
8bdd16b4 297 urljoin(url, t['title_link']), BandcampIE.ie_key(),
298 str_or_none(t.get('track_id') or t.get('id')), t.get('title'))
299 for t in track_info
300 if t.get('duration')]
301
302 current = tralbum.get('current') or {}
3a379e5e 303
09804265
JMF
304 return {
305 '_type': 'playlist',
72c1f8de 306 'uploader_id': uploader_id,
b48f147d 307 'id': playlist_id,
8bdd16b4 308 'title': current.get('title'),
309 'description': current.get('about'),
310 'entries': entries,
09804265 311 }
62bafabc
AV
312
313
8bdd16b4 314class BandcampWeeklyIE(BandcampIE):
6d923aab
S
315 IE_NAME = 'Bandcamp:weekly'
316 _VALID_URL = r'https?://(?:www\.)?bandcamp\.com/?\?(?:.*?&)?show=(?P<id>\d+)'
62bafabc
AV
317 _TESTS = [{
318 'url': 'https://bandcamp.com/?show=224',
319 'md5': 'b00df799c733cf7e0c567ed187dea0fd',
320 'info_dict': {
321 'id': '224',
322 'ext': 'opus',
6d923aab
S
323 'title': 'BC Weekly April 4th 2017 - Magic Moments',
324 'description': 'md5:5d48150916e8e02d030623a48512c874',
325 'duration': 5829.77,
326 'release_date': '20170404',
327 'series': 'Bandcamp Weekly',
328 'episode': 'Magic Moments',
6d923aab 329 'episode_id': '224',
8bdd16b4 330 },
331 'params': {
332 'format': 'opus-lo',
333 },
62bafabc
AV
334 }, {
335 'url': 'https://bandcamp.com/?blah/blah@&show=228',
336 'only_matching': True
337 }]
338
339 def _real_extract(self, url):
8bdd16b4 340 show_id = self._match_id(url)
341 webpage = self._download_webpage(url, show_id)
62bafabc 342
8bdd16b4 343 blob = self._extract_data_attr(webpage, show_id, 'blob')
62bafabc 344
8bdd16b4 345 show = blob['bcw_data'][show_id]
62bafabc 346
6d923aab
S
347 formats = []
348 for format_id, format_url in show['audio_stream'].items():
3052a30d 349 if not url_or_none(format_url):
6d923aab
S
350 continue
351 for known_ext in KNOWN_EXTENSIONS:
352 if known_ext in format_id:
353 ext = known_ext
354 break
355 else:
356 ext = None
357 formats.append({
358 'format_id': format_id,
359 'url': format_url,
360 'ext': ext,
361 'vcodec': 'none',
362 })
363 self._sort_formats(formats)
62bafabc 364
6d923aab
S
365 title = show.get('audio_title') or 'Bandcamp Weekly'
366 subtitle = show.get('subtitle')
367 if subtitle:
368 title += ' - %s' % subtitle
62bafabc 369
62bafabc 370 return {
8bdd16b4 371 'id': show_id,
6d923aab
S
372 'title': title,
373 'description': show.get('desc') or show.get('short_desc'),
62bafabc 374 'duration': float_or_none(show.get('audio_duration')),
62bafabc
AV
375 'is_live': False,
376 'release_date': unified_strdate(show.get('published_date')),
377 'series': 'Bandcamp Weekly',
6d923aab 378 'episode': show.get('subtitle'),
8bdd16b4 379 'episode_id': show_id,
62bafabc
AV
380 'formats': formats
381 }
bc874548
A
382
383
85a0ad01 384class BandcampUserIE(InfoExtractor):
385 IE_NAME = 'Bandcamp:user'
386 _VALID_URL = r'https?://(?!www\.)(?P<id>[^.]+)\.bandcamp\.com(?:/music)?/?(?:[#?]|$)'
387
bc874548 388 _TESTS = [{
85a0ad01 389 # Type 1 Bandcamp user page.
390 'url': 'https://adrianvonziegler.bandcamp.com',
391 'info_dict': {
392 'id': 'adrianvonziegler',
393 'title': 'Discography of adrianvonziegler',
394 },
395 'playlist_mincount': 23,
396 }, {
397 # Bandcamp user page with only one album
398 'url': 'http://dotscale.bandcamp.com',
399 'info_dict': {
400 'id': 'dotscale',
401 'title': 'Discography of dotscale'
402 },
403 'playlist_count': 1,
404 }, {
405 # Type 2 Bandcamp user page.
406 'url': 'https://nightcallofficial.bandcamp.com',
407 'info_dict': {
408 'id': 'nightcallofficial',
409 'title': 'Discography of nightcallofficial',
410 },
411 'playlist_count': 4,
412 }, {
bc874548
A
413 'url': 'https://steviasphere.bandcamp.com/music',
414 'playlist_mincount': 47,
415 'info_dict': {
416 'id': 'steviasphere',
85a0ad01 417 'title': 'Discography of steviasphere',
bc874548
A
418 },
419 }, {
420 'url': 'https://coldworldofficial.bandcamp.com/music',
421 'playlist_mincount': 10,
422 'info_dict': {
423 'id': 'coldworldofficial',
85a0ad01 424 'title': 'Discography of coldworldofficial',
bc874548
A
425 },
426 }, {
427 'url': 'https://nuclearwarnowproductions.bandcamp.com/music',
428 'playlist_mincount': 399,
429 'info_dict': {
430 'id': 'nuclearwarnowproductions',
85a0ad01 431 'title': 'Discography of nuclearwarnowproductions',
bc874548 432 },
85a0ad01 433 }]
bc874548
A
434
435 def _real_extract(self, url):
85a0ad01 436 uploader = self._match_id(url)
437 webpage = self._download_webpage(url, uploader)
438
96b49af0 439 discography_data = (re.findall(r'<li data-item-id=["\'][^>]+>\s*<a href=["\'](?![^"\'/]*?/merch)([^"\']+)', webpage)
85a0ad01 440 or re.findall(r'<div[^>]+trackTitle["\'][^"\']+["\']([^"\']+)', webpage))
441
442 return self.playlist_from_matches(
443 discography_data, uploader, f'Discography of {uploader}', getter=lambda x: urljoin(url, x))