ae87ca8adb684ac2b65bb942b9b09e02d05bde91
[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, Curriculum, CurriculumCourse
6
7
8 class Section(models.Model):
9     title = models.CharField(max_length=255, unique=True)
10     slug = models.SlugField(max_length=255, unique=True)
11     order = models.IntegerField()
12     xml_file = models.FileField(upload_to="catalogue/section/xml",
13         null=True, blank=True, max_length=255)
14     image = models.ImageField(upload_to="catalogue/section/image",
15         null=True, blank=True)
16
17     class Meta:
18         ordering = ['order']
19
20     class IncompleteError(BaseException):
21         pass
22
23     def __unicode__(self):
24         return self.title
25
26     def get_absolute_url(self):
27         return "%s#%s" % (reverse("catalogue_lessons"), self.slug)
28
29     @classmethod
30     def publish(cls, infile):
31         from librarian.parser import WLDocument
32         from django.core.files.base import ContentFile
33         xml = infile.get_string()
34         wldoc = WLDocument.from_string(xml)
35
36         try:
37             lessons = [Lesson.objects.get(slug=part.slug)
38                         for part in wldoc.book_info.parts]
39         except Lesson.DoesNotExist, e:
40             raise cls.IncompleteError(part.slug)
41
42         slug = wldoc.book_info.url.slug
43         try:
44             section = cls.objects.get(slug=slug)
45         except cls.DoesNotExist:
46             section = cls(slug=slug, order=0)
47
48         # Save XML file
49         section.xml_file.save('%s.xml' % slug, ContentFile(xml), save=False)
50         section.title = wldoc.book_info.title
51         section.save()
52
53         section.lesson_set.all().update(section=None)
54         for i, lesson in enumerate(lessons):
55             lesson.section = section
56             lesson.order = i
57             lesson.save()
58
59         return section
60
61     def syntetic_lesson(self, level):
62         try:
63             return self.lesson_set.filter(type='synthetic', level=level)[0]
64         except IndexError:
65             return None
66
67
68 class Lesson(models.Model):
69     section = models.ForeignKey(Section, null=True, blank=True)
70     level = models.ForeignKey(Level)
71     title = models.CharField(max_length=255)
72     slug = models.SlugField(max_length=255, unique=True)
73     type = models.CharField(max_length=15, db_index=True)
74     order = models.IntegerField(db_index=True)
75     dc = JSONField(default='{}')
76     curriculum_courses = models.ManyToManyField(CurriculumCourse, blank=True)
77
78     xml_file = models.FileField(upload_to="catalogue/lesson/xml",
79         null=True, blank=True, max_length=255)
80     html_file = models.FileField(upload_to="catalogue/lesson/html",
81         null=True, blank=True, max_length=255)
82     package = models.FileField(upload_to="catalogue/lesson/pack",
83         null=True, blank=True, max_length=255)
84     student_package = models.FileField(upload_to="catalogue/lesson/student_pack",
85         null=True, blank=True, max_length=255)
86     pdf = models.FileField(upload_to="catalogue/lesson/pdf",
87         null=True, blank=True, max_length=255)
88     student_pdf = models.FileField(upload_to="catalogue/lesson/student_pdf",
89         null=True, blank=True, max_length=255)
90
91     class Meta:
92         ordering = ['section', 'level', 'order']
93
94     def __unicode__(self):
95         return self.title
96
97     @models.permalink
98     def get_absolute_url(self):
99         return ('catalogue_lesson', [self.slug])
100
101     @classmethod
102     def publish(cls, infile):
103         from librarian.parser import WLDocument
104         from django.core.files.base import ContentFile
105         xml = infile.get_string()
106         wldoc = WLDocument.from_string(xml)
107
108         # Check if not section metadata block.
109         if wldoc.book_info.parts:
110             return Section.publish(infile)
111         
112         slug = wldoc.book_info.url.slug
113         try:
114             lesson = cls.objects.get(slug=slug)
115             lesson.attachment_set.all().delete()
116         except cls.DoesNotExist:
117             lesson = cls(slug=slug, order=0)
118
119         # Save XML file
120         lesson.xml_file.save('%s.xml' % slug, ContentFile(xml), save=False)
121         lesson.title = wldoc.book_info.title
122
123         lesson.level = Level.objects.get(slug=wldoc.book_info.audience)
124         lesson.populate_dc()
125         lesson.build_html(infile=infile)
126         lesson.build_pdf(infile=infile)
127         lesson.build_pdf(student=True, infile=infile)
128         lesson.build_package()
129         lesson.build_package(student=True)
130         return lesson
131
132     def populate_dc(self):
133         from librarian.parser import WLDocument
134         wldoc = WLDocument.from_file(self.xml_file.path)
135         self.dc = wldoc.book_info.to_dict()
136         self.type = self.dc["type"]
137         self.save()
138
139         courses = set()
140         for identifier in wldoc.book_info.curriculum:
141             try:
142                 curr = Curriculum.objects.get(identifier=identifier)
143             except Curriculum.DoesNotExist:
144                 pass
145             else:
146                 courses.add(curr.course)
147         self.curriculum_courses = courses
148
149     def wldocument(self, infile=None):
150         from librarian import IOFile
151         from librarian.parser import WLDocument
152         from .publish import OrmDocProvider
153
154         if infile is None:
155             infile = IOFile.from_filename(self.xml_file.path)
156             for att in self.attachment_set.all():
157                 infile.attachments["%s.%s" % (att.slug, att.ext)] = \
158                     IOFile.from_filename(att.file.path)
159         return WLDocument(infile, provider=OrmDocProvider())
160
161     def build_html(self, infile=None):
162         from .publish import HtmlFormat
163         wldoc = self.wldocument(infile)
164         html = HtmlFormat(wldoc).build()
165         self.html_file.save("%s.html" % self.slug,
166             File(open(html.get_filename())))
167
168     def build_pdf(self, student=False, infile=None):
169         from .publish import PdfFormat
170         wldoc = self.wldocument(infile)
171         if student:
172             pdf = PdfFormat(wldoc).build()
173             self.student_pdf.save("%s.pdf" % self.slug,
174                 File(open(pdf.get_filename())))
175         else:
176             pdf = PdfFormat(wldoc, teacher=True).build()
177             self.pdf.save("%s.pdf" % self.slug,
178                 File(open(pdf.get_filename())))
179
180     def add_to_zip(self, zipf, student=False, prefix=''):
181         zipf.write(self.xml_file.path,
182             "%spliki-zrodlowe/%s.xml" % (prefix, self.slug))
183         pdf = self.student_pdf if student else self.pdf
184         if pdf:
185             zipf.write(pdf.path, 
186                 "%s%s%s.pdf" % (prefix, self.slug, "_student" if student else ""))
187         for attachment in self.attachment_set.all():
188             zipf.write(attachment.file.path,
189                 u"%smaterialy/%s.%s" % (prefix, attachment.slug, attachment.ext))
190             
191         
192
193     def build_package(self, student=False):
194         from StringIO import StringIO
195         import zipfile
196         from django.core.files.base import ContentFile
197         buff = StringIO()
198         zipf = zipfile.ZipFile(buff, 'w', zipfile.ZIP_STORED)
199         self.add_to_zip(zipf, student)
200         zipf.close()
201         fieldname = "student_package" if student else "package"
202         getattr(self, fieldname).save(
203             "%s%s.zip" % (self.slug, "_student" if student else ""),
204             ContentFile(buff.getvalue()))
205
206     def get_syntetic(self):
207         if self.section is None: return None
208         return self.section.syntetic_lesson(self.level)
209
210     def get_other_level(self):
211         if self.section is None: return None
212         other_levels = self.section.lesson_set.exclude(level=self.level)
213         if other_levels.exists():
214             return other_levels[0].level
215
216     def get_previous(self):
217         if self.section is None: return None
218         try:
219             return self.section.lesson_set.filter(
220                 type=self.type, level=self.level,
221                 order__lt=self.order).order_by('-order')[0]
222         except IndexError:
223             return None
224
225     def get_next(self):
226         if self.section is None: return None
227         try:
228             return self.section.lesson_set.filter(
229                 type=self.type, level=self.level,
230                 order__gt=self.order).order_by('order')[0]
231         except IndexError:
232             return None
233
234
235 class Attachment(models.Model):
236     slug = models.CharField(max_length=255)
237     ext = models.CharField(max_length=15)
238     lesson = models.ForeignKey(Lesson)
239     file = models.FileField(upload_to="catalogue/attachment")
240
241     class Meta:
242         ordering = ['slug', 'ext']
243         unique_together = ['lesson', 'slug', 'ext']
244
245     def __unicode__(self):
246         return "%s.%s" % (self.slug, self.ext)
247
248
249 class Part(models.Model):
250     lesson = models.ForeignKey(Lesson)
251     pdf = models.FileField(upload_to="catalogue/part/pdf",
252         null=True, blank=True)
253     student_pdf = models.FileField(upload_to="catalogue/part/student_pdf",
254         null=True, blank=True)
255
256
257 class LessonStub(models.Model):
258     section = models.ForeignKey(Section, null=True, blank=True)
259     level = models.ForeignKey(Level)
260     title = models.CharField(max_length=255)
261     type = models.CharField(max_length=15, db_index=True)
262     order = models.IntegerField(db_index=True)
263
264     class Meta:
265         ordering = ['section', 'level', 'order']
266
267     def __unicode__(self):
268         return self.title