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