]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/bandcamp.py
[bandcamp:weekly] Improve and extract more metadata (closes #12758)
[yt-dlp.git] / youtube_dl / extractor / bandcamp.py
CommitLineData
3798eadc
PH
1from __future__ import unicode_literals
2
45aef472 3import json
0aacd2de 4import random
45aef472 5import re
0aacd2de 6import time
45aef472
PH
7
8from .common import InfoExtractor
1cc79574 9from ..compat import (
cffa6aa1 10 compat_str,
09804265 11 compat_urlparse,
1cc79574
PH
12)
13from ..utils import (
45aef472 14 ExtractorError,
ba717dca
S
15 float_or_none,
16 int_or_none,
6d923aab 17 KNOWN_EXTENSIONS,
0aacd2de
S
18 parse_filesize,
19 unescapeHTML,
20 update_url_query,
62bafabc 21 unified_strdate,
45aef472
PH
22)
23
24
25class BandcampIE(InfoExtractor):
6d923aab 26 _VALID_URL = r'https?://.*?\.bandcamp\.com/track/(?P<title>[^/?#&]+)'
cffa6aa1 27 _TESTS = [{
3798eadc 28 'url': 'http://youtube-dl.bandcamp.com/track/youtube-dl-test-song',
3798eadc
PH
29 'md5': 'c557841d5e50261777a6585648adf439',
30 'info_dict': {
d9bf4652
S
31 'id': '1812978515',
32 'ext': 'mp3',
33 'title': "youtube-dl \"'/\\\u00e4\u21ad - youtube-dl test song \"'/\\\u00e4\u21ad",
34 'duration': 9.8485,
6f5ac90c 35 },
3798eadc 36 '_skip': 'There is a limit of 200 free downloads / month for the test song'
d9bf4652
S
37 }, {
38 'url': 'http://benprunty.bandcamp.com/track/lanius-battle',
0f63dc24 39 'md5': '0369ace6b939f0927e62c67a1a8d9fa7',
d9bf4652
S
40 'info_dict': {
41 'id': '2650410135',
0f63dc24
TF
42 'ext': 'aiff',
43 'title': 'Ben Prunty - Lanius (Battle)',
44 'uploader': 'Ben Prunty',
d9bf4652 45 },
cffa6aa1 46 }]
45aef472
PH
47
48 def _real_extract(self, url):
49 mobj = re.match(self._VALID_URL, url)
50 title = mobj.group('title')
51 webpage = self._download_webpage(url, title)
8b4774dc 52 thumbnail = self._html_search_meta('og:image', webpage, default=None)
45aef472 53 m_download = re.search(r'freeDownloadPage: "(.*?)"', webpage)
79981f03 54 if not m_download:
cffa6aa1 55 m_trackinfo = re.search(r'trackinfo: (.+),\s*?\n', webpage)
5ecd3c6a
PH
56 if m_trackinfo:
57 json_code = m_trackinfo.group(1)
79981f03 58 data = json.loads(json_code)[0]
70346165
T
59 track_id = compat_str(data['id'])
60
61 if not data.get('file'):
62 raise ExtractorError('Not streamable', video_id=track_id, expected=True)
5ecd3c6a 63
5ecd3c6a 64 formats = []
79981f03 65 for format_id, format_url in data['file'].items():
2902d44f 66 ext, abr_str = format_id.split('-', 1)
5ecd3c6a
PH
67 formats.append({
68 'format_id': format_id,
1e52776a 69 'url': self._proto_relative_url(format_url, 'http:'),
79981f03 70 'ext': ext,
5ecd3c6a 71 'vcodec': 'none',
79981f03 72 'acodec': ext,
ba717dca 73 'abr': int_or_none(abr_str),
5ecd3c6a
PH
74 })
75
76 self._sort_formats(formats)
cffa6aa1 77
d35dc6d3 78 return {
70346165 79 'id': track_id,
79981f03 80 'title': data['title'],
8b4774dc 81 'thumbnail': thumbnail,
cffa6aa1 82 'formats': formats,
ba717dca 83 'duration': float_or_none(data.get('duration')),
d35dc6d3 84 }
5ecd3c6a 85 else:
3798eadc 86 raise ExtractorError('No free songs found')
45aef472
PH
87
88 download_link = m_download.group(1)
d9bf4652 89 video_id = self._search_regex(
b524a001 90 r'(?ms)var TralbumData = .*?[{,]\s*id: (?P<id>\d+),?$',
99c2398b 91 webpage, 'video id')
45aef472 92
0aacd2de
S
93 download_webpage = self._download_webpage(
94 download_link, video_id, 'Downloading free downloads page')
95
96 blob = self._parse_json(
97 self._search_regex(
98 r'data-blob=(["\'])(?P<blob>{.+?})\1', download_webpage,
99 'blob', group='blob'),
100 video_id, transform_source=unescapeHTML)
101
102 info = blob['digital_items'][0]
103
104 downloads = info['downloads']
105 track = info['title']
106
107 artist = info.get('artist')
108 title = '%s - %s' % (artist, track) if artist else track
109
110 download_formats = {}
111 for f in blob['download_formats']:
112 name, ext = f.get('name'), f.get('file_extension')
113 if all(isinstance(x, compat_str) for x in (name, ext)):
114 download_formats[name] = ext.strip('.')
115
116 formats = []
117 for format_id, f in downloads.items():
118 format_url = f.get('url')
119 if not format_url:
120 continue
121 # Stat URL generation algorithm is reverse engineered from
122 # download_*_bundle_*.js
123 stat_url = update_url_query(
124 format_url.replace('/download/', '/statdownload/'), {
125 '.rand': int(time.time() * 1000 * random.random()),
126 })
127 format_id = f.get('encoding_name') or format_id
128 stat = self._download_json(
129 stat_url, video_id, 'Downloading %s JSON' % format_id,
130 transform_source=lambda s: s[s.index('{'):s.rindex('}') + 1],
131 fatal=False)
132 if not stat:
133 continue
134 retry_url = stat.get('retry_url')
135 if not isinstance(retry_url, compat_str):
136 continue
137 formats.append({
138 'url': self._proto_relative_url(retry_url, 'http:'),
139 'ext': download_formats.get(format_id),
140 'format_id': format_id,
141 'format_note': f.get('description'),
142 'filesize': parse_filesize(f.get('size_mb')),
143 'vcodec': 'none',
144 })
145 self._sort_formats(formats)
45aef472 146
5ecd3c6a
PH
147 return {
148 'id': video_id,
0aacd2de 149 'title': title,
8b4774dc 150 'thumbnail': info.get('thumb_url') or thumbnail,
f8b5ab8c 151 'uploader': info.get('artist'),
0aacd2de
S
152 'artist': artist,
153 'track': track,
154 'formats': formats,
5ecd3c6a 155 }
09804265
JMF
156
157
158class BandcampAlbumIE(InfoExtractor):
3798eadc 159 IE_NAME = 'Bandcamp:album'
6d923aab 160 _VALID_URL = r'https?://(?:(?P<subdomain>[^.]+)\.)?bandcamp\.com(?:/album/(?P<album_id>[^/?#&]+))?'
09804265 161
22a6f150 162 _TESTS = [{
3798eadc
PH
163 'url': 'http://blazo.bandcamp.com/album/jazz-format-mixtape-vol-1',
164 'playlist': [
d35dc6d3 165 {
3798eadc
PH
166 'md5': '39bc1eded3476e927c724321ddf116cf',
167 'info_dict': {
13ba3a64
PH
168 'id': '1353101989',
169 'ext': 'mp3',
3798eadc 170 'title': 'Intro',
d35dc6d3
JMF
171 }
172 },
173 {
3798eadc
PH
174 'md5': '1a2c32e2691474643e912cc6cd4bffaa',
175 'info_dict': {
13ba3a64
PH
176 'id': '38097443',
177 'ext': 'mp3',
3798eadc 178 'title': 'Kero One - Keep It Alive (Blazo remix)',
d35dc6d3
JMF
179 }
180 },
181 ],
13ba3a64
PH
182 'info_dict': {
183 'title': 'Jazz Format Mixtape vol.1',
72c1f8de
PH
184 'id': 'jazz-format-mixtape-vol-1',
185 'uploader_id': 'blazo',
13ba3a64 186 },
3798eadc
PH
187 'params': {
188 'playlistend': 2
d35dc6d3 189 },
72c1f8de 190 'skip': 'Bandcamp imposes download limits.'
22a6f150
PH
191 }, {
192 'url': 'http://nightbringer.bandcamp.com/album/hierophany-of-the-open-grave',
193 'info_dict': {
194 'title': 'Hierophany of the Open Grave',
72c1f8de
PH
195 'uploader_id': 'nightbringer',
196 'id': 'hierophany-of-the-open-grave',
22a6f150
PH
197 },
198 'playlist_mincount': 9,
1fa17469
S
199 }, {
200 'url': 'http://dotscale.bandcamp.com',
201 'info_dict': {
202 'title': 'Loom',
72c1f8de
PH
203 'id': 'dotscale',
204 'uploader_id': 'dotscale',
1fa17469
S
205 },
206 'playlist_mincount': 7,
64fc49ab
S
207 }, {
208 # with escaped quote in title
209 'url': 'https://jstrecords.bandcamp.com/album/entropy-ep',
210 'info_dict': {
211 'title': '"Entropy" EP',
212 'uploader_id': 'jstrecords',
213 'id': 'entropy-ep',
214 },
215 'playlist_mincount': 3,
019f4c03
YCH
216 }, {
217 # not all tracks have songs
218 'url': 'https://insulters.bandcamp.com/album/we-are-the-plague',
219 'info_dict': {
220 'id': 'we-are-the-plague',
221 'title': 'WE ARE THE PLAGUE',
222 'uploader_id': 'insulters',
223 },
224 'playlist_count': 2,
22a6f150 225 }]
d35dc6d3 226
62bafabc
AV
227 @classmethod
228 def suitable(cls, url):
6d923aab
S
229 return (False
230 if BandcampWeeklyIE.suitable(url) or BandcampIE.suitable(url)
231 else super(BandcampAlbumIE, cls).suitable(url))
62bafabc 232
09804265
JMF
233 def _real_extract(self, url):
234 mobj = re.match(self._VALID_URL, url)
72c1f8de
PH
235 uploader_id = mobj.group('subdomain')
236 album_id = mobj.group('album_id')
237 playlist_id = album_id or uploader_id
238 webpage = self._download_webpage(url, playlist_id)
019f4c03
YCH
239 track_elements = re.findall(
240 r'(?s)<div[^>]*>(.*?<a[^>]+href="([^"]+?)"[^>]+itemprop="url"[^>]*>.*?)</div>', webpage)
241 if not track_elements:
3798eadc 242 raise ExtractorError('The page doesn\'t contain any tracks')
019f4c03 243 # Only tracks with duration info have songs
09804265
JMF
244 entries = [
245 self.url_result(compat_urlparse.urljoin(url, t_path), ie=BandcampIE.ie_key())
019f4c03
YCH
246 for elem_content, t_path in track_elements
247 if self._html_search_meta('duration', elem_content, default=None)]
248
64fc49ab
S
249 title = self._html_search_regex(
250 r'album_title\s*:\s*"((?:\\.|[^"\\])+?)"',
251 webpage, 'title', fatal=False)
252 if title:
253 title = title.replace(r'\"', '"')
09804265
JMF
254 return {
255 '_type': 'playlist',
72c1f8de 256 'uploader_id': uploader_id,
b48f147d 257 'id': playlist_id,
09804265
JMF
258 'title': title,
259 'entries': entries,
260 }
62bafabc
AV
261
262
263class BandcampWeeklyIE(InfoExtractor):
6d923aab
S
264 IE_NAME = 'Bandcamp:weekly'
265 _VALID_URL = r'https?://(?:www\.)?bandcamp\.com/?\?(?:.*?&)?show=(?P<id>\d+)'
62bafabc
AV
266 _TESTS = [{
267 'url': 'https://bandcamp.com/?show=224',
268 'md5': 'b00df799c733cf7e0c567ed187dea0fd',
269 'info_dict': {
270 'id': '224',
271 'ext': 'opus',
6d923aab
S
272 'title': 'BC Weekly April 4th 2017 - Magic Moments',
273 'description': 'md5:5d48150916e8e02d030623a48512c874',
274 'duration': 5829.77,
275 'release_date': '20170404',
276 'series': 'Bandcamp Weekly',
277 'episode': 'Magic Moments',
278 'episode_number': 208,
279 'episode_id': '224',
62bafabc
AV
280 }
281 }, {
282 'url': 'https://bandcamp.com/?blah/blah@&show=228',
283 'only_matching': True
284 }]
285
286 def _real_extract(self, url):
287 video_id = self._match_id(url)
288 webpage = self._download_webpage(url, video_id)
289
290 blob = self._parse_json(
291 self._search_regex(
292 r'data-blob=(["\'])(?P<blob>{.+?})\1', webpage,
293 'blob', group='blob'),
294 video_id, transform_source=unescapeHTML)
295
296 show = blob['bcw_show']
297
298 # This is desired because any invalid show id redirects to `bandcamp.com`
299 # which happens to expose the latest Bandcamp Weekly episode.
6d923aab 300 show_id = int_or_none(show.get('show_id')) or int_or_none(video_id)
62bafabc 301
6d923aab
S
302 formats = []
303 for format_id, format_url in show['audio_stream'].items():
304 if not isinstance(format_url, compat_str):
305 continue
306 for known_ext in KNOWN_EXTENSIONS:
307 if known_ext in format_id:
308 ext = known_ext
309 break
310 else:
311 ext = None
312 formats.append({
313 'format_id': format_id,
314 'url': format_url,
315 'ext': ext,
316 'vcodec': 'none',
317 })
318 self._sort_formats(formats)
62bafabc 319
6d923aab
S
320 title = show.get('audio_title') or 'Bandcamp Weekly'
321 subtitle = show.get('subtitle')
322 if subtitle:
323 title += ' - %s' % subtitle
62bafabc 324
6d923aab
S
325 episode_number = None
326 seq = blob.get('bcw_seq')
62bafabc 327
6d923aab
S
328 if seq and isinstance(seq, list):
329 try:
330 episode_number = next(
331 int_or_none(e.get('episode_number'))
332 for e in seq
333 if isinstance(e, dict) and int_or_none(e.get('id')) == show_id)
334 except StopIteration:
335 pass
62bafabc
AV
336
337 return {
338 'id': video_id,
6d923aab
S
339 'title': title,
340 'description': show.get('desc') or show.get('short_desc'),
62bafabc 341 'duration': float_or_none(show.get('audio_duration')),
62bafabc
AV
342 'is_live': False,
343 'release_date': unified_strdate(show.get('published_date')),
344 'series': 'Bandcamp Weekly',
6d923aab
S
345 'episode': show.get('subtitle'),
346 'episode_number': episode_number,
62bafabc
AV
347 'episode_id': compat_str(video_id),
348 'formats': formats
349 }