logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

bandcamp.py (14460B)


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