1 # -*- coding: utf-8 -*-
 
   6 from tempfile import mkdtemp
 
   8 from django.forms import Form, CharField
 
  10 from librarian import IOFile
 
  11 from catalogue.models import Lesson
 
  14 class LessonImportForm(Form):
 
  15     lesson_xml = CharField()
 
  16     gallery_url = CharField(required=False)
 
  17     attachments = CharField(required=False)
 
  21         attachment_names = json.loads(self.cleaned_data['attachments'])
 
  23         remote_gallery_url = self.cleaned_data['gallery_url']
 
  24         if remote_gallery_url and attachment_names:
 
  25             for attachment_name in attachment_names:
 
  26                 attachment_url = ('%s%s' % (remote_gallery_url, attachment_name)).encode('utf-8')
 
  27                 temp_filename = os.path.join(temp_dir, attachment_name)
 
  28                 urllib.urlretrieve(attachment_url, temp_filename)
 
  29                 attachments[attachment_name] = IOFile.from_filename(temp_filename)
 
  31         lesson = Lesson.publish(
 
  32             IOFile.from_string(self.cleaned_data['lesson_xml'], attachments=attachments))
 
  33         if os.path.isdir(temp_dir):
 
  34             shutil.rmtree(temp_dir)