]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/bandcamp.py
6f806d84ee2432cbfc228f1223465573c5995681
[yt-dlp.git] / yt_dlp / extractor / bandcamp.py
1 import random
2 import re
3 import time
4
5 from .common import InfoExtractor
6 from ..compat import compat_str
7 from ..utils import (
8 ExtractorError,
9 float_or_none,
10 int_or_none,
11 KNOWN_EXTENSIONS,
12 parse_filesize,
13 str_or_none,
14 try_get,
15 update_url_query,
16 unified_strdate,
17 unified_timestamp,
18 url_or_none,
19 urljoin,
20 )
21
22
23 class BandcampIE(InfoExtractor):
24 _VALID_URL = r'https?://[^/]+\.bandcamp\.com/track/(?P<id>[^/?#&]+)'
25 _TESTS = [{
26 'url': 'http://youtube-dl.bandcamp.com/track/youtube-dl-test-song',
27 'md5': 'c557841d5e50261777a6585648adf439',
28 'info_dict': {
29 'id': '1812978515',
30 'ext': 'mp3',
31 'title': "youtube-dl \"'/\\ä↭ - youtube-dl \"'/\\ä↭ - youtube-dl test song \"'/\\ä↭",
32 'duration': 9.8485,
33 'uploader': 'youtube-dl "\'/\\ä↭',
34 'upload_date': '20121129',
35 'timestamp': 1354224127,
36 },
37 '_skip': 'There is a limit of 200 free downloads / month for the test song'
38 }, {
39 # free download
40 'url': 'http://benprunty.bandcamp.com/track/lanius-battle',
41 'info_dict': {
42 'id': '2650410135',
43 'ext': 'aiff',
44 'title': 'Ben Prunty - Lanius (Battle)',
45 'thumbnail': r're:^https?://.*\.jpg$',
46 'uploader': 'Ben Prunty',
47 'timestamp': 1396508491,
48 'upload_date': '20140403',
49 'release_timestamp': 1396483200,
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',
57 },
58 }, {
59 # no free download, mp3 128
60 'url': 'https://relapsealumni.bandcamp.com/track/hail-to-fire',
61 'md5': 'fec12ff55e804bb7f7ebeb77a800c8b7',
62 'info_dict': {
63 'id': '2584466013',
64 'ext': 'mp3',
65 'title': 'Mastodon - Hail to Fire',
66 'thumbnail': r're:^https?://.*\.jpg$',
67 'uploader': 'Mastodon',
68 'timestamp': 1322005399,
69 'upload_date': '20111122',
70 'release_timestamp': 1076112000,
71 'release_date': '20040207',
72 'duration': 120.79,
73 'track': 'Hail to Fire',
74 'track_number': 5,
75 'track_id': '2584466013',
76 'artist': 'Mastodon',
77 'album': 'Call of the Mastodon',
78 },
79 }]
80
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
86 def _real_extract(self, url):
87 title = self._match_id(url)
88 webpage = self._download_webpage(url, title)
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')
127 if download_link:
128 track_id = compat_str(tralbum['id'])
129
130 download_webpage = self._download_webpage(
131 download_link, track_id, 'Downloading free downloads page')
132
133 blob = self._extract_data_attr(download_webpage, track_id, 'blob')
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):
141 if not track:
142 track = info.get('title')
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
176 formats.append({
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',
183 'acodec': format_id.split('-')[0],
184 })
185
186 self._sort_formats(formats)
187
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))
193
194 return {
195 'id': track_id,
196 'title': title,
197 'thumbnail': thumbnail,
198 'uploader': artist,
199 'timestamp': timestamp,
200 'release_timestamp': unified_timestamp(tralbum.get('album_release_date')),
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,
208 }
209
210
211 class BandcampAlbumIE(BandcampIE):
212 IE_NAME = 'Bandcamp:album'
213 _VALID_URL = r'https?://(?:(?P<subdomain>[^.]+)\.)?bandcamp\.com/album/(?P<id>[^/?#&]+)'
214
215 _TESTS = [{
216 'url': 'http://blazo.bandcamp.com/album/jazz-format-mixtape-vol-1',
217 'playlist': [
218 {
219 'md5': '39bc1eded3476e927c724321ddf116cf',
220 'info_dict': {
221 'id': '1353101989',
222 'ext': 'mp3',
223 'title': 'Blazo - Intro',
224 'timestamp': 1311756226,
225 'upload_date': '20110727',
226 'uploader': 'Blazo',
227 }
228 },
229 {
230 'md5': '1a2c32e2691474643e912cc6cd4bffaa',
231 'info_dict': {
232 'id': '38097443',
233 'ext': 'mp3',
234 'title': 'Blazo - Kero One - Keep It Alive (Blazo remix)',
235 'timestamp': 1311757238,
236 'upload_date': '20110727',
237 'uploader': 'Blazo',
238 }
239 },
240 ],
241 'info_dict': {
242 'title': 'Jazz Format Mixtape vol.1',
243 'id': 'jazz-format-mixtape-vol-1',
244 'uploader_id': 'blazo',
245 },
246 'params': {
247 'playlistend': 2
248 },
249 'skip': 'Bandcamp imposes download limits.'
250 }, {
251 'url': 'http://nightbringer.bandcamp.com/album/hierophany-of-the-open-grave',
252 'info_dict': {
253 'title': 'Hierophany of the Open Grave',
254 'uploader_id': 'nightbringer',
255 'id': 'hierophany-of-the-open-grave',
256 },
257 'playlist_mincount': 9,
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',
265 'description': 'md5:0ff22959c943622972596062f2f366a5',
266 },
267 'playlist_mincount': 3,
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',
275 'description': 'md5:b3cf845ee41b2b1141dc7bde9237255f',
276 },
277 'playlist_count': 2,
278 }]
279
280 @classmethod
281 def suitable(cls, url):
282 return (False
283 if BandcampWeeklyIE.suitable(url) or BandcampIE.suitable(url)
284 else super(BandcampAlbumIE, cls).suitable(url))
285
286 def _real_extract(self, url):
287 uploader_id, album_id = self._match_valid_url(url).groups()
288 playlist_id = album_id or uploader_id
289 webpage = self._download_webpage(url, playlist_id)
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')
294 # Only tracks with duration info have songs
295 entries = [
296 self.url_result(
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 {}
303
304 return {
305 '_type': 'playlist',
306 'uploader_id': uploader_id,
307 'id': playlist_id,
308 'title': current.get('title'),
309 'description': current.get('about'),
310 'entries': entries,
311 }
312
313
314 class BandcampWeeklyIE(BandcampIE):
315 IE_NAME = 'Bandcamp:weekly'
316 _VALID_URL = r'https?://(?:www\.)?bandcamp\.com/?\?(?:.*?&)?show=(?P<id>\d+)'
317 _TESTS = [{
318 'url': 'https://bandcamp.com/?show=224',
319 'md5': 'b00df799c733cf7e0c567ed187dea0fd',
320 'info_dict': {
321 'id': '224',
322 'ext': 'opus',
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',
329 'episode_id': '224',
330 },
331 'params': {
332 'format': 'opus-lo',
333 },
334 }, {
335 'url': 'https://bandcamp.com/?blah/blah@&show=228',
336 'only_matching': True
337 }]
338
339 def _real_extract(self, url):
340 show_id = self._match_id(url)
341 webpage = self._download_webpage(url, show_id)
342
343 blob = self._extract_data_attr(webpage, show_id, 'blob')
344
345 show = blob['bcw_data'][show_id]
346
347 formats = []
348 for format_id, format_url in show['audio_stream'].items():
349 if not url_or_none(format_url):
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)
364
365 title = show.get('audio_title') or 'Bandcamp Weekly'
366 subtitle = show.get('subtitle')
367 if subtitle:
368 title += ' - %s' % subtitle
369
370 return {
371 'id': show_id,
372 'title': title,
373 'description': show.get('desc') or show.get('short_desc'),
374 'duration': float_or_none(show.get('audio_duration')),
375 'is_live': False,
376 'release_date': unified_strdate(show.get('published_date')),
377 'series': 'Bandcamp Weekly',
378 'episode': show.get('subtitle'),
379 'episode_id': show_id,
380 'formats': formats
381 }
382
383
384 class BandcampUserIE(InfoExtractor):
385 IE_NAME = 'Bandcamp:user'
386 _VALID_URL = r'https?://(?!www\.)(?P<id>[^.]+)\.bandcamp\.com(?:/music)?/?(?:[#?]|$)'
387
388 _TESTS = [{
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 }, {
413 'url': 'https://steviasphere.bandcamp.com/music',
414 'playlist_mincount': 47,
415 'info_dict': {
416 'id': 'steviasphere',
417 'title': 'Discography of steviasphere',
418 },
419 }, {
420 'url': 'https://coldworldofficial.bandcamp.com/music',
421 'playlist_mincount': 10,
422 'info_dict': {
423 'id': 'coldworldofficial',
424 'title': 'Discography of coldworldofficial',
425 },
426 }, {
427 'url': 'https://nuclearwarnowproductions.bandcamp.com/music',
428 'playlist_mincount': 399,
429 'info_dict': {
430 'id': 'nuclearwarnowproductions',
431 'title': 'Discography of nuclearwarnowproductions',
432 },
433 }]
434
435 def _real_extract(self, url):
436 uploader = self._match_id(url)
437 webpage = self._download_webpage(url, uploader)
438
439 discography_data = (re.findall(r'<li data-item-id=["\'][^>]+>\s*<a href=["\'](?![^"\'/]*?/merch)([^"\']+)', webpage)
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))