bandcamp.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. unified_strdate,
  19. )
  20. class BandcampIE(InfoExtractor):
  21. _VALID_URL = r'https?://.*?\.bandcamp\.com/track/(?P<title>.*)'
  22. _TESTS = [{
  23. 'url': 'http://youtube-dl.bandcamp.com/track/youtube-dl-test-song',
  24. 'md5': 'c557841d5e50261777a6585648adf439',
  25. 'info_dict': {
  26. 'id': '1812978515',
  27. 'ext': 'mp3',
  28. 'title': "youtube-dl \"'/\\\u00e4\u21ad - youtube-dl test song \"'/\\\u00e4\u21ad",
  29. 'duration': 9.8485,
  30. },
  31. '_skip': 'There is a limit of 200 free downloads / month for the test song'
  32. }, {
  33. 'url': 'http://benprunty.bandcamp.com/track/lanius-battle',
  34. 'md5': '0369ace6b939f0927e62c67a1a8d9fa7',
  35. 'info_dict': {
  36. 'id': '2650410135',
  37. 'ext': 'aiff',
  38. 'title': 'Ben Prunty - Lanius (Battle)',
  39. 'uploader': 'Ben Prunty',
  40. },
  41. }]
  42. def _real_extract(self, url):
  43. mobj = re.match(self._VALID_URL, url)
  44. title = mobj.group('title')
  45. webpage = self._download_webpage(url, title)
  46. thumbnail = self._html_search_meta('og:image', webpage, default=None)
  47. m_download = re.search(r'freeDownloadPage: "(.*?)"', webpage)
  48. if not m_download:
  49. m_trackinfo = re.search(r'trackinfo: (.+),\s*?\n', webpage)
  50. if m_trackinfo:
  51. json_code = m_trackinfo.group(1)
  52. data = json.loads(json_code)[0]
  53. track_id = compat_str(data['id'])
  54. if not data.get('file'):
  55. raise ExtractorError('Not streamable', video_id=track_id, expected=True)
  56. formats = []
  57. for format_id, format_url in data['file'].items():
  58. ext, abr_str = format_id.split('-', 1)
  59. formats.append({
  60. 'format_id': format_id,
  61. 'url': self._proto_relative_url(format_url, 'http:'),
  62. 'ext': ext,
  63. 'vcodec': 'none',
  64. 'acodec': ext,
  65. 'abr': int_or_none(abr_str),
  66. })
  67. self._sort_formats(formats)
  68. return {
  69. 'id': track_id,
  70. 'title': data['title'],
  71. 'thumbnail': thumbnail,
  72. 'formats': formats,
  73. 'duration': float_or_none(data.get('duration')),
  74. }
  75. else:
  76. raise ExtractorError('No free songs found')
  77. download_link = m_download.group(1)
  78. video_id = self._search_regex(
  79. r'(?ms)var TralbumData = .*?[{,]\s*id: (?P<id>\d+),?$',
  80. webpage, 'video id')
  81. download_webpage = self._download_webpage(
  82. download_link, video_id, 'Downloading free downloads page')
  83. blob = self._parse_json(
  84. self._search_regex(
  85. r'data-blob=(["\'])(?P<blob>{.+?})\1', download_webpage,
  86. 'blob', group='blob'),
  87. video_id, transform_source=unescapeHTML)
  88. info = blob['digital_items'][0]
  89. downloads = info['downloads']
  90. track = info['title']
  91. artist = info.get('artist')
  92. title = '%s - %s' % (artist, track) if artist else track
  93. download_formats = {}
  94. for f in blob['download_formats']:
  95. name, ext = f.get('name'), f.get('file_extension')
  96. if all(isinstance(x, compat_str) for x in (name, ext)):
  97. download_formats[name] = ext.strip('.')
  98. formats = []
  99. for format_id, f in downloads.items():
  100. format_url = f.get('url')
  101. if not format_url:
  102. continue
  103. # Stat URL generation algorithm is reverse engineered from
  104. # download_*_bundle_*.js
  105. stat_url = update_url_query(
  106. format_url.replace('/download/', '/statdownload/'), {
  107. '.rand': int(time.time() * 1000 * random.random()),
  108. })
  109. format_id = f.get('encoding_name') or format_id
  110. stat = self._download_json(
  111. stat_url, video_id, 'Downloading %s JSON' % format_id,
  112. transform_source=lambda s: s[s.index('{'):s.rindex('}') + 1],
  113. fatal=False)
  114. if not stat:
  115. continue
  116. retry_url = stat.get('retry_url')
  117. if not isinstance(retry_url, compat_str):
  118. continue
  119. formats.append({
  120. 'url': self._proto_relative_url(retry_url, 'http:'),
  121. 'ext': download_formats.get(format_id),
  122. 'format_id': format_id,
  123. 'format_note': f.get('description'),
  124. 'filesize': parse_filesize(f.get('size_mb')),
  125. 'vcodec': 'none',
  126. })
  127. self._sort_formats(formats)
  128. return {
  129. 'id': video_id,
  130. 'title': title,
  131. 'thumbnail': info.get('thumb_url') or thumbnail,
  132. 'uploader': info.get('artist'),
  133. 'artist': artist,
  134. 'track': track,
  135. 'formats': formats,
  136. }
  137. class BandcampAlbumIE(InfoExtractor):
  138. IE_NAME = 'Bandcamp:album'
  139. _VALID_URL = r'https?://(?:(?P<subdomain>[^.]+)\.)?bandcamp\.com(?:/album/(?P<album_id>[^?#]+)|/?(?:$|[?#]))'
  140. _TESTS = [{
  141. 'url': 'http://blazo.bandcamp.com/album/jazz-format-mixtape-vol-1',
  142. 'playlist': [
  143. {
  144. 'md5': '39bc1eded3476e927c724321ddf116cf',
  145. 'info_dict': {
  146. 'id': '1353101989',
  147. 'ext': 'mp3',
  148. 'title': 'Intro',
  149. }
  150. },
  151. {
  152. 'md5': '1a2c32e2691474643e912cc6cd4bffaa',
  153. 'info_dict': {
  154. 'id': '38097443',
  155. 'ext': 'mp3',
  156. 'title': 'Kero One - Keep It Alive (Blazo remix)',
  157. }
  158. },
  159. ],
  160. 'info_dict': {
  161. 'title': 'Jazz Format Mixtape vol.1',
  162. 'id': 'jazz-format-mixtape-vol-1',
  163. 'uploader_id': 'blazo',
  164. },
  165. 'params': {
  166. 'playlistend': 2
  167. },
  168. 'skip': 'Bandcamp imposes download limits.'
  169. }, {
  170. 'url': 'http://nightbringer.bandcamp.com/album/hierophany-of-the-open-grave',
  171. 'info_dict': {
  172. 'title': 'Hierophany of the Open Grave',
  173. 'uploader_id': 'nightbringer',
  174. 'id': 'hierophany-of-the-open-grave',
  175. },
  176. 'playlist_mincount': 9,
  177. }, {
  178. 'url': 'http://dotscale.bandcamp.com',
  179. 'info_dict': {
  180. 'title': 'Loom',
  181. 'id': 'dotscale',
  182. 'uploader_id': 'dotscale',
  183. },
  184. 'playlist_mincount': 7,
  185. }, {
  186. # with escaped quote in title
  187. 'url': 'https://jstrecords.bandcamp.com/album/entropy-ep',
  188. 'info_dict': {
  189. 'title': '"Entropy" EP',
  190. 'uploader_id': 'jstrecords',
  191. 'id': 'entropy-ep',
  192. },
  193. 'playlist_mincount': 3,
  194. }, {
  195. # not all tracks have songs
  196. 'url': 'https://insulters.bandcamp.com/album/we-are-the-plague',
  197. 'info_dict': {
  198. 'id': 'we-are-the-plague',
  199. 'title': 'WE ARE THE PLAGUE',
  200. 'uploader_id': 'insulters',
  201. },
  202. 'playlist_count': 2,
  203. }]
  204. @classmethod
  205. def suitable(cls, url):
  206. return False if BandcampWeeklyIE.suitable(url) else super(BandcampAlbumIE, cls).suitable(url)
  207. def _real_extract(self, url):
  208. mobj = re.match(self._VALID_URL, url)
  209. uploader_id = mobj.group('subdomain')
  210. album_id = mobj.group('album_id')
  211. playlist_id = album_id or uploader_id
  212. webpage = self._download_webpage(url, playlist_id)
  213. track_elements = re.findall(
  214. r'(?s)<div[^>]*>(.*?<a[^>]+href="([^"]+?)"[^>]+itemprop="url"[^>]*>.*?)</div>', webpage)
  215. if not track_elements:
  216. raise ExtractorError('The page doesn\'t contain any tracks')
  217. # Only tracks with duration info have songs
  218. entries = [
  219. self.url_result(compat_urlparse.urljoin(url, t_path), ie=BandcampIE.ie_key())
  220. for elem_content, t_path in track_elements
  221. if self._html_search_meta('duration', elem_content, default=None)]
  222. title = self._html_search_regex(
  223. r'album_title\s*:\s*"((?:\\.|[^"\\])+?)"',
  224. webpage, 'title', fatal=False)
  225. if title:
  226. title = title.replace(r'\"', '"')
  227. return {
  228. '_type': 'playlist',
  229. 'uploader_id': uploader_id,
  230. 'id': playlist_id,
  231. 'title': title,
  232. 'entries': entries,
  233. }
  234. class BandcampWeeklyIE(InfoExtractor):
  235. IE_NAME = 'Bandcamp:bandcamp_weekly'
  236. _VALID_URL = r'https?://(?:www\.)?bandcamp\.com/?\?(?:.*&)?show=(?P<id>\d+)(?:$|[&#])'
  237. _TESTS = [{
  238. 'url': 'https://bandcamp.com/?show=224',
  239. 'md5': 'b00df799c733cf7e0c567ed187dea0fd',
  240. 'info_dict': {
  241. 'id': '224',
  242. 'ext': 'opus',
  243. 'title': 'BC Weekly April 4th 2017: Magic Moments',
  244. 'description': 'Stones Throw\'s Vex Ruffin, plus up and coming singer Salami Rose Joe Louis, in conversation about their fantastic DIY albums.',
  245. }
  246. }, {
  247. 'url': 'https://bandcamp.com/?blah/blah@&show=228',
  248. 'only_matching': True
  249. }]
  250. def _real_extract(self, url):
  251. video_id = self._match_id(url)
  252. webpage = self._download_webpage(url, video_id)
  253. blob = self._parse_json(
  254. self._search_regex(
  255. r'data-blob=(["\'])(?P<blob>{.+?})\1', webpage,
  256. 'blob', group='blob'),
  257. video_id, transform_source=unescapeHTML)
  258. show = blob['bcw_show']
  259. # This is desired because any invalid show id redirects to `bandcamp.com`
  260. # which happens to expose the latest Bandcamp Weekly episode.
  261. video_id = compat_str(show['show_id'])
  262. def to_format_dictionaries(audio_stream):
  263. dictionaries = [{'format_id': kvp[0], 'url': kvp[1]} for kvp in audio_stream.items()]
  264. known_extensions = ['mp3', 'opus']
  265. for dictionary in dictionaries:
  266. for ext in known_extensions:
  267. if ext in dictionary['format_id']:
  268. dictionary['ext'] = ext
  269. break
  270. return dictionaries
  271. formats = to_format_dictionaries(show['audio_stream'])
  272. self._sort_formats(formats)
  273. return {
  274. 'id': video_id,
  275. 'title': show['audio_title'] + ': ' + show['subtitle'],
  276. 'description': show.get('desc'),
  277. 'duration': float_or_none(show.get('audio_duration')),
  278. 'webpage_url': 'https://bandcamp.com/?show=' + video_id,
  279. 'is_live': False,
  280. 'release_date': unified_strdate(show.get('published_date')),
  281. 'series': 'Bandcamp Weekly',
  282. 'episode_id': compat_str(video_id),
  283. 'formats': formats
  284. }