[bandcamp] Extract track_number (closes #17266)
[youtube-dl] / 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     KNOWN_EXTENSIONS,
18     parse_filesize,
19     unescapeHTML,
20     update_url_query,
21     unified_strdate,
22     url_or_none,
23 )
24
25
26 class BandcampIE(InfoExtractor):
27     _VALID_URL = r'https?://.*?\.bandcamp\.com/track/(?P<title>[^/?#&]+)'
28     _TESTS = [{
29         'url': 'http://youtube-dl.bandcamp.com/track/youtube-dl-test-song',
30         'md5': 'c557841d5e50261777a6585648adf439',
31         'info_dict': {
32             'id': '1812978515',
33             'ext': 'mp3',
34             'title': "youtube-dl  \"'/\\\u00e4\u21ad - youtube-dl test song \"'/\\\u00e4\u21ad",
35             'duration': 9.8485,
36         },
37         '_skip': 'There is a limit of 200 free downloads / month for the test song'
38     }, {
39         'url': 'http://benprunty.bandcamp.com/track/lanius-battle',
40         'md5': '0369ace6b939f0927e62c67a1a8d9fa7',
41         'info_dict': {
42             'id': '2650410135',
43             'ext': 'aiff',
44             'title': 'Ben Prunty - Lanius (Battle)',
45             'uploader': 'Ben Prunty',
46         },
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         },
58     }]
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)
64         thumbnail = self._html_search_meta('og:image', webpage, default=None)
65         m_download = re.search(r'freeDownloadPage: "(.*?)"', webpage)
66         if not m_download:
67             m_trackinfo = re.search(r'trackinfo: (.+),\s*?\n', webpage)
68             if m_trackinfo:
69                 json_code = m_trackinfo.group(1)
70                 data = json.loads(json_code)[0]
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)
75
76                 formats = []
77                 for format_id, format_url in data['file'].items():
78                     ext, abr_str = format_id.split('-', 1)
79                     formats.append({
80                         'format_id': format_id,
81                         'url': self._proto_relative_url(format_url, 'http:'),
82                         'ext': ext,
83                         'vcodec': 'none',
84                         'acodec': ext,
85                         'abr': int_or_none(abr_str),
86                     })
87
88                 self._sort_formats(formats)
89
90                 return {
91                     'id': track_id,
92                     'title': data['title'],
93                     'thumbnail': thumbnail,
94                     'formats': formats,
95                     'duration': float_or_none(data.get('duration')),
96                     'track_number': int_or_none(data.get('track_num')),
97                 }
98             else:
99                 raise ExtractorError('No free songs found')
100
101         download_link = m_download.group(1)
102         video_id = self._search_regex(
103             r'(?ms)var TralbumData = .*?[{,]\s*id: (?P<id>\d+),?$',
104             webpage, 'video id')
105
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
147             retry_url = url_or_none(stat.get('retry_url'))
148             if not retry_url:
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)
159
160         return {
161             'id': video_id,
162             'title': title,
163             'thumbnail': info.get('thumb_url') or thumbnail,
164             'uploader': info.get('artist'),
165             'artist': artist,
166             'track': track,
167             'formats': formats,
168         }
169
170
171 class BandcampAlbumIE(InfoExtractor):
172     IE_NAME = 'Bandcamp:album'
173     _VALID_URL = r'https?://(?:(?P<subdomain>[^.]+)\.)?bandcamp\.com(?:/album/(?P<album_id>[^/?#&]+))?'
174
175     _TESTS = [{
176         'url': 'http://blazo.bandcamp.com/album/jazz-format-mixtape-vol-1',
177         'playlist': [
178             {
179                 'md5': '39bc1eded3476e927c724321ddf116cf',
180                 'info_dict': {
181                     'id': '1353101989',
182                     'ext': 'mp3',
183                     'title': 'Intro',
184                 }
185             },
186             {
187                 'md5': '1a2c32e2691474643e912cc6cd4bffaa',
188                 'info_dict': {
189                     'id': '38097443',
190                     'ext': 'mp3',
191                     'title': 'Kero One - Keep It Alive (Blazo remix)',
192                 }
193             },
194         ],
195         'info_dict': {
196             'title': 'Jazz Format Mixtape vol.1',
197             'id': 'jazz-format-mixtape-vol-1',
198             'uploader_id': 'blazo',
199         },
200         'params': {
201             'playlistend': 2
202         },
203         'skip': 'Bandcamp imposes download limits.'
204     }, {
205         'url': 'http://nightbringer.bandcamp.com/album/hierophany-of-the-open-grave',
206         'info_dict': {
207             'title': 'Hierophany of the Open Grave',
208             'uploader_id': 'nightbringer',
209             'id': 'hierophany-of-the-open-grave',
210         },
211         'playlist_mincount': 9,
212     }, {
213         'url': 'http://dotscale.bandcamp.com',
214         'info_dict': {
215             'title': 'Loom',
216             'id': 'dotscale',
217             'uploader_id': 'dotscale',
218         },
219         'playlist_mincount': 7,
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,
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,
238     }]
239
240     @classmethod
241     def suitable(cls, url):
242         return (False
243                 if BandcampWeeklyIE.suitable(url) or BandcampIE.suitable(url)
244                 else super(BandcampAlbumIE, cls).suitable(url))
245
246     def _real_extract(self, url):
247         mobj = re.match(self._VALID_URL, url)
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)
252         track_elements = re.findall(
253             r'(?s)<div[^>]*>(.*?<a[^>]+href="([^"]+?)"[^>]+itemprop="url"[^>]*>.*?)</div>', webpage)
254         if not track_elements:
255             raise ExtractorError('The page doesn\'t contain any tracks')
256         # Only tracks with duration info have songs
257         entries = [
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))
264             for elem_content, t_path in track_elements
265             if self._html_search_meta('duration', elem_content, default=None)]
266
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'\"', '"')
272         return {
273             '_type': 'playlist',
274             'uploader_id': uploader_id,
275             'id': playlist_id,
276             'title': title,
277             'entries': entries,
278         }
279
280
281 class BandcampWeeklyIE(InfoExtractor):
282     IE_NAME = 'Bandcamp:weekly'
283     _VALID_URL = r'https?://(?:www\.)?bandcamp\.com/?\?(?:.*?&)?show=(?P<id>\d+)'
284     _TESTS = [{
285         'url': 'https://bandcamp.com/?show=224',
286         'md5': 'b00df799c733cf7e0c567ed187dea0fd',
287         'info_dict': {
288             'id': '224',
289             'ext': 'opus',
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',
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.
318         show_id = int_or_none(show.get('show_id')) or int_or_none(video_id)
319
320         formats = []
321         for format_id, format_url in show['audio_stream'].items():
322             if not url_or_none(format_url):
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)
337
338         title = show.get('audio_title') or 'Bandcamp Weekly'
339         subtitle = show.get('subtitle')
340         if subtitle:
341             title += ' - %s' % subtitle
342
343         episode_number = None
344         seq = blob.get('bcw_seq')
345
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
354
355         return {
356             'id': video_id,
357             'title': title,
358             'description': show.get('desc') or show.get('short_desc'),
359             'duration': float_or_none(show.get('audio_duration')),
360             'is_live': False,
361             'release_date': unified_strdate(show.get('published_date')),
362             'series': 'Bandcamp Weekly',
363             'episode': show.get('subtitle'),
364             'episode_number': episode_number,
365             'episode_id': compat_str(video_id),
366             'formats': formats
367         }