You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

237 lines
8.1 KiB

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