bgneal@237: """
bgneal@237: import_old_podcasts.py - For importing podcasts from SG101 1.0 as csv files.
bgneal@237: """
bgneal@237: import csv
bgneal@237: import datetime
bgneal@237: 
bgneal@237: from django.core.management.base import LabelCommand, CommandError
bgneal@237: 
bgneal@237: from podcast.models import Channel, Item
bgneal@237: 
bgneal@237: 
bgneal@237: class Command(LabelCommand):
bgneal@237:     args = '<filename filename ...>'
bgneal@237:     help = 'Imports podcasts from the old database in CSV format'
bgneal@237: 
bgneal@237:     def handle_label(self, filename, **options):
bgneal@237:         """
bgneal@237:         Process each line in the CSV file given by filename by
bgneal@237:         creating a new weblink object and saving it to the database.
bgneal@237: 
bgneal@237:         """
bgneal@237:         try:
bgneal@237:             self.channel = Channel.objects.get(pk=1)
bgneal@237:         except Channel.DoesNotExist:
bgneal@237:             raise CommandError("Need a default channel with pk=1")
bgneal@237: 
bgneal@237:         try:
bgneal@237:             with open(filename, "rb") as f:
bgneal@237:                 self.reader = csv.DictReader(f)
bgneal@237:                 try:
bgneal@237:                     for row in self.reader:
bgneal@237:                         self.process_row(row)
bgneal@237:                 except csv.Error, e:
bgneal@237:                     raise CommandError("CSV error: %s %s %s" % (
bgneal@237:                         filename, self.reader.line_num, e))
bgneal@237: 
bgneal@237:         except IOError:
bgneal@237:             raise CommandError("Could not open file: %s" % filename)
bgneal@237: 
bgneal@237:     def process_row(self, row):
bgneal@237:         """
bgneal@237:         Process one row from the CSV file: create an object for the row
bgneal@237:         and save it in the database.
bgneal@237: 
bgneal@237:         """
bgneal@237:         item = Item(channel=self.channel,
bgneal@237:             title=row['title'],
bgneal@237:             author=row['author'],
bgneal@237:             subtitle=row['subtitle'],
bgneal@237:             summary=row['summary'],
bgneal@237:             enclosure_url=row['enclosure_url'],
bgneal@237:             alt_enclosure_url='',
bgneal@237:             enclosure_length=int(row['enclosure_length']),
bgneal@237:             enclosure_type=row['enclosure_type'],
bgneal@237:             guid=row['guid'],
bgneal@237:             pubdate=datetime.datetime.strptime(row['pubdate'],
bgneal@237:                 "%Y-%m-%d %H:%M:%S"),
bgneal@237:             duration=row['duration'],
bgneal@237:             keywords=row['keywords'],
bgneal@237:             explicit=row['explicit'])
bgneal@237: 
bgneal@237:         item.save()