]> jfr.im git - yt-dlp.git/blame - youtube_dl/extractor/bandcamp.py
[pornhub:uservideos] Add missing raise
[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,
0aacd2de
S
17 parse_filesize,
18 unescapeHTML,
19 update_url_query,
45aef472
PH
20)
21
22
23class BandcampIE(InfoExtractor):
b48f147d 24 _VALID_URL = r'https?://.*?\.bandcamp\.com/track/(?P<title>.*)'
cffa6aa1 25 _TESTS = [{
3798eadc 26 'url': 'http://youtube-dl.bandcamp.com/track/youtube-dl-test-song',
3798eadc
PH
27 'md5': 'c557841d5e50261777a6585648adf439',
28 'info_dict': {
d9bf4652
S
29 'id': '1812978515',
30 'ext': 'mp3',
31 'title': "youtube-dl \"'/\\\u00e4\u21ad - youtube-dl test song \"'/\\\u00e4\u21ad",
32 'duration': 9.8485,
6f5ac90c 33 },
3798eadc 34 '_skip': 'There is a limit of 200 free downloads / month for the test song'
d9bf4652
S
35 }, {
36 'url': 'http://benprunty.bandcamp.com/track/lanius-battle',
0f63dc24 37 'md5': '0369ace6b939f0927e62c67a1a8d9fa7',
d9bf4652
S
38 'info_dict': {
39 'id': '2650410135',
0f63dc24
TF
40 'ext': 'aiff',
41 'title': 'Ben Prunty - Lanius (Battle)',
42 'uploader': 'Ben Prunty',
d9bf4652 43 },
cffa6aa1 44 }]
45aef472
PH
45
46 def _real_extract(self, url):
47 mobj = re.match(self._VALID_URL, url)
48 title = mobj.group('title')
49 webpage = self._download_webpage(url, title)
8b4774dc 50 thumbnail = self._html_search_meta('og:image', webpage, default=None)
45aef472 51 m_download = re.search(r'freeDownloadPage: "(.*?)"', webpage)
79981f03 52 if not m_download:
cffa6aa1 53 m_trackinfo = re.search(r'trackinfo: (.+),\s*?\n', webpage)
5ecd3c6a
PH
54 if m_trackinfo:
55 json_code = m_trackinfo.group(1)
79981f03 56 data = json.loads(json_code)[0]
70346165
T
57 track_id = compat_str(data['id'])
58
59 if not data.get('file'):
60 raise ExtractorError('Not streamable', video_id=track_id, expected=True)
5ecd3c6a 61
5ecd3c6a 62 formats = []
79981f03 63 for format_id, format_url in data['file'].items():
2902d44f 64 ext, abr_str = format_id.split('-', 1)
5ecd3c6a
PH
65 formats.append({
66 'format_id': format_id,
1e52776a 67 'url': self._proto_relative_url(format_url, 'http:'),
79981f03 68 'ext': ext,
5ecd3c6a 69 'vcodec': 'none',
79981f03 70 'acodec': ext,
ba717dca 71 'abr': int_or_none(abr_str),
5ecd3c6a
PH
72 })
73
74 self._sort_formats(formats)
cffa6aa1 75
d35dc6d3 76 return {
70346165 77 'id': track_id,
79981f03 78 'title': data['title'],
8b4774dc 79 'thumbnail': thumbnail,
cffa6aa1 80 'formats': formats,
ba717dca 81 'duration': float_or_none(data.get('duration')),
d35dc6d3 82 }
5ecd3c6a 83 else:
3798eadc 84 raise ExtractorError('No free songs found')
45aef472
PH
85
86 download_link = m_download.group(1)
d9bf4652 87 video_id = self._search_regex(
b524a001 88 r'(?ms)var TralbumData = .*?[{,]\s*id: (?P<id>\d+),?$',
99c2398b 89 webpage, 'video id')
45aef472 90
0aacd2de
S
91 download_webpage = self._download_webpage(
92 download_link, video_id, 'Downloading free downloads page')
93
94 blob = self._parse_json(
95 self._search_regex(
96 r'data-blob=(["\'])(?P<blob>{.+?})\1', download_webpage,
97 'blob', group='blob'),
98 video_id, transform_source=unescapeHTML)
99
100 info = blob['digital_items'][0]
101
102 downloads = info['downloads']
103 track = info['title']
104
105 artist = info.get('artist')
106 title = '%s - %s' % (artist, track) if artist else track
107
108 download_formats = {}
109 for f in blob['download_formats']:
110 name, ext = f.get('name'), f.get('file_extension')
111 if all(isinstance(x, compat_str) for x in (name, ext)):
112 download_formats[name] = ext.strip('.')
113
114 formats = []
115 for format_id, f in downloads.items():
116 format_url = f.get('url')
117 if not format_url:
118 continue
119 # Stat URL generation algorithm is reverse engineered from
120 # download_*_bundle_*.js
121 stat_url = update_url_query(
122 format_url.replace('/download/', '/statdownload/'), {
123 '.rand': int(time.time() * 1000 * random.random()),
124 })
125 format_id = f.get('encoding_name') or format_id
126 stat = self._download_json(
127 stat_url, video_id, 'Downloading %s JSON' % format_id,
128 transform_source=lambda s: s[s.index('{'):s.rindex('}') + 1],
129 fatal=False)
130 if not stat:
131 continue
132 retry_url = stat.get('retry_url')
133 if not isinstance(retry_url, compat_str):
134 continue
135 formats.append({
136 'url': self._proto_relative_url(retry_url, 'http:'),
137 'ext': download_formats.get(format_id),
138 'format_id': format_id,
139 'format_note': f.get('description'),
140 'filesize': parse_filesize(f.get('size_mb')),
141 'vcodec': 'none',
142 })
143 self._sort_formats(formats)
45aef472 144
5ecd3c6a
PH
145 return {
146 'id': video_id,
0aacd2de 147 'title': title,
8b4774dc 148 'thumbnail': info.get('thumb_url') or thumbnail,
f8b5ab8c 149 'uploader': info.get('artist'),
0aacd2de
S
150 'artist': artist,
151 'track': track,
152 'formats': formats,
5ecd3c6a 153 }
09804265
JMF
154
155
156class BandcampAlbumIE(InfoExtractor):
3798eadc 157 IE_NAME = 'Bandcamp:album'
72c1f8de 158 _VALID_URL = r'https?://(?:(?P<subdomain>[^.]+)\.)?bandcamp\.com(?:/album/(?P<album_id>[^?#]+)|/?(?:$|[?#]))'
09804265 159
22a6f150 160 _TESTS = [{
3798eadc
PH
161 'url': 'http://blazo.bandcamp.com/album/jazz-format-mixtape-vol-1',
162 'playlist': [
d35dc6d3 163 {
3798eadc
PH
164 'md5': '39bc1eded3476e927c724321ddf116cf',
165 'info_dict': {
13ba3a64
PH
166 'id': '1353101989',
167 'ext': 'mp3',
3798eadc 168 'title': 'Intro',
d35dc6d3
JMF
169 }
170 },
171 {
3798eadc
PH
172 'md5': '1a2c32e2691474643e912cc6cd4bffaa',
173 'info_dict': {
13ba3a64
PH
174 'id': '38097443',
175 'ext': 'mp3',
3798eadc 176 'title': 'Kero One - Keep It Alive (Blazo remix)',
d35dc6d3
JMF
177 }
178 },
179 ],
13ba3a64
PH
180 'info_dict': {
181 'title': 'Jazz Format Mixtape vol.1',
72c1f8de
PH
182 'id': 'jazz-format-mixtape-vol-1',
183 'uploader_id': 'blazo',
13ba3a64 184 },
3798eadc
PH
185 'params': {
186 'playlistend': 2
d35dc6d3 187 },
72c1f8de 188 'skip': 'Bandcamp imposes download limits.'
22a6f150
PH
189 }, {
190 'url': 'http://nightbringer.bandcamp.com/album/hierophany-of-the-open-grave',
191 'info_dict': {
192 'title': 'Hierophany of the Open Grave',
72c1f8de
PH
193 'uploader_id': 'nightbringer',
194 'id': 'hierophany-of-the-open-grave',
22a6f150
PH
195 },
196 'playlist_mincount': 9,
1fa17469
S
197 }, {
198 'url': 'http://dotscale.bandcamp.com',
199 'info_dict': {
200 'title': 'Loom',
72c1f8de
PH
201 'id': 'dotscale',
202 'uploader_id': 'dotscale',
1fa17469
S
203 },
204 'playlist_mincount': 7,
64fc49ab
S
205 }, {
206 # with escaped quote in title
207 'url': 'https://jstrecords.bandcamp.com/album/entropy-ep',
208 'info_dict': {
209 'title': '"Entropy" EP',
210 'uploader_id': 'jstrecords',
211 'id': 'entropy-ep',
212 },
213 'playlist_mincount': 3,
019f4c03
YCH
214 }, {
215 # not all tracks have songs
216 'url': 'https://insulters.bandcamp.com/album/we-are-the-plague',
217 'info_dict': {
218 'id': 'we-are-the-plague',
219 'title': 'WE ARE THE PLAGUE',
220 'uploader_id': 'insulters',
221 },
222 'playlist_count': 2,
22a6f150 223 }]
d35dc6d3 224
09804265
JMF
225 def _real_extract(self, url):
226 mobj = re.match(self._VALID_URL, url)
72c1f8de
PH
227 uploader_id = mobj.group('subdomain')
228 album_id = mobj.group('album_id')
229 playlist_id = album_id or uploader_id
230 webpage = self._download_webpage(url, playlist_id)
019f4c03
YCH
231 track_elements = re.findall(
232 r'(?s)<div[^>]*>(.*?<a[^>]+href="([^"]+?)"[^>]+itemprop="url"[^>]*>.*?)</div>', webpage)
233 if not track_elements:
3798eadc 234 raise ExtractorError('The page doesn\'t contain any tracks')
019f4c03 235 # Only tracks with duration info have songs
09804265
JMF
236 entries = [
237 self.url_result(compat_urlparse.urljoin(url, t_path), ie=BandcampIE.ie_key())
019f4c03
YCH
238 for elem_content, t_path in track_elements
239 if self._html_search_meta('duration', elem_content, default=None)]
240
64fc49ab
S
241 title = self._html_search_regex(
242 r'album_title\s*:\s*"((?:\\.|[^"\\])+?)"',
243 webpage, 'title', fatal=False)
244 if title:
245 title = title.replace(r'\"', '"')
09804265
JMF
246 return {
247 '_type': 'playlist',
72c1f8de 248 'uploader_id': uploader_id,
b48f147d 249 'id': playlist_id,
09804265
JMF
250 'title': title,
251 'entries': entries,
252 }