spotify.py 6.2 KB

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