#!/opt/local/bin/python
#
# PodcastBaker is an easy way to create an iTunes compatable Podcast
# from the media files in a directory.
# Copyright (C) 2011 Noel Schutt

"""PodcastBaker is an easy way to create an iTunes compatable Podcast

This script will read all the files in a folder that match a filter,
creating a Podcast XML file based on the file metadata. For MP3 files,
the data is pulled from the ID3v2 metadata.
"""


version = (0, 1)
version_string = ".".join(map(str, version))

from mutagen.mp3 import MP3 # only import for MP3 files for now
import glob
import os.path
from time import strptime, strftime
from xml.etree.ElementTree import Element, SubElement, tostring

#============ Settings ============
# Edit the podcast_info to customize the podcast.
# If the podcast episodes aren't by date, you'll have more
# editing to do.

date_format = '%Y-%m-%d' # date format used in XML file
infile_date_format = '%Y-%m-%d' # used if input file is a different date format
file_filter = '/Users/noel/Sites/tec/sermons/*.mp3' # absolute path to files

#==== Podcast General Info ===
# base_url is the location of the files
# home_url is a link to a webpage for the podcasts
# title is the title of the podcast as it will appear in iTunes
# description is a general description of the podcast
podcast_info = { 'base_url':'http://example.com/podcasts/',
                 'home_url':'http://example.com/',
                 'title':'My Podcast',
                 'description':'My personal Podcast feed.'
               }

#============ END Settings ============


top = Element('rss')
top.set('version', '2.0')
top.set('xmlns:itunes', 'http://www.itunes.com/dtds/podcast-1.0.dtd')


chan = SubElement(top, 'channel')

chan_title = SubElement(chan, 'title')
chan_title.text = podcast_info['title']

chan_link = SubElement(chan, 'link')
chan_link.text = podcast_info['home_url']

chan_description = SubElement(chan, 'description')
chan_description.text = podcast_info['description']



for afile in glob.iglob(file_filter) :

    audio = MP3(afile)
    artist = audio["TPE1"]
    album = audio["TALB"]

    item = SubElement(chan, 'item')
    
    podcast_title = SubElement(item, 'title')
    podcast_title.text = str(audio["TIT2"])

    podcast_author = SubElement(item, 'itunes:author')
    podcast_author.text = str(audio["TPE1"])

    podcast_pubDate = SubElement(item, 'pubDate')
    try :
        podcast_pubDate.text = strftime(date_format, strptime(os.path.splitext(os.path.split(afile)[1])[0], infile_date_format))
    except :
        pass

    podcast_enclosure = SubElement(item, 'enclosure', {'url':podcast_info['base_url']+os.path.split(afile)[1], 'length':str(int(audio.info.length)), 'type':'audio/mpeg'})

    podcast_duration = SubElement(item, 'itunes:duration')
    podcast_duration.text = str(int(audio.info.length))
    
print '<?xml version="1.0"?>'
print tostring(top)

