[ie/wistia] Support password-protected videos (#11100)
[yt-dlp3.git] / yt_dlp / extractor / bandcamp.py
blob0abe05982996db5206df07edeaf44debae5f9b60
1 import functools
2 import json
3 import random
4 import re
5 import time
7 from .common import InfoExtractor
8 from ..utils import (
9 KNOWN_EXTENSIONS,
10 ExtractorError,
11 extract_attributes,
12 float_or_none,
13 get_element_html_by_id,
14 int_or_none,
15 parse_filesize,
16 str_or_none,
17 try_get,
18 unified_strdate,
19 unified_timestamp,
20 update_url_query,
21 url_or_none,
22 urljoin,
24 from ..utils.traversal import traverse_obj
27 class BandcampIE(InfoExtractor):
28 _VALID_URL = r'https?://(?P<uploader>[^/]+)\.bandcamp\.com/track/(?P<id>[^/?#&]+)'
29 _EMBED_REGEX = [r'<meta property="og:url"[^>]*?content="(?P<url>.*?bandcamp\.com.*?)"']
30 _TESTS = [{
31 'url': 'http://youtube-dl.bandcamp.com/track/youtube-dl-test-song',
32 'md5': 'c557841d5e50261777a6585648adf439',
33 'info_dict': {
34 'id': '1812978515',
35 'ext': 'mp3',
36 'title': 'youtube-dl "\'/\\ä↭ - youtube-dl "\'/\\ä↭ - youtube-dl test song "\'/\\ä↭',
37 'duration': 9.8485,
38 'uploader': 'youtube-dl "\'/\\ä↭',
39 'upload_date': '20121129',
40 'timestamp': 1354224127,
41 'track': 'youtube-dl "\'/\\ä↭ - youtube-dl test song "\'/\\ä↭',
42 'album_artist': 'youtube-dl "\'/\\ä↭',
43 'track_id': '1812978515',
44 'artist': 'youtube-dl "\'/\\ä↭',
45 'uploader_url': 'https://youtube-dl.bandcamp.com',
46 'uploader_id': 'youtube-dl',
47 'thumbnail': 'https://f4.bcbits.com/img/a3216802731_5.jpg',
49 'skip': 'There is a limit of 200 free downloads / month for the test song',
50 }, {
51 # free download
52 'url': 'http://benprunty.bandcamp.com/track/lanius-battle',
53 'info_dict': {
54 'id': '2650410135',
55 'ext': 'm4a',
56 'acodec': r're:[fa]lac',
57 'title': 'Ben Prunty - Lanius (Battle)',
58 'thumbnail': r're:^https?://.*\.jpg$',
59 'uploader': 'Ben Prunty',
60 'timestamp': 1396508491,
61 'upload_date': '20140403',
62 'release_timestamp': 1396483200,
63 'release_date': '20140403',
64 'duration': 260.877,
65 'track': 'Lanius (Battle)',
66 'track_number': 1,
67 'track_id': '2650410135',
68 'artist': 'Ben Prunty',
69 'album_artist': 'Ben Prunty',
70 'album': 'FTL: Advanced Edition Soundtrack',
71 'uploader_url': 'https://benprunty.bandcamp.com',
72 'uploader_id': 'benprunty',
74 }, {
75 # no free download, mp3 128
76 'url': 'https://relapsealumni.bandcamp.com/track/hail-to-fire',
77 'md5': 'fec12ff55e804bb7f7ebeb77a800c8b7',
78 'info_dict': {
79 'id': '2584466013',
80 'ext': 'mp3',
81 'title': 'Mastodon - Hail to Fire',
82 'thumbnail': r're:^https?://.*\.jpg$',
83 'uploader': 'Mastodon',
84 'timestamp': 1322005399,
85 'upload_date': '20111122',
86 'release_timestamp': 1076112000,
87 'release_date': '20040207',
88 'duration': 120.79,
89 'track': 'Hail to Fire',
90 'track_number': 5,
91 'track_id': '2584466013',
92 'artist': 'Mastodon',
93 'album_artist': 'Mastodon',
94 'album': 'Call of the Mastodon',
95 'uploader_url': 'https://relapsealumni.bandcamp.com',
96 'uploader_id': 'relapsealumni',
98 }, {
99 # track from compilation album (artist/album_artist difference)
100 'url': 'https://diskotopia.bandcamp.com/track/safehouse',
101 'md5': '19c5337bca1428afa54129f86a2f6a69',
102 'info_dict': {
103 'id': '1978174799',
104 'ext': 'mp3',
105 'title': 'submerse - submerse - Safehouse',
106 'thumbnail': r're:^https?://.*\.jpg$',
107 'uploader': 'submerse',
108 'timestamp': 1480779297,
109 'upload_date': '20161203',
110 'release_timestamp': 1481068800,
111 'release_date': '20161207',
112 'duration': 154.066,
113 'track': 'submerse - Safehouse',
114 'track_number': 3,
115 'track_id': '1978174799',
116 'artist': 'submerse',
117 'album_artist': 'Diskotopia',
118 'album': 'DSK F/W 2016-2017 Free Compilation',
119 'uploader_url': 'https://diskotopia.bandcamp.com',
120 'uploader_id': 'diskotopia',
124 def _extract_data_attr(self, webpage, video_id, attr='tralbum', fatal=True):
125 return self._parse_json(self._html_search_regex(
126 rf'data-{attr}=(["\'])({{.+?}})\1', webpage,
127 attr + ' data', group=2), video_id, fatal=fatal)
129 def _real_extract(self, url):
130 title, uploader = self._match_valid_url(url).group('id', 'uploader')
131 webpage = self._download_webpage(url, title)
132 tralbum = self._extract_data_attr(webpage, title)
133 thumbnail = self._og_search_thumbnail(webpage)
135 track_id = None
136 track = None
137 track_number = None
138 duration = None
140 formats = []
141 track_info = try_get(tralbum, lambda x: x['trackinfo'][0], dict)
142 if track_info:
143 file_ = track_info.get('file')
144 if isinstance(file_, dict):
145 for format_id, format_url in file_.items():
146 if not url_or_none(format_url):
147 continue
148 ext, abr_str = format_id.split('-', 1)
149 formats.append({
150 'format_id': format_id,
151 'url': self._proto_relative_url(format_url, 'http:'),
152 'ext': ext,
153 'vcodec': 'none',
154 'acodec': ext,
155 'abr': int_or_none(abr_str),
157 track = track_info.get('title')
158 track_id = str_or_none(
159 track_info.get('track_id') or track_info.get('id'))
160 track_number = int_or_none(track_info.get('track_num'))
161 duration = float_or_none(track_info.get('duration'))
163 embed = self._extract_data_attr(webpage, title, 'embed', False)
164 current = tralbum.get('current') or {}
165 artist = embed.get('artist') or current.get('artist') or tralbum.get('artist')
166 album_artist = self._html_search_regex(
167 r'<h3 class="albumTitle">[\S\s]*?by\s*<span>\s*<a href="[^>]+">\s*([^>]+?)\s*</a>',
168 webpage, 'album artist', fatal=False)
169 timestamp = unified_timestamp(
170 current.get('publish_date') or tralbum.get('album_publish_date'))
172 download_link = tralbum.get('freeDownloadPage')
173 if download_link:
174 track_id = str(tralbum['id'])
176 download_webpage = self._download_webpage(
177 download_link, track_id, 'Downloading free downloads page')
179 blob = self._extract_data_attr(download_webpage, track_id, 'blob')
181 info = try_get(
182 blob, (lambda x: x['digital_items'][0],
183 lambda x: x['download_items'][0]), dict)
184 if info:
185 downloads = info.get('downloads')
186 if isinstance(downloads, dict):
187 if not track:
188 track = info.get('title')
189 if not artist:
190 artist = info.get('artist')
191 if not thumbnail:
192 thumbnail = info.get('thumb_url')
194 download_formats = {}
195 download_formats_list = blob.get('download_formats')
196 if isinstance(download_formats_list, list):
197 for f in blob['download_formats']:
198 name, ext = f.get('name'), f.get('file_extension')
199 if all(isinstance(x, str) for x in (name, ext)):
200 download_formats[name] = ext.strip('.')
202 for format_id, f in downloads.items():
203 format_url = f.get('url')
204 if not format_url:
205 continue
206 # Stat URL generation algorithm is reverse engineered from
207 # download_*_bundle_*.js
208 stat_url = update_url_query(
209 format_url.replace('/download/', '/statdownload/'), {
210 '.rand': int(time.time() * 1000 * random.random()),
212 format_id = f.get('encoding_name') or format_id
213 stat = self._download_json(
214 stat_url, track_id, f'Downloading {format_id} JSON',
215 transform_source=lambda s: s[s.index('{'):s.rindex('}') + 1],
216 fatal=False)
217 if not stat:
218 continue
219 retry_url = url_or_none(stat.get('retry_url'))
220 if not retry_url:
221 continue
222 formats.append({
223 'url': self._proto_relative_url(retry_url, 'http:'),
224 'ext': download_formats.get(format_id),
225 'format_id': format_id,
226 'format_note': f.get('description'),
227 'filesize': parse_filesize(f.get('size_mb')),
228 'vcodec': 'none',
229 'acodec': format_id.split('-')[0],
232 title = f'{artist} - {track}' if artist else track
234 if not duration:
235 duration = float_or_none(self._html_search_meta(
236 'duration', webpage, default=None))
238 return {
239 'id': track_id,
240 'title': title,
241 'thumbnail': thumbnail,
242 'uploader': artist,
243 'uploader_id': uploader,
244 'uploader_url': f'https://{uploader}.bandcamp.com',
245 'timestamp': timestamp,
246 'release_timestamp': unified_timestamp(tralbum.get('album_release_date')),
247 'duration': duration,
248 'track': track,
249 'track_number': track_number,
250 'track_id': track_id,
251 'artist': artist,
252 'album': embed.get('album_title'),
253 'album_artist': album_artist,
254 'formats': formats,
258 class BandcampAlbumIE(BandcampIE): # XXX: Do not subclass from concrete IE
259 IE_NAME = 'Bandcamp:album'
260 _VALID_URL = r'https?://(?:(?P<subdomain>[^.]+)\.)?bandcamp\.com/album/(?P<id>[^/?#&]+)'
262 _TESTS = [{
263 'url': 'http://blazo.bandcamp.com/album/jazz-format-mixtape-vol-1',
264 'playlist': [
266 'md5': '39bc1eded3476e927c724321ddf116cf',
267 'info_dict': {
268 'id': '1353101989',
269 'ext': 'mp3',
270 'title': 'Blazo - Intro',
271 'timestamp': 1311756226,
272 'upload_date': '20110727',
273 'uploader': 'Blazo',
277 'md5': '1a2c32e2691474643e912cc6cd4bffaa',
278 'info_dict': {
279 'id': '38097443',
280 'ext': 'mp3',
281 'title': 'Blazo - Kero One - Keep It Alive (Blazo remix)',
282 'timestamp': 1311757238,
283 'upload_date': '20110727',
284 'uploader': 'Blazo',
288 'info_dict': {
289 'title': 'Jazz Format Mixtape vol.1',
290 'id': 'jazz-format-mixtape-vol-1',
291 'uploader_id': 'blazo',
293 'params': {
294 'playlistend': 2,
296 'skip': 'Bandcamp imposes download limits.',
297 }, {
298 'url': 'http://nightbringer.bandcamp.com/album/hierophany-of-the-open-grave',
299 'info_dict': {
300 'title': 'Hierophany of the Open Grave',
301 'uploader_id': 'nightbringer',
302 'id': 'hierophany-of-the-open-grave',
304 'playlist_mincount': 9,
305 }, {
306 # with escaped quote in title
307 'url': 'https://jstrecords.bandcamp.com/album/entropy-ep',
308 'info_dict': {
309 'title': '"Entropy" EP',
310 'uploader_id': 'jstrecords',
311 'id': 'entropy-ep',
312 'description': 'md5:0ff22959c943622972596062f2f366a5',
314 'playlist_mincount': 3,
315 }, {
316 # not all tracks have songs
317 'url': 'https://insulters.bandcamp.com/album/we-are-the-plague',
318 'info_dict': {
319 'id': 'we-are-the-plague',
320 'title': 'WE ARE THE PLAGUE',
321 'uploader_id': 'insulters',
322 'description': 'md5:b3cf845ee41b2b1141dc7bde9237255f',
324 'playlist_count': 2,
327 @classmethod
328 def suitable(cls, url):
329 return (False
330 if BandcampWeeklyIE.suitable(url) or BandcampIE.suitable(url)
331 else super().suitable(url))
333 def _real_extract(self, url):
334 uploader_id, album_id = self._match_valid_url(url).groups()
335 playlist_id = album_id or uploader_id
336 webpage = self._download_webpage(url, playlist_id)
337 tralbum = self._extract_data_attr(webpage, playlist_id)
338 track_info = tralbum.get('trackinfo')
339 if not track_info:
340 raise ExtractorError('The page doesn\'t contain any tracks')
341 # Only tracks with duration info have songs
342 entries = [
343 self.url_result(
344 urljoin(url, t['title_link']), BandcampIE.ie_key(),
345 str_or_none(t.get('track_id') or t.get('id')), t.get('title'))
346 for t in track_info
347 if t.get('duration')]
349 current = tralbum.get('current') or {}
351 return {
352 '_type': 'playlist',
353 'uploader_id': uploader_id,
354 'id': playlist_id,
355 'title': current.get('title'),
356 'description': current.get('about'),
357 'entries': entries,
361 class BandcampWeeklyIE(BandcampIE): # XXX: Do not subclass from concrete IE
362 IE_NAME = 'Bandcamp:weekly'
363 _VALID_URL = r'https?://(?:www\.)?bandcamp\.com/?\?(?:.*?&)?show=(?P<id>\d+)'
364 _TESTS = [{
365 'url': 'https://bandcamp.com/?show=224',
366 'md5': 'b00df799c733cf7e0c567ed187dea0fd',
367 'info_dict': {
368 'id': '224',
369 'ext': 'opus',
370 'title': 'BC Weekly April 4th 2017 - Magic Moments',
371 'description': 'md5:5d48150916e8e02d030623a48512c874',
372 'duration': 5829.77,
373 'release_date': '20170404',
374 'series': 'Bandcamp Weekly',
375 'episode': 'Magic Moments',
376 'episode_id': '224',
378 'params': {
379 'format': 'opus-lo',
381 }, {
382 'url': 'https://bandcamp.com/?blah/blah@&show=228',
383 'only_matching': True,
386 def _real_extract(self, url):
387 show_id = self._match_id(url)
388 webpage = self._download_webpage(url, show_id)
390 blob = self._extract_data_attr(webpage, show_id, 'blob')
392 show = blob['bcw_data'][show_id]
394 formats = []
395 for format_id, format_url in show['audio_stream'].items():
396 if not url_or_none(format_url):
397 continue
398 for known_ext in KNOWN_EXTENSIONS:
399 if known_ext in format_id:
400 ext = known_ext
401 break
402 else:
403 ext = None
404 formats.append({
405 'format_id': format_id,
406 'url': format_url,
407 'ext': ext,
408 'vcodec': 'none',
411 title = show.get('audio_title') or 'Bandcamp Weekly'
412 subtitle = show.get('subtitle')
413 if subtitle:
414 title += f' - {subtitle}'
416 return {
417 'id': show_id,
418 'title': title,
419 'description': show.get('desc') or show.get('short_desc'),
420 'duration': float_or_none(show.get('audio_duration')),
421 'is_live': False,
422 'release_date': unified_strdate(show.get('published_date')),
423 'series': 'Bandcamp Weekly',
424 'episode': show.get('subtitle'),
425 'episode_id': show_id,
426 'formats': formats,
430 class BandcampUserIE(InfoExtractor):
431 IE_NAME = 'Bandcamp:user'
432 _VALID_URL = r'https?://(?!www\.)(?P<id>[^.]+)\.bandcamp\.com(?:/music)?/?(?:[#?]|$)'
434 _TESTS = [{
435 # Type 1 Bandcamp user page.
436 'url': 'https://adrianvonziegler.bandcamp.com',
437 'info_dict': {
438 'id': 'adrianvonziegler',
439 'title': 'Discography of adrianvonziegler',
441 'playlist_mincount': 23,
442 }, {
443 # Bandcamp user page with only one album
444 'url': 'http://dotscale.bandcamp.com',
445 'info_dict': {
446 'id': 'dotscale',
447 'title': 'Discography of dotscale',
449 'playlist_count': 1,
450 }, {
451 # Type 2 Bandcamp user page.
452 'url': 'https://nightcallofficial.bandcamp.com',
453 'info_dict': {
454 'id': 'nightcallofficial',
455 'title': 'Discography of nightcallofficial',
457 'playlist_count': 4,
458 }, {
459 'url': 'https://steviasphere.bandcamp.com/music',
460 'playlist_mincount': 47,
461 'info_dict': {
462 'id': 'steviasphere',
463 'title': 'Discography of steviasphere',
465 }, {
466 'url': 'https://coldworldofficial.bandcamp.com/music',
467 'playlist_mincount': 7,
468 'info_dict': {
469 'id': 'coldworldofficial',
470 'title': 'Discography of coldworldofficial',
472 }, {
473 'url': 'https://nuclearwarnowproductions.bandcamp.com/music',
474 'playlist_mincount': 399,
475 'info_dict': {
476 'id': 'nuclearwarnowproductions',
477 'title': 'Discography of nuclearwarnowproductions',
481 def _yield_items(self, webpage):
482 yield from (
483 re.findall(r'<li data-item-id=["\'][^>]+>\s*<a href=["\'](?![^"\'/]*?/merch)([^"\']+)', webpage)
484 or re.findall(r'<div[^>]+trackTitle["\'][^"\']+["\']([^"\']+)', webpage))
486 yield from traverse_obj(webpage, (
487 {functools.partial(get_element_html_by_id, 'music-grid')}, {extract_attributes},
488 'data-client-items', {json.loads}, ..., 'page_url', {str}))
490 def _real_extract(self, url):
491 uploader = self._match_id(url)
492 webpage = self._download_webpage(url, uploader)
494 return self.playlist_from_matches(
495 self._yield_items(webpage), uploader, f'Discography of {uploader}',
496 getter=functools.partial(urljoin, url))