Merge remote-tracking branch 'jaimeMF/yt-playlists'
[youtube-dl] / youtube_dl / extractor / bandcamp.py
1 import json
2 import re
3
4 from .common import InfoExtractor
5 from ..utils import (
6     compat_str,
7     compat_urlparse,
8     ExtractorError,
9 )
10
11
12 class BandcampIE(InfoExtractor):
13     IE_NAME = u'Bandcamp'
14     _VALID_URL = r'http://.*?\.bandcamp\.com/track/(?P<title>.*)'
15     _TESTS = [{
16         u'url': u'http://youtube-dl.bandcamp.com/track/youtube-dl-test-song',
17         u'file': u'1812978515.mp3',
18         u'md5': u'cdeb30cdae1921719a3cbcab696ef53c',
19         u'info_dict': {
20             u"title": u"youtube-dl test song \"'/\\\u00e4\u21ad"
21         },
22         u'skip': u'There is a limit of 200 free downloads / month for the test song'
23     }, {
24         u'url': u'http://blazo.bandcamp.com/album/jazz-format-mixtape-vol-1',
25         u'playlist': [
26             {
27                 u'file': u'1353101989.mp3',
28                 u'md5': u'39bc1eded3476e927c724321ddf116cf',
29                 u'info_dict': {
30                     u'title': u'Intro',
31                 }
32             },
33             {
34                 u'file': u'38097443.mp3',
35                 u'md5': u'1a2c32e2691474643e912cc6cd4bffaa',
36                 u'info_dict': {
37                     u'title': u'Kero One - Keep It Alive (Blazo remix)',
38                 }
39             },
40         ],
41         u'params': {
42             u'playlistend': 2
43         },
44         u'skip': u'Bancamp imposes download limits. See test_playlists:test_bandcamp_album for the playlist test'
45     }]
46
47     def _real_extract(self, url):
48         mobj = re.match(self._VALID_URL, url)
49         title = mobj.group('title')
50         webpage = self._download_webpage(url, title)
51         # We get the link to the free download page
52         m_download = re.search(r'freeDownloadPage: "(.*?)"', webpage)
53         if m_download is None:
54             m_trackinfo = re.search(r'trackinfo: (.+),\s*?\n', webpage)
55         if m_trackinfo:
56             json_code = m_trackinfo.group(1)
57             data = json.loads(json_code)
58
59             entries = []
60             for d in data:
61                 formats = [{
62                     'format_id': 'format_id',
63                     'url': format_url,
64                     'ext': format_id.partition('-')[0]
65                 } for format_id, format_url in sorted(d['file'].items())]
66                 entries.append({
67                     'id': compat_str(d['id']),
68                     'title': d['title'],
69                     'formats': formats,
70                 })
71
72             return self.playlist_result(entries, title, title)
73         else:
74             raise ExtractorError(u'No free songs found')
75
76         download_link = m_download.group(1)
77         id = re.search(r'var TralbumData = {(.*?)id: (?P<id>\d*?)$', 
78                        webpage, re.MULTILINE|re.DOTALL).group('id')
79
80         download_webpage = self._download_webpage(download_link, id,
81                                                   'Downloading free downloads page')
82         # We get the dictionary of the track from some javascrip code
83         info = re.search(r'items: (.*?),$',
84                          download_webpage, re.MULTILINE).group(1)
85         info = json.loads(info)[0]
86         # We pick mp3-320 for now, until format selection can be easily implemented.
87         mp3_info = info[u'downloads'][u'mp3-320']
88         # If we try to use this url it says the link has expired
89         initial_url = mp3_info[u'url']
90         re_url = r'(?P<server>http://(.*?)\.bandcamp\.com)/download/track\?enc=mp3-320&fsig=(?P<fsig>.*?)&id=(?P<id>.*?)&ts=(?P<ts>.*)$'
91         m_url = re.match(re_url, initial_url)
92         #We build the url we will use to get the final track url
93         # This url is build in Bandcamp in the script download_bunde_*.js
94         request_url = '%s/statdownload/track?enc=mp3-320&fsig=%s&id=%s&ts=%s&.rand=665028774616&.vrs=1' % (m_url.group('server'), m_url.group('fsig'), id, m_url.group('ts'))
95         final_url_webpage = self._download_webpage(request_url, id, 'Requesting download url')
96         # If we could correctly generate the .rand field the url would be
97         #in the "download_url" key
98         final_url = re.search(r'"retry_url":"(.*?)"', final_url_webpage).group(1)
99
100         track_info = {'id':id,
101                       'title' : info[u'title'],
102                       'ext' :   'mp3',
103                       'url' :   final_url,
104                       'thumbnail' : info[u'thumb_url'],
105                       'uploader' :  info[u'artist']
106                       }
107
108         return [track_info]
109
110
111 class BandcampAlbumIE(InfoExtractor):
112     IE_NAME = u'Bandcamp:album'
113     _VALID_URL = r'http://.*?\.bandcamp\.com/album/(?P<title>.*)'
114
115     def _real_extract(self, url):
116         mobj = re.match(self._VALID_URL, url)
117         title = mobj.group('title')
118         webpage = self._download_webpage(url, title)
119         tracks_paths = re.findall(r'<a href="(.*?)" itemprop="url">', webpage)
120         if not tracks_paths:
121             raise ExtractorError(u'The page doesn\'t contain any track')
122         entries = [
123             self.url_result(compat_urlparse.urljoin(url, t_path), ie=BandcampIE.ie_key())
124             for t_path in tracks_paths]
125         title = self._search_regex(r'album_title : "(.*?)"', webpage, u'title')
126         return {
127             '_type': 'playlist',
128             'title': title,
129             'entries': entries,
130         }