bandcamp.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import random
  4. import re
  5. import time
  6. from .common import InfoExtractor
  7. from ..compat import compat_str
  8. from ..utils import (
  9. ExtractorError,
  10. float_or_none,
  11. int_or_none,
  12. KNOWN_EXTENSIONS,
  13. parse_filesize,
  14. str_or_none,
  15. try_get,
  16. update_url_query,
  17. unified_strdate,
  18. unified_timestamp,
  19. url_or_none,
  20. urljoin,
  21. )
  22. class BandcampIE(InfoExtractor):
  23. _VALID_URL = r'https?://[^/]+\.bandcamp\.com/track/(?P<id>[^/?#&]+)'
  24. _TESTS = [{
  25. 'url': 'http://youtube-dl.bandcamp.com/track/youtube-dl-test-song',
  26. 'md5': 'c557841d5e50261777a6585648adf439',
  27. 'info_dict': {
  28. 'id': '1812978515',
  29. 'ext': 'mp3',
  30. 'title': "youtube-dl \"'/\\ä↭ - youtube-dl \"'/\\ä↭ - youtube-dl test song \"'/\\ä↭",
  31. 'duration': 9.8485,
  32. 'uploader': 'youtube-dl "\'/\\ä↭',
  33. 'upload_date': '20121129',
  34. 'timestamp': 1354224127,
  35. },
  36. '_skip': 'There is a limit of 200 free downloads / month for the test song'
  37. }, {
  38. # free download
  39. 'url': 'http://benprunty.bandcamp.com/track/lanius-battle',
  40. 'info_dict': {
  41. 'id': '2650410135',
  42. 'ext': 'aiff',
  43. 'title': 'Ben Prunty - Lanius (Battle)',
  44. 'thumbnail': r're:^https?://.*\.jpg$',
  45. 'uploader': 'Ben Prunty',
  46. 'timestamp': 1396508491,
  47. 'upload_date': '20140403',
  48. 'release_date': '20140403',
  49. 'duration': 260.877,
  50. 'track': 'Lanius (Battle)',
  51. 'track_number': 1,
  52. 'track_id': '2650410135',
  53. 'artist': 'Ben Prunty',
  54. 'album': 'FTL: Advanced Edition Soundtrack',
  55. },
  56. }, {
  57. # no free download, mp3 128
  58. 'url': 'https://relapsealumni.bandcamp.com/track/hail-to-fire',
  59. 'md5': 'fec12ff55e804bb7f7ebeb77a800c8b7',
  60. 'info_dict': {
  61. 'id': '2584466013',
  62. 'ext': 'mp3',
  63. 'title': 'Mastodon - Hail to Fire',
  64. 'thumbnail': r're:^https?://.*\.jpg$',
  65. 'uploader': 'Mastodon',
  66. 'timestamp': 1322005399,
  67. 'upload_date': '20111122',
  68. 'release_date': '20040207',
  69. 'duration': 120.79,
  70. 'track': 'Hail to Fire',
  71. 'track_number': 5,
  72. 'track_id': '2584466013',
  73. 'artist': 'Mastodon',
  74. 'album': 'Call of the Mastodon',
  75. },
  76. }]
  77. def _extract_data_attr(self, webpage, video_id, attr='tralbum', fatal=True):
  78. return self._parse_json(self._html_search_regex(
  79. r'data-%s=(["\'])({.+?})\1' % attr, webpage,
  80. attr + ' data', group=2), video_id, fatal=fatal)
  81. def _real_extract(self, url):
  82. title = self._match_id(url)
  83. webpage = self._download_webpage(url, title)
  84. tralbum = self._extract_data_attr(webpage, title)
  85. thumbnail = self._og_search_thumbnail(webpage)
  86. track_id = None
  87. track = None
  88. track_number = None
  89. duration = None
  90. formats = []
  91. track_info = try_get(tralbum, lambda x: x['trackinfo'][0], dict)
  92. if track_info:
  93. file_ = track_info.get('file')
  94. if isinstance(file_, dict):
  95. for format_id, format_url in file_.items():
  96. if not url_or_none(format_url):
  97. continue
  98. ext, abr_str = format_id.split('-', 1)
  99. formats.append({
  100. 'format_id': format_id,
  101. 'url': self._proto_relative_url(format_url, 'http:'),
  102. 'ext': ext,
  103. 'vcodec': 'none',
  104. 'acodec': ext,
  105. 'abr': int_or_none(abr_str),
  106. })
  107. track = track_info.get('title')
  108. track_id = str_or_none(
  109. track_info.get('track_id') or track_info.get('id'))
  110. track_number = int_or_none(track_info.get('track_num'))
  111. duration = float_or_none(track_info.get('duration'))
  112. embed = self._extract_data_attr(webpage, title, 'embed', False)
  113. current = tralbum.get('current') or {}
  114. artist = embed.get('artist') or current.get('artist') or tralbum.get('artist')
  115. timestamp = unified_timestamp(
  116. current.get('publish_date') or tralbum.get('album_publish_date'))
  117. download_link = tralbum.get('freeDownloadPage')
  118. if download_link:
  119. track_id = compat_str(tralbum['id'])
  120. download_webpage = self._download_webpage(
  121. download_link, track_id, 'Downloading free downloads page')
  122. blob = self._extract_data_attr(download_webpage, track_id, 'blob')
  123. info = try_get(
  124. blob, (lambda x: x['digital_items'][0],
  125. lambda x: x['download_items'][0]), dict)
  126. if info:
  127. downloads = info.get('downloads')
  128. if isinstance(downloads, dict):
  129. if not track:
  130. track = info.get('title')
  131. if not artist:
  132. artist = info.get('artist')
  133. if not thumbnail:
  134. thumbnail = info.get('thumb_url')
  135. download_formats = {}
  136. download_formats_list = blob.get('download_formats')
  137. if isinstance(download_formats_list, list):
  138. for f in blob['download_formats']:
  139. name, ext = f.get('name'), f.get('file_extension')
  140. if all(isinstance(x, compat_str) for x in (name, ext)):
  141. download_formats[name] = ext.strip('.')
  142. for format_id, f in downloads.items():
  143. format_url = f.get('url')
  144. if not format_url:
  145. continue
  146. # Stat URL generation algorithm is reverse engineered from
  147. # download_*_bundle_*.js
  148. stat_url = update_url_query(
  149. format_url.replace('/download/', '/statdownload/'), {
  150. '.rand': int(time.time() * 1000 * random.random()),
  151. })
  152. format_id = f.get('encoding_name') or format_id
  153. stat = self._download_json(
  154. stat_url, track_id, 'Downloading %s JSON' % format_id,
  155. transform_source=lambda s: s[s.index('{'):s.rindex('}') + 1],
  156. fatal=False)
  157. if not stat:
  158. continue
  159. retry_url = url_or_none(stat.get('retry_url'))
  160. if not retry_url:
  161. continue
  162. formats.append({
  163. 'url': self._proto_relative_url(retry_url, 'http:'),
  164. 'ext': download_formats.get(format_id),
  165. 'format_id': format_id,
  166. 'format_note': f.get('description'),
  167. 'filesize': parse_filesize(f.get('size_mb')),
  168. 'vcodec': 'none',
  169. })
  170. self._sort_formats(formats)
  171. title = '%s - %s' % (artist, track) if artist else track
  172. if not duration:
  173. duration = float_or_none(self._html_search_meta(
  174. 'duration', webpage, default=None))
  175. return {
  176. 'id': track_id,
  177. 'title': title,
  178. 'thumbnail': thumbnail,
  179. 'uploader': artist,
  180. 'timestamp': timestamp,
  181. 'release_date': unified_strdate(tralbum.get('album_release_date')),
  182. 'duration': duration,
  183. 'track': track,
  184. 'track_number': track_number,
  185. 'track_id': track_id,
  186. 'artist': artist,
  187. 'album': embed.get('album_title'),
  188. 'formats': formats,
  189. }
  190. class BandcampAlbumIE(BandcampIE):
  191. IE_NAME = 'Bandcamp:album'
  192. _VALID_URL = r'https?://(?:(?P<subdomain>[^.]+)\.)?bandcamp\.com(?:/album/(?P<id>[^/?#&]+))?'
  193. _TESTS = [{
  194. 'url': 'http://blazo.bandcamp.com/album/jazz-format-mixtape-vol-1',
  195. 'playlist': [
  196. {
  197. 'md5': '39bc1eded3476e927c724321ddf116cf',
  198. 'info_dict': {
  199. 'id': '1353101989',
  200. 'ext': 'mp3',
  201. 'title': 'Blazo - Intro',
  202. 'timestamp': 1311756226,
  203. 'upload_date': '20110727',
  204. 'uploader': 'Blazo',
  205. }
  206. },
  207. {
  208. 'md5': '1a2c32e2691474643e912cc6cd4bffaa',
  209. 'info_dict': {
  210. 'id': '38097443',
  211. 'ext': 'mp3',
  212. 'title': 'Blazo - Kero One - Keep It Alive (Blazo remix)',
  213. 'timestamp': 1311757238,
  214. 'upload_date': '20110727',
  215. 'uploader': 'Blazo',
  216. }
  217. },
  218. ],
  219. 'info_dict': {
  220. 'title': 'Jazz Format Mixtape vol.1',
  221. 'id': 'jazz-format-mixtape-vol-1',
  222. 'uploader_id': 'blazo',
  223. },
  224. 'params': {
  225. 'playlistend': 2
  226. },
  227. 'skip': 'Bandcamp imposes download limits.'
  228. }, {
  229. 'url': 'http://nightbringer.bandcamp.com/album/hierophany-of-the-open-grave',
  230. 'info_dict': {
  231. 'title': 'Hierophany of the Open Grave',
  232. 'uploader_id': 'nightbringer',
  233. 'id': 'hierophany-of-the-open-grave',
  234. },
  235. 'playlist_mincount': 9,
  236. }, {
  237. 'url': 'http://dotscale.bandcamp.com',
  238. 'info_dict': {
  239. 'title': 'Loom',
  240. 'id': 'dotscale',
  241. 'uploader_id': 'dotscale',
  242. },
  243. 'playlist_mincount': 7,
  244. }, {
  245. # with escaped quote in title
  246. 'url': 'https://jstrecords.bandcamp.com/album/entropy-ep',
  247. 'info_dict': {
  248. 'title': '"Entropy" EP',
  249. 'uploader_id': 'jstrecords',
  250. 'id': 'entropy-ep',
  251. 'description': 'md5:0ff22959c943622972596062f2f366a5',
  252. },
  253. 'playlist_mincount': 3,
  254. }, {
  255. # not all tracks have songs
  256. 'url': 'https://insulters.bandcamp.com/album/we-are-the-plague',
  257. 'info_dict': {
  258. 'id': 'we-are-the-plague',
  259. 'title': 'WE ARE THE PLAGUE',
  260. 'uploader_id': 'insulters',
  261. 'description': 'md5:b3cf845ee41b2b1141dc7bde9237255f',
  262. },
  263. 'playlist_count': 2,
  264. }]
  265. @classmethod
  266. def suitable(cls, url):
  267. return (False
  268. if BandcampWeeklyIE.suitable(url) or BandcampIE.suitable(url)
  269. else super(BandcampAlbumIE, cls).suitable(url))
  270. def _real_extract(self, url):
  271. uploader_id, album_id = re.match(self._VALID_URL, url).groups()
  272. playlist_id = album_id or uploader_id
  273. webpage = self._download_webpage(url, playlist_id)
  274. tralbum = self._extract_data_attr(webpage, playlist_id)
  275. track_info = tralbum.get('trackinfo')
  276. if not track_info:
  277. raise ExtractorError('The page doesn\'t contain any tracks')
  278. # Only tracks with duration info have songs
  279. entries = [
  280. self.url_result(
  281. urljoin(url, t['title_link']), BandcampIE.ie_key(),
  282. str_or_none(t.get('track_id') or t.get('id')), t.get('title'))
  283. for t in track_info
  284. if t.get('duration')]
  285. current = tralbum.get('current') or {}
  286. return {
  287. '_type': 'playlist',
  288. 'uploader_id': uploader_id,
  289. 'id': playlist_id,
  290. 'title': current.get('title'),
  291. 'description': current.get('about'),
  292. 'entries': entries,
  293. }
  294. class BandcampWeeklyIE(BandcampIE):
  295. IE_NAME = 'Bandcamp:weekly'
  296. _VALID_URL = r'https?://(?:www\.)?bandcamp\.com/?\?(?:.*?&)?show=(?P<id>\d+)'
  297. _TESTS = [{
  298. 'url': 'https://bandcamp.com/?show=224',
  299. 'md5': 'b00df799c733cf7e0c567ed187dea0fd',
  300. 'info_dict': {
  301. 'id': '224',
  302. 'ext': 'opus',
  303. 'title': 'BC Weekly April 4th 2017 - Magic Moments',
  304. 'description': 'md5:5d48150916e8e02d030623a48512c874',
  305. 'duration': 5829.77,
  306. 'release_date': '20170404',
  307. 'series': 'Bandcamp Weekly',
  308. 'episode': 'Magic Moments',
  309. 'episode_id': '224',
  310. },
  311. 'params': {
  312. 'format': 'opus-lo',
  313. },
  314. }, {
  315. 'url': 'https://bandcamp.com/?blah/blah@&show=228',
  316. 'only_matching': True
  317. }]
  318. def _real_extract(self, url):
  319. show_id = self._match_id(url)
  320. webpage = self._download_webpage(url, show_id)
  321. blob = self._extract_data_attr(webpage, show_id, 'blob')
  322. show = blob['bcw_data'][show_id]
  323. formats = []
  324. for format_id, format_url in show['audio_stream'].items():
  325. if not url_or_none(format_url):
  326. continue
  327. for known_ext in KNOWN_EXTENSIONS:
  328. if known_ext in format_id:
  329. ext = known_ext
  330. break
  331. else:
  332. ext = None
  333. formats.append({
  334. 'format_id': format_id,
  335. 'url': format_url,
  336. 'ext': ext,
  337. 'vcodec': 'none',
  338. })
  339. self._sort_formats(formats)
  340. title = show.get('audio_title') or 'Bandcamp Weekly'
  341. subtitle = show.get('subtitle')
  342. if subtitle:
  343. title += ' - %s' % subtitle
  344. return {
  345. 'id': show_id,
  346. 'title': title,
  347. 'description': show.get('desc') or show.get('short_desc'),
  348. 'duration': float_or_none(show.get('audio_duration')),
  349. 'is_live': False,
  350. 'release_date': unified_strdate(show.get('published_date')),
  351. 'series': 'Bandcamp Weekly',
  352. 'episode': show.get('subtitle'),
  353. 'episode_id': show_id,
  354. 'formats': formats
  355. }