Importing whole sections.
[edumed.git] / catalogue / models.py
1 from django.core.files import File
2 from django.core.urlresolvers import reverse
3 from django.db import models
4 from jsonfield import JSONField
5 from curriculum.models import Level
6
7
8 class Section(models.Model):
9     title = models.CharField(max_length=255, unique=True)
10     slug = models.SlugField(unique=True)
11     order = models.IntegerField()
12     xml_file = models.FileField(upload_to="catalogue/section/xml",
13         null=True, blank=True)
14
15     class Meta:
16         ordering = ['order']
17
18     class IncompleteError(BaseException):
19         pass
20
21     def __unicode__(self):
22         return self.title
23
24     def get_absolute_url(self):
25         return "%s#%s" % (reverse("catalogue_lessons"), self.slug)
26
27     @classmethod
28     def publish(cls, infile):
29         from librarian.parser import WLDocument
30         from django.core.files.base import ContentFile
31         xml = infile.get_string()
32         wldoc = WLDocument.from_string(xml)
33
34         try:
35             lessons = [Lesson.objects.get(slug=part.slug)
36                         for part in wldoc.book_info.parts]
37         except Lesson.DoesNotExist, e:
38             raise cls.IncompleteError(e)
39
40         slug = wldoc.book_info.url.slug
41         try:
42             section = cls.objects.get(slug=slug)
43         except cls.DoesNotExist:
44             section = cls(slug=slug, order=0)
45
46         # Save XML file
47         section.xml_file.save('%s.xml' % slug, ContentFile(xml), save=False)
48         section.title = wldoc.book_info.title
49         section.save()
50
51         section.lesson_set.all().update(section=None)
52         for i, lesson in enumerate(lessons):
53             lesson.section = section
54             lesson.order = i
55             lesson.save()
56
57         return section
58
59
60     def syntetic_lesson(self):
61         try:
62             return self.lesson_set.filter(type='synthetic')[0]
63         except IndexError:
64             return None
65
66
67 class Lesson(models.Model):
68     section = models.ForeignKey(Section, null=True, blank=True)
69     level = models.ForeignKey(Level)
70     title = models.CharField(max_length=255)
71     slug = models.SlugField(unique=True)
72     type = models.CharField(max_length=15, db_index=True)
73     order = models.IntegerField(db_index=True)
74     dc = JSONField(default='{}')
75
76     xml_file = models.FileField(upload_to="catalogue/lesson/xml",
77         null=True, blank=True) # FIXME: slug in paths
78     html_file = models.FileField(upload_to="catalogue/lesson/html",
79         null=True, blank=True)
80     package = models.FileField(upload_to="catalogue/lesson/pack",
81         null=True, blank=True)
82     student_package = models.FileField(upload_to="catalogue/lesson/student_pack",
83         null=True, blank=True)
84     pdf = models.FileField(upload_to="catalogue/lesson/pdf",
85         null=True, blank=True)
86     student_pdf = models.FileField(upload_to="catalogue/lesson/student_pdf",
87         null=True, blank=True)
88
89     class Meta:
90         ordering = ['section', 'level', 'order']
91
92     def __unicode__(self):
93         return self.title
94
95     @models.permalink
96     def get_absolute_url(self):
97         return ('catalogue_lesson', [self.slug])
98
99     @classmethod
100     def publish(cls, infile):
101         from librarian.parser import WLDocument
102         from django.core.files.base import ContentFile
103         xml = infile.get_string()
104         wldoc = WLDocument.from_string(xml)
105
106         # Check if not section metadata block.
107         if wldoc.book_info.parts:
108             return Section.publish(infile)
109         
110         slug = wldoc.book_info.url.slug
111         try:
112             lesson = cls.objects.get(slug=slug)
113         except cls.DoesNotExist:
114             lesson = cls(slug=slug)
115
116         lesson.attachment_set.all().delete()
117         for att_name, att_file in infile.attachments.items():
118             try:
119                 slug, ext = att_name.rsplit('.', 1)
120             except ValueError:
121                 slug, ext = att_name, ''
122             attachment = lesson.attachment_set.create(slug=slug, ext=ext)
123             attachment.file.save(att_name, ContentFile(att_file.get_string()))
124
125         # Save XML file
126         lesson.xml_file.save('%s.xml' % slug, ContentFile(xml), save=False)
127         lesson.title = wldoc.book_info.title
128
129         lesson.level = Level.objects.get(slug=wldoc.book_info.audience)
130         lesson.order = 0
131         lesson.populate_dc()
132         lesson.type = lesson.dc["type"]
133         lesson.save()
134         lesson.build_html()
135         lesson.build_package()
136         lesson.build_package(student=True)
137         return lesson
138
139     def populate_dc(self):
140         from librarian.parser import WLDocument
141         wldoc = WLDocument.from_file(self.xml_file.path)
142         self.dc = wldoc.book_info.to_dict()
143         self.save()
144
145     def build_html(self):
146         from librarian.parser import WLDocument
147         wldoc = WLDocument.from_file(self.xml_file.path)
148         html = wldoc.as_html()
149         self.html_file.save("%s.html" % self.slug,
150             File(open(html.get_filename())))
151
152     def build_package(self, student=False):
153         from StringIO import StringIO
154         import zipfile
155         from django.core.files.base import ContentFile
156         buff = StringIO()
157         zipf = zipfile.ZipFile(buff, 'w', zipfile.ZIP_STORED)
158         zipf.write(self.xml_file.path, "pliki-zrodlowe/%s.xml" % self.slug)
159         pdf = self.student_pdf if student else self.pdf
160         if pdf:
161             zipf.write(self.xml_file.path, 
162                 "%s%s.pdf" % (self.slug, "_student" if student else ""))
163         zipf.close()
164         fieldname = "student_package" if student else "package"
165         getattr(self, fieldname).save(
166             "%s%s.zip" % (self.slug, "_student" if student else ""),
167             ContentFile(buff.getvalue()))
168
169
170 class Attachment(models.Model):
171     slug = models.CharField(max_length=255)
172     ext = models.CharField(max_length=15)
173     lesson = models.ForeignKey(Lesson)
174     file = models.FileField(upload_to="catalogue/attachment")
175
176     class Meta:
177         ordering = ['slug', 'ext']
178         unique_together = ['lesson', 'slug', 'ext']
179
180     def __unicode__(self):
181         return "%s.%s" % (self.slug, self.ext)
182
183
184 class Part(models.Model):
185     lesson = models.ForeignKey(Lesson)
186     pdf = models.FileField(upload_to="catalogue/part/pdf",
187         null=True, blank=True)
188     student_pdf = models.FileField(upload_to="catalogue/part/student_pdf",
189         null=True, blank=True)