Merge pull request #12861 from Tithen-Firion/cbsinteractive-fix
[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     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': '0369ace6b939f0927e62c67a1a8d9fa7',
38         'info_dict': {
39             'id': '2650410135',
40             'ext': 'aiff',
41             'title': 'Ben Prunty - Lanius (Battle)',
42             'uploader': 'Ben Prunty',
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         thumbnail = self._html_search_meta('og:image', webpage, default=None)
51         m_download = re.search(r'freeDownloadPage: "(.*?)"', webpage)
52         if not m_download:
53             m_trackinfo = re.search(r'trackinfo: (.+),\s*?\n', webpage)
54             if m_trackinfo:
55                 json_code = m_trackinfo.group(1)
56                 data = json.loads(json_code)[0]
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)
61
62                 formats = []
63                 for format_id, format_url in data['file'].items():
64                     ext, abr_str = format_id.split('-', 1)
65                     formats.append({
66                         'format_id': format_id,
67                         'url': self._proto_relative_url(format_url, 'http:'),
68                         'ext': ext,
69                         'vcodec': 'none',
70                         'acodec': ext,
71                         'abr': int_or_none(abr_str),
72                     })
73
74                 self._sort_formats(formats)
75
76                 return {
77                     'id': track_id,
78                     'title': data['title'],
79                     'thumbnail': thumbnail,
80                     'formats': formats,
81                     'duration': float_or_none(data.get('duration')),
82                 }
83             else:
84                 raise ExtractorError('No free songs found')
85
86         download_link = m_download.group(1)
87         video_id = self._search_regex(
88             r'(?ms)var TralbumData = .*?[{,]\s*id: (?P<id>\d+),?$',
89             webpage, 'video id')
90
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)
144
145         return {
146             'id': video_id,
147             'title': title,
148             'thumbnail': info.get('thumb_url') or thumbnail,
149             'uploader': info.get('artist'),
150             'artist': artist,
151             'track': track,
152             'formats': formats,
153         }
154
155
156 class BandcampAlbumIE(InfoExtractor):
157     IE_NAME = 'Bandcamp:album'
158     _VALID_URL = r'https?://(?:(?P<subdomain>[^.]+)\.)?bandcamp\.com(?:/album/(?P<album_id>[^?#]+)|/?(?:$|[?#]))'
159
160     _TESTS = [{
161         'url': 'http://blazo.bandcamp.com/album/jazz-format-mixtape-vol-1',
162         'playlist': [
163             {
164                 'md5': '39bc1eded3476e927c724321ddf116cf',
165                 'info_dict': {
166                     'id': '1353101989',
167                     'ext': 'mp3',
168                     'title': 'Intro',
169                 }
170             },
171             {
172                 'md5': '1a2c32e2691474643e912cc6cd4bffaa',
173                 'info_dict': {
174                     'id': '38097443',
175                     'ext': 'mp3',
176                     'title': 'Kero One - Keep It Alive (Blazo remix)',
177                 }
178             },
179         ],
180         'info_dict': {
181             'title': 'Jazz Format Mixtape vol.1',
182             'id': 'jazz-format-mixtape-vol-1',
183             'uploader_id': 'blazo',
184         },
185         'params': {
186             'playlistend': 2
187         },
188         'skip': 'Bandcamp imposes download limits.'
189     }, {
190         'url': 'http://nightbringer.bandcamp.com/album/hierophany-of-the-open-grave',
191         'info_dict': {
192             'title': 'Hierophany of the Open Grave',
193             'uploader_id': 'nightbringer',
194             'id': 'hierophany-of-the-open-grave',
195         },
196         'playlist_mincount': 9,
197     }, {
198         'url': 'http://dotscale.bandcamp.com',
199         'info_dict': {
200             'title': 'Loom',
201             'id': 'dotscale',
202             'uploader_id': 'dotscale',
203         },
204         'playlist_mincount': 7,
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,
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,
223     }]
224
225     def _real_extract(self, url):
226         mobj = re.match(self._VALID_URL, url)
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)
231         track_elements = re.findall(
232             r'(?s)<div[^>]*>(.*?<a[^>]+href="([^"]+?)"[^>]+itemprop="url"[^>]*>.*?)</div>', webpage)
233         if not track_elements:
234             raise ExtractorError('The page doesn\'t contain any tracks')
235         # Only tracks with duration info have songs
236         entries = [
237             self.url_result(compat_urlparse.urljoin(url, t_path), ie=BandcampIE.ie_key())
238             for elem_content, t_path in track_elements
239             if self._html_search_meta('duration', elem_content, default=None)]
240
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'\"', '"')
246         return {
247             '_type': 'playlist',
248             'uploader_id': uploader_id,
249             'id': playlist_id,
250             'title': title,
251             'entries': entries,
252         }