logo

youtube-dl

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

spotify.py (5739B)


  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import json
  4. import re
  5. from .common import InfoExtractor
  6. from ..utils import (
  7. clean_podcast_url,
  8. float_or_none,
  9. int_or_none,
  10. strip_or_none,
  11. try_get,
  12. unified_strdate,
  13. )
  14. class SpotifyBaseIE(InfoExtractor):
  15. _ACCESS_TOKEN = None
  16. _OPERATION_HASHES = {
  17. 'Episode': '8276d4423d709ae9b68ec1b74cc047ba0f7479059a37820be730f125189ac2bf',
  18. 'MinimalShow': '13ee079672fad3f858ea45a55eb109553b4fb0969ed793185b2e34cbb6ee7cc0',
  19. 'ShowEpisodes': 'e0e5ce27bd7748d2c59b4d44ba245a8992a05be75d6fabc3b20753fc8857444d',
  20. }
  21. _VALID_URL_TEMPL = r'https?://open\.spotify\.com/%s/(?P<id>[^/?&#]+)'
  22. def _real_initialize(self):
  23. self._ACCESS_TOKEN = self._download_json(
  24. 'https://open.spotify.com/get_access_token', None)['accessToken']
  25. def _call_api(self, operation, video_id, variables):
  26. return self._download_json(
  27. 'https://api-partner.spotify.com/pathfinder/v1/query', video_id, query={
  28. 'operationName': 'query' + operation,
  29. 'variables': json.dumps(variables),
  30. 'extensions': json.dumps({
  31. 'persistedQuery': {
  32. 'sha256Hash': self._OPERATION_HASHES[operation],
  33. },
  34. })
  35. }, headers={'authorization': 'Bearer ' + self._ACCESS_TOKEN})['data']
  36. def _extract_episode(self, episode, series):
  37. episode_id = episode['id']
  38. title = episode['name'].strip()
  39. formats = []
  40. audio_preview = episode.get('audioPreview') or {}
  41. audio_preview_url = audio_preview.get('url')
  42. if audio_preview_url:
  43. f = {
  44. 'url': audio_preview_url.replace('://p.scdn.co/mp3-preview/', '://anon-podcast.scdn.co/'),
  45. 'vcodec': 'none',
  46. }
  47. audio_preview_format = audio_preview.get('format')
  48. if audio_preview_format:
  49. f['format_id'] = audio_preview_format
  50. mobj = re.match(r'([0-9A-Z]{3})_(?:[A-Z]+_)?(\d+)', audio_preview_format)
  51. if mobj:
  52. f.update({
  53. 'abr': int(mobj.group(2)),
  54. 'ext': mobj.group(1).lower(),
  55. })
  56. formats.append(f)
  57. for item in (try_get(episode, lambda x: x['audio']['items']) or []):
  58. item_url = item.get('url')
  59. if not (item_url and item.get('externallyHosted')):
  60. continue
  61. formats.append({
  62. 'url': clean_podcast_url(item_url),
  63. 'vcodec': 'none',
  64. })
  65. thumbnails = []
  66. for source in (try_get(episode, lambda x: x['coverArt']['sources']) or []):
  67. source_url = source.get('url')
  68. if not source_url:
  69. continue
  70. thumbnails.append({
  71. 'url': source_url,
  72. 'width': int_or_none(source.get('width')),
  73. 'height': int_or_none(source.get('height')),
  74. })
  75. return {
  76. 'id': episode_id,
  77. 'title': title,
  78. 'formats': formats,
  79. 'thumbnails': thumbnails,
  80. 'description': strip_or_none(episode.get('description')),
  81. 'duration': float_or_none(try_get(
  82. episode, lambda x: x['duration']['totalMilliseconds']), 1000),
  83. 'release_date': unified_strdate(try_get(
  84. episode, lambda x: x['releaseDate']['isoString'])),
  85. 'series': series,
  86. }
  87. class SpotifyIE(SpotifyBaseIE):
  88. IE_NAME = 'spotify'
  89. _VALID_URL = SpotifyBaseIE._VALID_URL_TEMPL % 'episode'
  90. _TEST = {
  91. 'url': 'https://open.spotify.com/episode/4Z7GAJ50bgctf6uclHlWKo',
  92. 'md5': '74010a1e3fa4d9e1ab3aa7ad14e42d3b',
  93. 'info_dict': {
  94. 'id': '4Z7GAJ50bgctf6uclHlWKo',
  95. 'ext': 'mp3',
  96. 'title': 'From the archive: Why time management is ruining our lives',
  97. 'description': 'md5:b120d9c4ff4135b42aa9b6d9cde86935',
  98. 'duration': 2083.605,
  99. 'release_date': '20201217',
  100. 'series': "The Guardian's Audio Long Reads",
  101. }
  102. }
  103. def _real_extract(self, url):
  104. episode_id = self._match_id(url)
  105. episode = self._call_api('Episode', episode_id, {
  106. 'uri': 'spotify:episode:' + episode_id
  107. })['episode']
  108. return self._extract_episode(
  109. episode, try_get(episode, lambda x: x['podcast']['name']))
  110. class SpotifyShowIE(SpotifyBaseIE):
  111. IE_NAME = 'spotify:show'
  112. _VALID_URL = SpotifyBaseIE._VALID_URL_TEMPL % 'show'
  113. _TEST = {
  114. 'url': 'https://open.spotify.com/show/4PM9Ke6l66IRNpottHKV9M',
  115. 'info_dict': {
  116. 'id': '4PM9Ke6l66IRNpottHKV9M',
  117. 'title': 'The Story from the Guardian',
  118. 'description': 'The Story podcast is dedicated to our finest audio documentaries, investigations and long form stories',
  119. },
  120. 'playlist_mincount': 36,
  121. }
  122. def _real_extract(self, url):
  123. show_id = self._match_id(url)
  124. podcast = self._call_api('ShowEpisodes', show_id, {
  125. 'limit': 1000000000,
  126. 'offset': 0,
  127. 'uri': 'spotify:show:' + show_id,
  128. })['podcast']
  129. podcast_name = podcast.get('name')
  130. entries = []
  131. for item in (try_get(podcast, lambda x: x['episodes']['items']) or []):
  132. episode = item.get('episode')
  133. if not episode:
  134. continue
  135. entries.append(self._extract_episode(episode, podcast_name))
  136. return self.playlist_result(
  137. entries, show_id, podcast_name, podcast.get('description'))