I'm thinking about how to create a script that fetches media. I'm considering using argparse for commands like sync, list, and update, though I might keep it simple by having the script read from config.json to download new episodes.
The directory structure would look like base_dir/<podcast_title_sanitized>//<YYYY-MM-DD - EpisodeTitle>.mp3. If a file exists, it may need to skip it or track downloaded GUIDs in a JSON database. I want to ensure the script is around 150-200 lines and handles cross-platform paths properly.Planning podcast downloader workflow
I’m outlining a workflow for my podcast downloader. First, I'll load the configuration file and iterate through each podcast. I plan to use feedparser to fetch the podcast feed from the corresponding URL and establish a directory for each podcast based on its title.
I want to create a state.json file in that directory to keep track of downloaded episode URLs. For each entry, I will check if it’s audio and then decide whether to download it based on whether it’s been downloaded before. I’ll also set up file naming using publication dates and slugified titles, adding entries to the state after successful downloads.Developing podcast downloader functions
I’m planning to utilize Path from pathlib and create a slugify(s) function for safe filenames. I want to define additional methods like load_state(podcast_dir) to return GUIDs and save_state(podcast_dir, state) for tracking downloads. The download_file(url, dest_path) function should handle streaming with proper error handling.
For the user interface, I’ll incorporate argparse with a --config path option and possibly a --dry-run flag. I'll set a single-thread focus since advanced concurrency isn't necessary and mention the need to install dependencies like feedparser and requests.
Some edge cases to account for are feeds that may not have entry.enclosures and entries with missing publication dates, which I’ll fallback to default dates for. For organization, I’ll create year-based subdirectories as needed. Lastly, I’ll consider allowing the user to override the max_episodes setting via the command line.Simplifying podcast downloader script
I’m considering a simpler approach where the script downloads all episodes but only fetches new ones. I plan to include a helpful docstring at the top of the script for clarity. The header will start with #!/usr/bin/env python3, ensuring it's recognizable as a Python script.
I want to provide users with an example configuration and keep everything generic since they didn't specify an OS. In the final answer, I’ll include the script as a code block, mention its dependencies, give a config example, and provide a brief how-to-run guide without excessive disclaimers, just noting to "use only where allowed." Below is a self-contained example: a Python script that reads a config file of podcast RSS feeds, downloads new episodes, and organizes them in folders by podcast name and year.
1. Dependencies
Install:
bash
pip install feedparser requests
2. Example configuration file
Create a podcasts.json file in the same directory as the script:
If you want adjustments (e.g., different folder layout, tagging, or integration with a player), say what you’d like changed and I can adapt the script.
#!/usr/bin/env python3
"""
podcast_downloader.py
Download and organize podcasts from RSS feeds.
Usage:
python podcast_downloader.py --config podcasts.json
Requirements:
pip install feedparser requests
"""
import argparse
import json
import os
import re
import sys
from pathlib import Path
from typing import Dict, Any, Set, Optional
import feedparser
import requests
from time import mktime
from datetime import datetime
def slugify(text: str, max_length: int = 80) -> str:
"""Make a filesystem-safe slug from text."""
text = text.strip()
# Replace non-alphanumeric characters with spaces
text = re.sub(r"[^A-Za-z0-9]+", " ", text)
# Collapse whitespace and replace with underscores
text = re.sub(r"\s+", "_", text).strip("_")
if not text:
text = "untitled"
if len(text) > max_length:
text = text[:max_length].rstrip("_")
return text
def load_json(path: Path, default):
if not path.exists():
return default
with path.open("r", encoding="utf-8") as f:
return json.load(f)
def save_json(path: Path, data):
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
with tmp.open("w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
tmp.replace(path)
def load_state(podcast_dir: Path) -> Dict[str, Any]:
"""State file tracks which episodes were downloaded."""
state_path = podcast_dir / "state.json"
state = load_json(state_path, default={"downloaded_ids": []})
state.setdefault("downloaded_ids", [])
return state
def save_state(podcast_dir: Path, state: Dict[str, Any]):
state_path = podcast_dir / "state.json"
save_json(state_path, state)
def get_episode_id(entry) -> str:
"""
Try to get a stable unique ID for an episode:
GUID -> link -> title+published.
"""
if "id" in entry and entry.id:
return str(entry.id)
if "guid" in entry and entry.guid:
return str(entry.guid)
if "link" in entry and entry.link:
return str(entry.link)
# Fallback
title = getattr(entry, "title", "untitled")
pub = getattr(entry, "published", "")
return f"{title}|{pub}"
def get_pubdate(entry) -> Optional[datetime]:
"""Return publication date as datetime, or None if unavailable."""
if hasattr(entry, "published_parsed") and entry.published_parsed:
return datetime.fromtimestamp(mktime(entry.published_parsed))
if hasattr(entry, "updated_parsed") and entry.updated_parsed:
return datetime.fromtimestamp(mktime(entry.updated_parsed))
return None
def choose_enclosure(entry) -> Optional[Dict[str, Any]]:
"""
Choose an audio enclosure from an RSS entry.
Returns a dict with 'href' and maybe 'type'.
"""
enclosures = getattr(entry, "enclosures", []) or []
if not enclosures:
return None
# Prefer audio/* or application/octet-stream
for enc in enclosures:
mime = enc.get("type", "") or ""
if mime.startswith("audio/") or mime == "application/octet-stream":
return enc
# Fallback: first enclosure
return enclosures[0]
def infer_extension(url: str, mime_type: str = "") -> str:
# Try from URL
path = url.split("?", 1)[0]
_, dot, ext = path.rpartition(".")
if dot and ext:
ext = ext.lower()
if len(ext) <= 5:
return "." + ext
# Fallback from MIME
mime_type = mime_type.lower()
if mime_type == "audio/mpeg":
return ".mp3"
if mime_type == "audio/mp4" or mime_type == "audio/x-m4a":
return ".m4a"
if mime_type == "audio/ogg":
return ".ogg"
if mime_type == "audio/x-wav" or mime_type == "audio/wav":
return ".wav"
return ".mp3" # sensible default
def download_file(url: str, dest_path: Path, chunk_size: int = 1024 * 1024):
"""Download a file to dest_path, streaming in chunks."""
dest_path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = dest_path.with_suffix(dest_path.suffix + ".part")
with requests.get(url, stream=True, timeout=30) as r:
r.raise_for_status()
total = int(r.headers.get("Content-Length", 0))
downloaded = 0
with tmp_path.open("wb") as f:
for chunk in r.iter_content(chunk_size=chunk_size):
if not chunk:
continue
f.write(chunk)
downloaded += len(chunk)
if total:
done = int(50 * downloaded / total)
bar = "[" + "#" * done + "." * (50 - done) + "]"
percent = 100 * downloaded / total
print(
f"\r {bar} {percent:5.1f}% "
f"({downloaded/1_000_000:.1f}/{total/1_000_000:.1f} MB)",
end="",
flush=True,
)
if total:
print() # newline after progress bar
tmp_path.replace(dest_path)
def process_podcast(pcfg: Dict[str, Any], download_root: Path, dry_run: bool = False):
name = pcfg["name"]
feed_url = pcfg["feed_url"]
max_episodes = int(pcfg.get("max_episodes", 0))
safe_name = slugify(name, max_length=60)
podcast_dir = download_root / safe_name
print(f"\n=== {name} ===")
print(f"Feed: {feed_url}")
print(f"Directory: {podcast_dir}")
# Load state
state = load_state(podcast_dir)
downloaded_ids: Set[str] = set(state.get("downloaded_ids", []))
print("Fetching feed...")
feed = feedparser.parse(feed_url)
if feed.bozo:
print(f" ERROR: Failed to parse feed ({feed.bozo_exception})")
return
entries = feed.entries
if not entries:
print(" No entries found.")
return
# Newest first (most feeds already are, but just in case)
entries = sorted(
entries,
key=lambda e: get_pubdate(e) or datetime.fromtimestamp(0),
reverse=True,
)
if max_episodes > 0:
entries = entries[:max_episodes]
new_count = 0
for entry in entries:
ep_id = get_episode_id(entry)
if ep_id in downloaded_ids:
continue
title = getattr(entry, "title", "Untitled episode")
pubdate = get_pubdate(entry)
enclosure = choose_enclosure(entry)
if not enclosure:
print(f" Skipping (no audio enclosure): {title}")
continue
url = enclosure.get("href")
if not url:
print(f" Skipping (no URL in enclosure): {title}")
continue
mime = enclosure.get("type", "")
ext = infer_extension(url, mime)
if pubdate:
date_str = pubdate.strftime("%Y-%m-%d")
year_str = pubdate.strftime("%Y")
else:
date_str = "0000-00-00"
year_str = "unknown_year"
title_slug = slugify(title, max_length=80)
filename = f"{date_str} - {title_slug}{ext}"
ep_dir = podcast_dir / year_str
dest_path = ep_dir / filename
if dest_path.exists():
# Assume it's already downloaded
print(f" Already exists (file): {filename}")
downloaded_ids.add(ep_id)
continue
print(f" New episode: {title}")
print(f" Date: {date_str}")
print(f" URL: {url}")
print(f" File: {dest_path}")
if dry_run:
print(" [dry-run] Skipping download.")
continue
try:
download_file(url, dest_path)
print(" Downloaded.")
downloaded_ids.add(ep_id)
new_count += 1
except Exception as e:
print(f" ERROR during download: {e}")
# Do not mark as downloaded on failure
# Save updated state
state["downloaded_ids"] = sorted(downloaded_ids)
if not dry_run:
save_state(podcast_dir, state)
print(f"Done. New episodes downloaded: {new_count}")
def main():
parser = argparse.ArgumentParser(
description="Download and organize podcasts from RSS feeds."
)
parser.add_argument(
"--config",
"-c",
required=True,
help="Path to JSON config file (see example).",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Show what would be downloaded without saving anything.",
)
args = parser.parse_args()
config_path = Path(args.config)
if not config_path.exists():
print(f"Config file not found: {config_path}", file=sys.stderr)
sys.exit(1)
config = load_json(config_path, default=None)
if not config:
print(f"Invalid or empty config: {config_path}", file=sys.stderr)
sys.exit(1)
download_root = Path(config.get("download_root", ".")).expanduser()
podcasts = config.get("podcasts", [])
if not podcasts:
print("No podcasts defined in config.", file=sys.stderr)
sys.exit(1)
print(f"Download root: {download_root}")
for pcfg in podcasts:
process_podcast(pcfg, download_root, dry_run=args.dry_run)
if __name__ == "__main__":
main()