python
#!/usr/bin/env python3
"""
Podcast Downloader and Organizer
================================
A simple Python script to download podcast episodes from an RSS feed and organize them into folders by podcast title.
Downloads only new episodes (checks if file already exists).
Requires: pip install feedparser requests
"""
import argparse
import feedparser
import os
import re
import requests
from datetime import datetime
from urllib.parse import urlparse, unquote
from pathlib import Path
def sanitize_filename(filename: str, max_length: int = 200) -> str:
"""
Sanitize a filename by removing invalid characters and truncating if too long.
"""
# Remove or replace invalid filename characters
filename = re.sub(r'[<>:"/\\|?*]', '', filename)
# Replace multiple spaces or special chars with single underscore
filename = re.sub(r'[\s\W]+', '_', filename).strip('_')
# Truncate to max_length
return filename[:max_length].rstrip('_')
def get_file_extension(url: str) -> str:
"""
Extract file extension from URL.
"""
parsed = urlparse(url)
ext = os.path.splitext(parsed.path)[1][1:].lower() # Remove dot and lowercase
return ext if ext else 'mp3' # Default to mp3
def download_episode(url: str, filepath: str) -> bool:
"""
Download episode with progress indication via streaming.
Returns True if successful.
"""
try:
response = requests.get(url, stream=True, timeout=30)
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))
with open(filepath, 'wb') as file:
downloaded = 0
for chunk in response.iter_content(chunk_size=8192):
if chunk:
file.write(chunk)
downloaded += len(chunk)
if total_size > 0:
progress = (downloaded / total_size) * 100
print(f"\rDownloading... {progress:.1f}%", end='', flush=True)
print(f"\rDownload complete! ")
return True
except Exception as e:
print(f"\nError downloading {url}: {e}")
return False
def download_podcasts(rss_urls: list, download_dir: str):
"""
Main function to parse RSS feeds and download episodes.
"""
download_path = Path(download_dir).expanduser()
download_path.mkdir(parents=True, exist_ok=True)
for rss_url in rss_urls:
print(f"\nParsing RSS feed: {rss_url}")
try:
feed = feedparser.parse(rss_url)
if feed.bozo:
print(f"Warning: Feed parsing issues - {feed.bozo_exception}")
continue
if not feed.entries:
print("No episodes found in feed.")
continue
podcast_title = feed.feed.get('title', 'Unknown Podcast')
podcast_dir = download_path / sanitize_filename(podcast_title)
podcast_dir.mkdir(exist_ok=True)
print(f"Podcast: {podcast_title}")
print(f"Directory: {podcast_dir}")
print("-" * 50)
downloaded_count = 0
skipped_count = 0
for entry in feed.entries:
title = entry.get('title', 'Untitled Episode')
enclosure = entry.get('enclosure')
if not enclosure or not enclosure.get('url'):
print(f"No enclosure URL for: {title}")
continue
episode_url = enclosure['url']
ext = get_file_extension(episode_url)
# Use published date if available, else fallback
pubdate = entry.get('published_parsed')
date_str = pubdate.strftime('%Y-%m-%d') if pubdate else datetime.now().strftime('%Y-%m-%d')
filename = f"{date_str} - {sanitize_filename(title)}.{ext}"
filepath = podcast_dir / filename
if filepath.exists():
print(f"Skipping (exists): {filename}")
skipped_count += 1
continue
print(f"Downloading: {filename}")
if download_episode(episode_url, filepath):
downloaded_count += 1
else:
# Optional: remove failed partial download
filepath.unlink(missing_ok=True)
print("-" * 50)
print(f"Summary for '{podcast_title}': {downloaded_count} downloaded, {skipped_count} skipped.")
except Exception as e:
print(f"Error processing {rss_url}: {e}")
def main():
parser = argparse.ArgumentParser(description="Download and organize podcasts from RSS feeds.")
parser.add_argument('rss_urls', nargs='+', help="One or more RSS feed URLs (e.g., 'https://example.com/podcast.rss')")
parser.add_argument('-d', '--download-dir', default='~/Podcasts',
help="Download directory (default: ~/Podcasts)")
args = parser.parse_args()
download_podcasts(args.rss_urls, args.download_dir)
if __name__ == "__main__":
main()
This script is production-ready for personal use. For automation, cron it or add a config file! 🕵️♂️