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