hide banner
[edumed.git] / catalogue / forms.py
index 834785f..7230b23 100644 (file)
@@ -1,23 +1,35 @@
 # -*- coding: utf-8 -*-
-from django.forms import Form, FileField, CharField, ValidationError
+import json
+import os.path
+import shutil
+import urllib
+from tempfile import mkdtemp
 
+from django.forms import Form, CharField
+
+from librarian import IOFile
 from catalogue.models import Lesson
 
 
 class LessonImportForm(Form):
-    lesson_xml_file = FileField(required=False)
-    lesson_xml = CharField(required=False)
-
-    def clean(self):
-        from django.core.files.base import ContentFile
+    lesson_xml = CharField()
+    gallery_url = CharField(required=False)
+    attachments = CharField(required=False)
 
-        if not self.cleaned_data['lesson_xml_file']:
-            if self.cleaned_data['lesson_xml']:
-                self.cleaned_data['lesson_xml_file'] = \
-                    ContentFile(self.cleaned_data['lesson_xml'].encode('utf-8'))
-            else:
-                raise ValidationError(u"Proszę dostarczyć XML.")
-        return super(LessonImportForm, self).clean()
+    def save(self):
+        temp_dir = mkdtemp()
+        attachment_names = json.loads(self.cleaned_data['attachments'])
+        attachments = {}
+        remote_gallery_url = self.cleaned_data['gallery_url']
+        if remote_gallery_url and attachment_names:
+            for attachment_name in attachment_names:
+                attachment_url = ('%s%s' % (remote_gallery_url, attachment_name)).encode('utf-8')
+                temp_filename = os.path.join(temp_dir, attachment_name)
+                urllib.urlretrieve(attachment_url, temp_filename)
+                attachments[attachment_name] = IOFile.from_filename(temp_filename)
 
-    def save(self, commit=True, **kwargs):
-        return Lesson.publish(self.cleaned_data['book_xml_file'])
+        lesson = Lesson.publish(
+            IOFile.from_string(self.cleaned_data['lesson_xml'], attachments=attachments))
+        if os.path.isdir(temp_dir):
+            shutil.rmtree(temp_dir)
+        return lesson