podcast.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. import os
  2. import time
  3. from typing import Optional, Tuple
  4. from librespot.metadata import EpisodeId
  5. from const import ERROR, ID, ITEMS, NAME, SHOW, RELEASE_DATE, DURATION_MS, EXT_MAP
  6. from termoutput import PrintChannel, Printer
  7. from utils import create_download_directory, fix_filename
  8. from track import convert_audio_format
  9. from zspotify import ZSpotify
  10. from loader import Loader
  11. EPISODE_INFO_URL = 'https://api.spotify.com/v1/episodes'
  12. SHOWS_URL = 'https://api.spotify.com/v1/shows'
  13. def get_episode_info(episode_id_str) -> Tuple[Optional[str], Optional[str]]:
  14. with Loader(PrintChannel.PROGRESS_INFO, "Fetching episode information..."):
  15. (raw, info) = ZSpotify.invoke_url(f'{EPISODE_INFO_URL}/{episode_id_str}')
  16. if not info:
  17. Printer.print(PrintChannel.ERRORS, "### INVALID EPISODE ID ###")
  18. duration_ms = info[DURATION_MS]
  19. if ERROR in info:
  20. return None, None
  21. return fix_filename(info[SHOW][NAME]), duration_ms, fix_filename(info[NAME]), fix_filename(info[RELEASE_DATE])
  22. def get_show_episodes(show_id_str) -> list:
  23. episodes = []
  24. offset = 0
  25. limit = 50
  26. with Loader(PrintChannel.PROGRESS_INFO, "Fetching episodes..."):
  27. while True:
  28. resp = ZSpotify.invoke_url_with_params(
  29. f'{SHOWS_URL}/{show_id_str}/episodes', limit=limit, offset=offset)
  30. offset += limit
  31. for episode in resp[ITEMS]:
  32. episodes.append(episode[ID])
  33. if len(resp[ITEMS]) < limit:
  34. break
  35. return episodes
  36. def download_podcast_directly(url, filename):
  37. import functools
  38. import pathlib
  39. import shutil
  40. import requests
  41. from tqdm.auto import tqdm
  42. r = requests.get(url, stream=True, allow_redirects=True)
  43. if r.status_code != 200:
  44. r.raise_for_status() # Will only raise for 4xx codes, so...
  45. raise RuntimeError(
  46. f"Request to {url} returned status code {r.status_code}")
  47. file_size = int(r.headers.get('Content-Length', 0))
  48. path = pathlib.Path(filename).expanduser().resolve()
  49. path.parent.mkdir(parents=True, exist_ok=True)
  50. desc = "(Unknown total file size)" if file_size == 0 else ""
  51. r.raw.read = functools.partial(
  52. r.raw.read, decode_content=True) # Decompress if needed
  53. with tqdm.wrapattr(r.raw, "read", total=file_size, desc=desc) as r_raw:
  54. with path.open("wb") as f:
  55. shutil.copyfileobj(r_raw, f)
  56. return path
  57. def download_episode(episode_id) -> None:
  58. podcast_name, duration_ms, episode_name, release_date = get_episode_info(episode_id)
  59. prepare_download_loader = Loader(PrintChannel.PROGRESS_INFO, "Preparing download...")
  60. prepare_download_loader.start()
  61. if podcast_name is None:
  62. Printer.print(PrintChannel.SKIPS, '### SKIPPING: (EPISODE NOT FOUND) ###')
  63. prepare_download_loader.stop()
  64. else:
  65. ext = EXT_MAP.get(ZSpotify.CONFIG.get_download_format().lower())
  66. output_template = ZSpotify.CONFIG.get_output('podcast')
  67. output_template = output_template.replace("{podcast}", fix_filename(podcast_name))
  68. output_template = output_template.replace("{episode_name}", fix_filename(episode_name))
  69. output_template = output_template.replace("{release_date}", fix_filename(release_date))
  70. output_template = output_template.replace("{ext}", fix_filename(ext))
  71. filename = os.path.join(ZSpotify.CONFIG.get_root_podcast_path(), output_template)
  72. download_directory = os.path.dirname(filename)
  73. create_download_directory(download_directory)
  74. episode_id = EpisodeId.from_base62(episode_id)
  75. stream = ZSpotify.get_content_stream(
  76. episode_id, ZSpotify.DOWNLOAD_QUALITY)
  77. total_size = stream.input_stream.size
  78. if (
  79. os.path.isfile(filename)
  80. and os.path.getsize(filename) == total_size
  81. and ZSpotify.CONFIG.get_skip_existing_files()
  82. ):
  83. Printer.print(PrintChannel.SKIPS, "\n### SKIPPING: " + podcast_name + " - " + episode_name + " (EPISODE ALREADY EXISTS) ###")
  84. prepare_download_loader.stop()
  85. return
  86. prepare_download_loader.stop()
  87. time_start = time.time()
  88. downloaded = 0
  89. with open(filename, 'wb') as file, Printer.progress(
  90. desc=filename,
  91. total=total_size,
  92. unit='B',
  93. unit_scale=True,
  94. unit_divisor=1024
  95. ) as p_bar:
  96. prepare_download_loader.stop()
  97. while total_size > downloaded:
  98. data = stream.input_stream.stream().read(ZSpotify.CONFIG.get_chunk_size())
  99. p_bar.update(file.write(data))
  100. downloaded += len(data)
  101. if len(data) == 0:
  102. break
  103. if ZSpotify.CONFIG.get_download_real_time():
  104. delta_real = time.time() - time_start
  105. delta_want = (downloaded / total_size) * (duration_ms/1000)
  106. if delta_want > delta_real:
  107. time.sleep(delta_want - delta_real)
  108. convert_audio_format(filename)
  109. prepare_download_loader.stop()