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