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