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