bandcamp.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. import random
  2. import re
  3. import time
  4. from .common import InfoExtractor
  5. from ..utils import (
  6. KNOWN_EXTENSIONS,
  7. ExtractorError,
  8. float_or_none,
  9. int_or_none,
  10. parse_filesize,
  11. str_or_none,
  12. try_get,
  13. unified_strdate,
  14. unified_timestamp,
  15. update_url_query,
  16. url_or_none,
  17. urljoin,
  18. )
  19. class BandcampIE(InfoExtractor):
  20. _VALID_URL = r'https?://(?P<uploader>[^/]+)\.bandcamp\.com/track/(?P<id>[^/?#&]+)'
  21. _EMBED_REGEX = [r'<meta property="og:url"[^>]*?content="(?P<url>.*?bandcamp\.com.*?)"']
  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 "\'/\\ä↭ - youtube-dl "\'/\\ä↭ - youtube-dl test song "\'/\\ä↭',
  29. 'duration': 9.8485,
  30. 'uploader': 'youtube-dl "\'/\\ä↭',
  31. 'upload_date': '20121129',
  32. 'timestamp': 1354224127,
  33. 'track': 'youtube-dl "\'/\\ä↭ - youtube-dl test song "\'/\\ä↭',
  34. 'album_artist': 'youtube-dl "\'/\\ä↭',
  35. 'track_id': '1812978515',
  36. 'artist': 'youtube-dl "\'/\\ä↭',
  37. 'uploader_url': 'https://youtube-dl.bandcamp.com',
  38. 'uploader_id': 'youtube-dl',
  39. 'thumbnail': 'https://f4.bcbits.com/img/a3216802731_5.jpg',
  40. },
  41. 'skip': 'There is a limit of 200 free downloads / month for the test song',
  42. }, {
  43. # free download
  44. 'url': 'http://benprunty.bandcamp.com/track/lanius-battle',
  45. 'info_dict': {
  46. 'id': '2650410135',
  47. 'ext': 'm4a',
  48. 'acodec': r're:[fa]lac',
  49. 'title': 'Ben Prunty - Lanius (Battle)',
  50. 'thumbnail': r're:^https?://.*\.jpg$',
  51. 'uploader': 'Ben Prunty',
  52. 'timestamp': 1396508491,
  53. 'upload_date': '20140403',
  54. 'release_timestamp': 1396483200,
  55. 'release_date': '20140403',
  56. 'duration': 260.877,
  57. 'track': 'Lanius (Battle)',
  58. 'track_number': 1,
  59. 'track_id': '2650410135',
  60. 'artist': 'Ben Prunty',
  61. 'album_artist': 'Ben Prunty',
  62. 'album': 'FTL: Advanced Edition Soundtrack',
  63. 'uploader_url': 'https://benprunty.bandcamp.com',
  64. 'uploader_id': 'benprunty',
  65. },
  66. }, {
  67. # no free download, mp3 128
  68. 'url': 'https://relapsealumni.bandcamp.com/track/hail-to-fire',
  69. 'md5': 'fec12ff55e804bb7f7ebeb77a800c8b7',
  70. 'info_dict': {
  71. 'id': '2584466013',
  72. 'ext': 'mp3',
  73. 'title': 'Mastodon - Hail to Fire',
  74. 'thumbnail': r're:^https?://.*\.jpg$',
  75. 'uploader': 'Mastodon',
  76. 'timestamp': 1322005399,
  77. 'upload_date': '20111122',
  78. 'release_timestamp': 1076112000,
  79. 'release_date': '20040207',
  80. 'duration': 120.79,
  81. 'track': 'Hail to Fire',
  82. 'track_number': 5,
  83. 'track_id': '2584466013',
  84. 'artist': 'Mastodon',
  85. 'album_artist': 'Mastodon',
  86. 'album': 'Call of the Mastodon',
  87. 'uploader_url': 'https://relapsealumni.bandcamp.com',
  88. 'uploader_id': 'relapsealumni',
  89. },
  90. }, {
  91. # track from compilation album (artist/album_artist difference)
  92. 'url': 'https://diskotopia.bandcamp.com/track/safehouse',
  93. 'md5': '19c5337bca1428afa54129f86a2f6a69',
  94. 'info_dict': {
  95. 'id': '1978174799',
  96. 'ext': 'mp3',
  97. 'title': 'submerse - submerse - Safehouse',
  98. 'thumbnail': r're:^https?://.*\.jpg$',
  99. 'uploader': 'submerse',
  100. 'timestamp': 1480779297,
  101. 'upload_date': '20161203',
  102. 'release_timestamp': 1481068800,
  103. 'release_date': '20161207',
  104. 'duration': 154.066,
  105. 'track': 'submerse - Safehouse',
  106. 'track_number': 3,
  107. 'track_id': '1978174799',
  108. 'artist': 'submerse',
  109. 'album_artist': 'Diskotopia',
  110. 'album': 'DSK F/W 2016-2017 Free Compilation',
  111. 'uploader_url': 'https://diskotopia.bandcamp.com',
  112. 'uploader_id': 'diskotopia',
  113. },
  114. }]
  115. def _extract_data_attr(self, webpage, video_id, attr='tralbum', fatal=True):
  116. return self._parse_json(self._html_search_regex(
  117. rf'data-{attr}=(["\'])({{.+?}})\1', webpage,
  118. attr + ' data', group=2), video_id, fatal=fatal)
  119. def _real_extract(self, url):
  120. title, uploader = self._match_valid_url(url).group('id', 'uploader')
  121. webpage = self._download_webpage(url, title)
  122. tralbum = self._extract_data_attr(webpage, title)
  123. thumbnail = self._og_search_thumbnail(webpage)
  124. track_id = None
  125. track = None
  126. track_number = None
  127. duration = None
  128. formats = []
  129. track_info = try_get(tralbum, lambda x: x['trackinfo'][0], dict)
  130. if track_info:
  131. file_ = track_info.get('file')
  132. if isinstance(file_, dict):
  133. for format_id, format_url in file_.items():
  134. if not url_or_none(format_url):
  135. continue
  136. ext, abr_str = format_id.split('-', 1)
  137. formats.append({
  138. 'format_id': format_id,
  139. 'url': self._proto_relative_url(format_url, 'http:'),
  140. 'ext': ext,
  141. 'vcodec': 'none',
  142. 'acodec': ext,
  143. 'abr': int_or_none(abr_str),
  144. })
  145. track = track_info.get('title')
  146. track_id = str_or_none(
  147. track_info.get('track_id') or track_info.get('id'))
  148. track_number = int_or_none(track_info.get('track_num'))
  149. duration = float_or_none(track_info.get('duration'))
  150. embed = self._extract_data_attr(webpage, title, 'embed', False)
  151. current = tralbum.get('current') or {}
  152. artist = embed.get('artist') or current.get('artist') or tralbum.get('artist')
  153. album_artist = self._html_search_regex(
  154. r'<h3 class="albumTitle">[\S\s]*?by\s*<span>\s*<a href="[^>]+">\s*([^>]+?)\s*</a>',
  155. webpage, 'album artist', fatal=False)
  156. timestamp = unified_timestamp(
  157. current.get('publish_date') or tralbum.get('album_publish_date'))
  158. download_link = tralbum.get('freeDownloadPage')
  159. if download_link:
  160. track_id = str(tralbum['id'])
  161. download_webpage = self._download_webpage(
  162. download_link, track_id, 'Downloading free downloads page')
  163. blob = self._extract_data_attr(download_webpage, track_id, 'blob')
  164. info = try_get(
  165. blob, (lambda x: x['digital_items'][0],
  166. lambda x: x['download_items'][0]), dict)
  167. if info:
  168. downloads = info.get('downloads')
  169. if isinstance(downloads, dict):
  170. if not track:
  171. track = info.get('title')
  172. if not artist:
  173. artist = info.get('artist')
  174. if not thumbnail:
  175. thumbnail = info.get('thumb_url')
  176. download_formats = {}
  177. download_formats_list = blob.get('download_formats')
  178. if isinstance(download_formats_list, list):
  179. for f in blob['download_formats']:
  180. name, ext = f.get('name'), f.get('file_extension')
  181. if all(isinstance(x, str) for x in (name, ext)):
  182. download_formats[name] = ext.strip('.')
  183. for format_id, f in downloads.items():
  184. format_url = f.get('url')
  185. if not format_url:
  186. continue
  187. # Stat URL generation algorithm is reverse engineered from
  188. # download_*_bundle_*.js
  189. stat_url = update_url_query(
  190. format_url.replace('/download/', '/statdownload/'), {
  191. '.rand': int(time.time() * 1000 * random.random()),
  192. })
  193. format_id = f.get('encoding_name') or format_id
  194. stat = self._download_json(
  195. stat_url, track_id, f'Downloading {format_id} JSON',
  196. transform_source=lambda s: s[s.index('{'):s.rindex('}') + 1],
  197. fatal=False)
  198. if not stat:
  199. continue
  200. retry_url = url_or_none(stat.get('retry_url'))
  201. if not retry_url:
  202. continue
  203. formats.append({
  204. 'url': self._proto_relative_url(retry_url, 'http:'),
  205. 'ext': download_formats.get(format_id),
  206. 'format_id': format_id,
  207. 'format_note': f.get('description'),
  208. 'filesize': parse_filesize(f.get('size_mb')),
  209. 'vcodec': 'none',
  210. 'acodec': format_id.split('-')[0],
  211. })
  212. title = f'{artist} - {track}' if artist else track
  213. if not duration:
  214. duration = float_or_none(self._html_search_meta(
  215. 'duration', webpage, default=None))
  216. return {
  217. 'id': track_id,
  218. 'title': title,
  219. 'thumbnail': thumbnail,
  220. 'uploader': artist,
  221. 'uploader_id': uploader,
  222. 'uploader_url': f'https://{uploader}.bandcamp.com',
  223. 'timestamp': timestamp,
  224. 'release_timestamp': unified_timestamp(tralbum.get('album_release_date')),
  225. 'duration': duration,
  226. 'track': track,
  227. 'track_number': track_number,
  228. 'track_id': track_id,
  229. 'artist': artist,
  230. 'album': embed.get('album_title'),
  231. 'album_artist': album_artist,
  232. 'formats': formats,
  233. }
  234. class BandcampAlbumIE(BandcampIE): # XXX: Do not subclass from concrete IE
  235. IE_NAME = 'Bandcamp:album'
  236. _VALID_URL = r'https?://(?:(?P<subdomain>[^.]+)\.)?bandcamp\.com/album/(?P<id>[^/?#&]+)'
  237. _TESTS = [{
  238. 'url': 'http://blazo.bandcamp.com/album/jazz-format-mixtape-vol-1',
  239. 'playlist': [
  240. {
  241. 'md5': '39bc1eded3476e927c724321ddf116cf',
  242. 'info_dict': {
  243. 'id': '1353101989',
  244. 'ext': 'mp3',
  245. 'title': 'Blazo - Intro',
  246. 'timestamp': 1311756226,
  247. 'upload_date': '20110727',
  248. 'uploader': 'Blazo',
  249. },
  250. },
  251. {
  252. 'md5': '1a2c32e2691474643e912cc6cd4bffaa',
  253. 'info_dict': {
  254. 'id': '38097443',
  255. 'ext': 'mp3',
  256. 'title': 'Blazo - Kero One - Keep It Alive (Blazo remix)',
  257. 'timestamp': 1311757238,
  258. 'upload_date': '20110727',
  259. 'uploader': 'Blazo',
  260. },
  261. },
  262. ],
  263. 'info_dict': {
  264. 'title': 'Jazz Format Mixtape vol.1',
  265. 'id': 'jazz-format-mixtape-vol-1',
  266. 'uploader_id': 'blazo',
  267. },
  268. 'params': {
  269. 'playlistend': 2,
  270. },
  271. 'skip': 'Bandcamp imposes download limits.',
  272. }, {
  273. 'url': 'http://nightbringer.bandcamp.com/album/hierophany-of-the-open-grave',
  274. 'info_dict': {
  275. 'title': 'Hierophany of the Open Grave',
  276. 'uploader_id': 'nightbringer',
  277. 'id': 'hierophany-of-the-open-grave',
  278. },
  279. 'playlist_mincount': 9,
  280. }, {
  281. # with escaped quote in title
  282. 'url': 'https://jstrecords.bandcamp.com/album/entropy-ep',
  283. 'info_dict': {
  284. 'title': '"Entropy" EP',
  285. 'uploader_id': 'jstrecords',
  286. 'id': 'entropy-ep',
  287. 'description': 'md5:0ff22959c943622972596062f2f366a5',
  288. },
  289. 'playlist_mincount': 3,
  290. }, {
  291. # not all tracks have songs
  292. 'url': 'https://insulters.bandcamp.com/album/we-are-the-plague',
  293. 'info_dict': {
  294. 'id': 'we-are-the-plague',
  295. 'title': 'WE ARE THE PLAGUE',
  296. 'uploader_id': 'insulters',
  297. 'description': 'md5:b3cf845ee41b2b1141dc7bde9237255f',
  298. },
  299. 'playlist_count': 2,
  300. }]
  301. @classmethod
  302. def suitable(cls, url):
  303. return (False
  304. if BandcampWeeklyIE.suitable(url) or BandcampIE.suitable(url)
  305. else super().suitable(url))
  306. def _real_extract(self, url):
  307. uploader_id, album_id = self._match_valid_url(url).groups()
  308. playlist_id = album_id or uploader_id
  309. webpage = self._download_webpage(url, playlist_id)
  310. tralbum = self._extract_data_attr(webpage, playlist_id)
  311. track_info = tralbum.get('trackinfo')
  312. if not track_info:
  313. raise ExtractorError('The page doesn\'t contain any tracks')
  314. # Only tracks with duration info have songs
  315. entries = [
  316. self.url_result(
  317. urljoin(url, t['title_link']), BandcampIE.ie_key(),
  318. str_or_none(t.get('track_id') or t.get('id')), t.get('title'))
  319. for t in track_info
  320. if t.get('duration')]
  321. current = tralbum.get('current') or {}
  322. return {
  323. '_type': 'playlist',
  324. 'uploader_id': uploader_id,
  325. 'id': playlist_id,
  326. 'title': current.get('title'),
  327. 'description': current.get('about'),
  328. 'entries': entries,
  329. }
  330. class BandcampWeeklyIE(BandcampIE): # XXX: Do not subclass from concrete IE
  331. IE_NAME = 'Bandcamp:weekly'
  332. _VALID_URL = r'https?://(?:www\.)?bandcamp\.com/?\?(?:.*?&)?show=(?P<id>\d+)'
  333. _TESTS = [{
  334. 'url': 'https://bandcamp.com/?show=224',
  335. 'md5': 'b00df799c733cf7e0c567ed187dea0fd',
  336. 'info_dict': {
  337. 'id': '224',
  338. 'ext': 'opus',
  339. 'title': 'BC Weekly April 4th 2017 - Magic Moments',
  340. 'description': 'md5:5d48150916e8e02d030623a48512c874',
  341. 'duration': 5829.77,
  342. 'release_date': '20170404',
  343. 'series': 'Bandcamp Weekly',
  344. 'episode': 'Magic Moments',
  345. 'episode_id': '224',
  346. },
  347. 'params': {
  348. 'format': 'opus-lo',
  349. },
  350. }, {
  351. 'url': 'https://bandcamp.com/?blah/blah@&show=228',
  352. 'only_matching': True,
  353. }]
  354. def _real_extract(self, url):
  355. show_id = self._match_id(url)
  356. webpage = self._download_webpage(url, show_id)
  357. blob = self._extract_data_attr(webpage, show_id, 'blob')
  358. show = blob['bcw_data'][show_id]
  359. formats = []
  360. for format_id, format_url in show['audio_stream'].items():
  361. if not url_or_none(format_url):
  362. continue
  363. for known_ext in KNOWN_EXTENSIONS:
  364. if known_ext in format_id:
  365. ext = known_ext
  366. break
  367. else:
  368. ext = None
  369. formats.append({
  370. 'format_id': format_id,
  371. 'url': format_url,
  372. 'ext': ext,
  373. 'vcodec': 'none',
  374. })
  375. title = show.get('audio_title') or 'Bandcamp Weekly'
  376. subtitle = show.get('subtitle')
  377. if subtitle:
  378. title += f' - {subtitle}'
  379. return {
  380. 'id': show_id,
  381. 'title': title,
  382. 'description': show.get('desc') or show.get('short_desc'),
  383. 'duration': float_or_none(show.get('audio_duration')),
  384. 'is_live': False,
  385. 'release_date': unified_strdate(show.get('published_date')),
  386. 'series': 'Bandcamp Weekly',
  387. 'episode': show.get('subtitle'),
  388. 'episode_id': show_id,
  389. 'formats': formats,
  390. }
  391. class BandcampUserIE(InfoExtractor):
  392. IE_NAME = 'Bandcamp:user'
  393. _VALID_URL = r'https?://(?!www\.)(?P<id>[^.]+)\.bandcamp\.com(?:/music)?/?(?:[#?]|$)'
  394. _TESTS = [{
  395. # Type 1 Bandcamp user page.
  396. 'url': 'https://adrianvonziegler.bandcamp.com',
  397. 'info_dict': {
  398. 'id': 'adrianvonziegler',
  399. 'title': 'Discography of adrianvonziegler',
  400. },
  401. 'playlist_mincount': 23,
  402. }, {
  403. # Bandcamp user page with only one album
  404. 'url': 'http://dotscale.bandcamp.com',
  405. 'info_dict': {
  406. 'id': 'dotscale',
  407. 'title': 'Discography of dotscale',
  408. },
  409. 'playlist_count': 1,
  410. }, {
  411. # Type 2 Bandcamp user page.
  412. 'url': 'https://nightcallofficial.bandcamp.com',
  413. 'info_dict': {
  414. 'id': 'nightcallofficial',
  415. 'title': 'Discography of nightcallofficial',
  416. },
  417. 'playlist_count': 4,
  418. }, {
  419. 'url': 'https://steviasphere.bandcamp.com/music',
  420. 'playlist_mincount': 47,
  421. 'info_dict': {
  422. 'id': 'steviasphere',
  423. 'title': 'Discography of steviasphere',
  424. },
  425. }, {
  426. 'url': 'https://coldworldofficial.bandcamp.com/music',
  427. 'playlist_mincount': 10,
  428. 'info_dict': {
  429. 'id': 'coldworldofficial',
  430. 'title': 'Discography of coldworldofficial',
  431. },
  432. }, {
  433. 'url': 'https://nuclearwarnowproductions.bandcamp.com/music',
  434. 'playlist_mincount': 399,
  435. 'info_dict': {
  436. 'id': 'nuclearwarnowproductions',
  437. 'title': 'Discography of nuclearwarnowproductions',
  438. },
  439. }]
  440. def _real_extract(self, url):
  441. uploader = self._match_id(url)
  442. webpage = self._download_webpage(url, uploader)
  443. discography_data = (re.findall(r'<li data-item-id=["\'][^>]+>\s*<a href=["\'](?![^"\'/]*?/merch)([^"\']+)', webpage)
  444. or re.findall(r'<div[^>]+trackTitle["\'][^"\']+["\']([^"\']+)', webpage))
  445. return self.playlist_from_matches(
  446. discography_data, uploader, f'Discography of {uploader}', getter=lambda x: urljoin(url, x))