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.

417 lines
15 KiB

  1. from __future__ import unicode_literals
  2. import random
  3. import re
  4. import time
  5. from .common import InfoExtractor
  6. from ..compat import (
  7. compat_str,
  8. compat_urlparse,
  9. )
  10. from ..utils import (
  11. ExtractorError,
  12. float_or_none,
  13. int_or_none,
  14. KNOWN_EXTENSIONS,
  15. parse_filesize,
  16. str_or_none,
  17. try_get,
  18. unescapeHTML,
  19. update_url_query,
  20. unified_strdate,
  21. unified_timestamp,
  22. url_or_none,
  23. )
  24. class BandcampIE(InfoExtractor):
  25. _VALID_URL = r'https?://[^/]+\.bandcamp\.com/track/(?P<title>[^/?#&]+)'
  26. _TESTS = [{
  27. 'url': 'http://youtube-dl.bandcamp.com/track/youtube-dl-test-song',
  28. 'md5': 'c557841d5e50261777a6585648adf439',
  29. 'info_dict': {
  30. 'id': '1812978515',
  31. 'ext': 'mp3',
  32. 'title': "youtube-dl \"'/\\\u00e4\u21ad - youtube-dl test song \"'/\\\u00e4\u21ad",
  33. 'duration': 9.8485,
  34. },
  35. '_skip': 'There is a limit of 200 free downloads / month for the test song'
  36. }, {
  37. # free download
  38. 'url': 'http://benprunty.bandcamp.com/track/lanius-battle',
  39. 'md5': '853e35bf34aa1d6fe2615ae612564b36',
  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 _real_extract(self, url):
  78. mobj = re.match(self._VALID_URL, url)
  79. title = mobj.group('title')
  80. webpage = self._download_webpage(url, title)
  81. thumbnail = self._html_search_meta('og:image', webpage, default=None)
  82. track_id = None
  83. track = None
  84. track_number = None
  85. duration = None
  86. formats = []
  87. track_info = self._parse_json(
  88. self._search_regex(
  89. r'trackinfo\s*:\s*\[\s*({.+?})\s*\]\s*,\s*?\n',
  90. webpage, 'track info', default='{}'), title)
  91. if track_info:
  92. file_ = track_info.get('file')
  93. if isinstance(file_, dict):
  94. for format_id, format_url in file_.items():
  95. if not url_or_none(format_url):
  96. continue
  97. ext, abr_str = format_id.split('-', 1)
  98. formats.append({
  99. 'format_id': format_id,
  100. 'url': self._proto_relative_url(format_url, 'http:'),
  101. 'ext': ext,
  102. 'vcodec': 'none',
  103. 'acodec': ext,
  104. 'abr': int_or_none(abr_str),
  105. })
  106. track = track_info.get('title')
  107. track_id = str_or_none(track_info.get('track_id') or track_info.get('id'))
  108. track_number = int_or_none(track_info.get('track_num'))
  109. duration = float_or_none(track_info.get('duration'))
  110. def extract(key):
  111. return self._search_regex(
  112. r'\b%s\s*["\']?\s*:\s*(["\'])(?P<value>(?:(?!\1).)+)\1' % key,
  113. webpage, key, default=None, group='value')
  114. artist = extract('artist')
  115. album = extract('album_title')
  116. timestamp = unified_timestamp(
  117. extract('publish_date') or extract('album_publish_date'))
  118. release_date = unified_strdate(extract('album_release_date'))
  119. download_link = self._search_regex(
  120. r'freeDownloadPage\s*:\s*(["\'])(?P<url>(?:(?!\1).)+)\1', webpage,
  121. 'download link', default=None, group='url')
  122. if download_link:
  123. track_id = self._search_regex(
  124. r'(?ms)var TralbumData = .*?[{,]\s*id: (?P<id>\d+),?$',
  125. webpage, 'track id')
  126. download_webpage = self._download_webpage(
  127. download_link, track_id, 'Downloading free downloads page')
  128. blob = self._parse_json(
  129. self._search_regex(
  130. r'data-blob=(["\'])(?P<blob>{.+?})\1', download_webpage,
  131. 'blob', group='blob'),
  132. track_id, transform_source=unescapeHTML)
  133. info = try_get(
  134. blob, (lambda x: x['digital_items'][0],
  135. lambda x: x['download_items'][0]), dict)
  136. if info:
  137. downloads = info.get('downloads')
  138. if isinstance(downloads, dict):
  139. if not track:
  140. track = info.get('title')
  141. if not artist:
  142. artist = info.get('artist')
  143. if not thumbnail:
  144. thumbnail = info.get('thumb_url')
  145. download_formats = {}
  146. download_formats_list = blob.get('download_formats')
  147. if isinstance(download_formats_list, list):
  148. for f in blob['download_formats']:
  149. name, ext = f.get('name'), f.get('file_extension')
  150. if all(isinstance(x, compat_str) for x in (name, ext)):
  151. download_formats[name] = ext.strip('.')
  152. for format_id, f in downloads.items():
  153. format_url = f.get('url')
  154. if not format_url:
  155. continue
  156. # Stat URL generation algorithm is reverse engineered from
  157. # download_*_bundle_*.js
  158. stat_url = update_url_query(
  159. format_url.replace('/download/', '/statdownload/'), {
  160. '.rand': int(time.time() * 1000 * random.random()),
  161. })
  162. format_id = f.get('encoding_name') or format_id
  163. stat = self._download_json(
  164. stat_url, track_id, 'Downloading %s JSON' % format_id,
  165. transform_source=lambda s: s[s.index('{'):s.rindex('}') + 1],
  166. fatal=False)
  167. if not stat:
  168. continue
  169. retry_url = url_or_none(stat.get('retry_url'))
  170. if not retry_url:
  171. continue
  172. formats.append({
  173. 'url': self._proto_relative_url(retry_url, 'http:'),
  174. 'ext': download_formats.get(format_id),
  175. 'format_id': format_id,
  176. 'format_note': f.get('description'),
  177. 'filesize': parse_filesize(f.get('size_mb')),
  178. 'vcodec': 'none',
  179. })
  180. self._sort_formats(formats)
  181. title = '%s - %s' % (artist, track) if artist else track
  182. if not duration:
  183. duration = float_or_none(self._html_search_meta(
  184. 'duration', webpage, default=None))
  185. return {
  186. 'id': track_id,
  187. 'title': title,
  188. 'thumbnail': thumbnail,
  189. 'uploader': artist,
  190. 'timestamp': timestamp,
  191. 'release_date': release_date,
  192. 'duration': duration,
  193. 'track': track,
  194. 'track_number': track_number,
  195. 'track_id': track_id,
  196. 'artist': artist,
  197. 'album': album,
  198. 'formats': formats,
  199. }
  200. class BandcampAlbumIE(InfoExtractor):
  201. IE_NAME = 'Bandcamp:album'
  202. _VALID_URL = r'https?://(?:(?P<subdomain>[^.]+)\.)?bandcamp\.com(?:/album/(?P<album_id>[^/?#&]+))?'
  203. _TESTS = [{
  204. 'url': 'http://blazo.bandcamp.com/album/jazz-format-mixtape-vol-1',
  205. 'playlist': [
  206. {
  207. 'md5': '39bc1eded3476e927c724321ddf116cf',
  208. 'info_dict': {
  209. 'id': '1353101989',
  210. 'ext': 'mp3',
  211. 'title': 'Intro',
  212. }
  213. },
  214. {
  215. 'md5': '1a2c32e2691474643e912cc6cd4bffaa',
  216. 'info_dict': {
  217. 'id': '38097443',
  218. 'ext': 'mp3',
  219. 'title': 'Kero One - Keep It Alive (Blazo remix)',
  220. }
  221. },
  222. ],
  223. 'info_dict': {
  224. 'title': 'Jazz Format Mixtape vol.1',
  225. 'id': 'jazz-format-mixtape-vol-1',
  226. 'uploader_id': 'blazo',
  227. },
  228. 'params': {
  229. 'playlistend': 2
  230. },
  231. 'skip': 'Bandcamp imposes download limits.'
  232. }, {
  233. 'url': 'http://nightbringer.bandcamp.com/album/hierophany-of-the-open-grave',
  234. 'info_dict': {
  235. 'title': 'Hierophany of the Open Grave',
  236. 'uploader_id': 'nightbringer',
  237. 'id': 'hierophany-of-the-open-grave',
  238. },
  239. 'playlist_mincount': 9,
  240. }, {
  241. 'url': 'http://dotscale.bandcamp.com',
  242. 'info_dict': {
  243. 'title': 'Loom',
  244. 'id': 'dotscale',
  245. 'uploader_id': 'dotscale',
  246. },
  247. 'playlist_mincount': 7,
  248. }, {
  249. # with escaped quote in title
  250. 'url': 'https://jstrecords.bandcamp.com/album/entropy-ep',
  251. 'info_dict': {
  252. 'title': '"Entropy" EP',
  253. 'uploader_id': 'jstrecords',
  254. 'id': 'entropy-ep',
  255. },
  256. 'playlist_mincount': 3,
  257. }, {
  258. # not all tracks have songs
  259. 'url': 'https://insulters.bandcamp.com/album/we-are-the-plague',
  260. 'info_dict': {
  261. 'id': 'we-are-the-plague',
  262. 'title': 'WE ARE THE PLAGUE',
  263. 'uploader_id': 'insulters',
  264. },
  265. 'playlist_count': 2,
  266. }]
  267. @classmethod
  268. def suitable(cls, url):
  269. return (False
  270. if BandcampWeeklyIE.suitable(url) or BandcampIE.suitable(url)
  271. else super(BandcampAlbumIE, cls).suitable(url))
  272. def _real_extract(self, url):
  273. mobj = re.match(self._VALID_URL, url)
  274. uploader_id = mobj.group('subdomain')
  275. album_id = mobj.group('album_id')
  276. playlist_id = album_id or uploader_id
  277. webpage = self._download_webpage(url, playlist_id)
  278. track_elements = re.findall(
  279. r'(?s)<div[^>]*>(.*?<a[^>]+href="([^"]+?)"[^>]+itemprop="url"[^>]*>.*?)</div>', webpage)
  280. if not track_elements:
  281. raise ExtractorError('The page doesn\'t contain any tracks')
  282. # Only tracks with duration info have songs
  283. entries = [
  284. self.url_result(
  285. compat_urlparse.urljoin(url, t_path),
  286. ie=BandcampIE.ie_key(),
  287. video_title=self._search_regex(
  288. r'<span\b[^>]+\bitemprop=["\']name["\'][^>]*>([^<]+)',
  289. elem_content, 'track title', fatal=False))
  290. for elem_content, t_path in track_elements
  291. if self._html_search_meta('duration', elem_content, default=None)]
  292. title = self._html_search_regex(
  293. r'album_title\s*:\s*"((?:\\.|[^"\\])+?)"',
  294. webpage, 'title', fatal=False)
  295. if title:
  296. title = title.replace(r'\"', '"')
  297. return {
  298. '_type': 'playlist',
  299. 'uploader_id': uploader_id,
  300. 'id': playlist_id,
  301. 'title': title,
  302. 'entries': entries,
  303. }
  304. class BandcampWeeklyIE(InfoExtractor):
  305. IE_NAME = 'Bandcamp:weekly'
  306. _VALID_URL = r'https?://(?:www\.)?bandcamp\.com/?\?(?:.*?&)?show=(?P<id>\d+)'
  307. _TESTS = [{
  308. 'url': 'https://bandcamp.com/?show=224',
  309. 'md5': 'b00df799c733cf7e0c567ed187dea0fd',
  310. 'info_dict': {
  311. 'id': '224',
  312. 'ext': 'opus',
  313. 'title': 'BC Weekly April 4th 2017 - Magic Moments',
  314. 'description': 'md5:5d48150916e8e02d030623a48512c874',
  315. 'duration': 5829.77,
  316. 'release_date': '20170404',
  317. 'series': 'Bandcamp Weekly',
  318. 'episode': 'Magic Moments',
  319. 'episode_number': 208,
  320. 'episode_id': '224',
  321. }
  322. }, {
  323. 'url': 'https://bandcamp.com/?blah/blah@&show=228',
  324. 'only_matching': True
  325. }]
  326. def _real_extract(self, url):
  327. video_id = self._match_id(url)
  328. webpage = self._download_webpage(url, video_id)
  329. blob = self._parse_json(
  330. self._search_regex(
  331. r'data-blob=(["\'])(?P<blob>{.+?})\1', webpage,
  332. 'blob', group='blob'),
  333. video_id, transform_source=unescapeHTML)
  334. show = blob['bcw_show']
  335. # This is desired because any invalid show id redirects to `bandcamp.com`
  336. # which happens to expose the latest Bandcamp Weekly episode.
  337. show_id = int_or_none(show.get('show_id')) or int_or_none(video_id)
  338. formats = []
  339. for format_id, format_url in show['audio_stream'].items():
  340. if not url_or_none(format_url):
  341. continue
  342. for known_ext in KNOWN_EXTENSIONS:
  343. if known_ext in format_id:
  344. ext = known_ext
  345. break
  346. else:
  347. ext = None
  348. formats.append({
  349. 'format_id': format_id,
  350. 'url': format_url,
  351. 'ext': ext,
  352. 'vcodec': 'none',
  353. })
  354. self._sort_formats(formats)
  355. title = show.get('audio_title') or 'Bandcamp Weekly'
  356. subtitle = show.get('subtitle')
  357. if subtitle:
  358. title += ' - %s' % subtitle
  359. episode_number = None
  360. seq = blob.get('bcw_seq')
  361. if seq and isinstance(seq, list):
  362. try:
  363. episode_number = next(
  364. int_or_none(e.get('episode_number'))
  365. for e in seq
  366. if isinstance(e, dict) and int_or_none(e.get('id')) == show_id)
  367. except StopIteration:
  368. pass
  369. return {
  370. 'id': video_id,
  371. 'title': title,
  372. 'description': show.get('desc') or show.get('short_desc'),
  373. 'duration': float_or_none(show.get('audio_duration')),
  374. 'is_live': False,
  375. 'release_date': unified_strdate(show.get('published_date')),
  376. 'series': 'Bandcamp Weekly',
  377. 'episode': show.get('subtitle'),
  378. 'episode_number': episode_number,
  379. 'episode_id': compat_str(video_id),
  380. 'formats': formats
  381. }