bandcamp.py 8.7 KB

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