85f0af08d998d721c201274086df141d33b30550
[edumed.git] / catalogue / models.py
1 # -*- coding: utf-8
2 from django.core.files import File
3 from django.core.urlresolvers import reverse
4 from django.db import models
5 from jsonfield import JSONField
6 from fnpdjango.storage import BofhFileSystemStorage
7 from curriculum.models import Level, Curriculum, CurriculumCourse
8 import logging
9
10 bofh_storage = BofhFileSystemStorage()
11
12
13 class Section(models.Model):
14     title = models.CharField(max_length=255, unique=True)
15     slug = models.SlugField(max_length=255, unique=True)
16     order = models.IntegerField()
17     xml_file = models.FileField(upload_to="catalogue/section/xml",
18         null=True, blank=True, max_length=255,
19         storage=bofh_storage)
20     image = models.ImageField(upload_to="catalogue/section/image",
21         null=True, blank=True)
22
23     pic = models.ImageField(upload_to="catalogue/section/pic", null=True, blank=True)
24     pic_attribution = models.CharField(max_length=255, null=True, blank=True)
25     pic_src = models.URLField(null=True, blank=True)
26     
27     summary = models.TextField(blank=True, null=True)
28
29     class Meta:
30         ordering = ['order']
31
32     class IncompleteError(BaseException):
33         pass
34
35     def __unicode__(self):
36         return self.title
37
38     def get_absolute_url(self):
39         return "%s#gimnazjum_%s" % (reverse("catalogue_lessons"), self.slug)
40
41     @classmethod
42     def publish(cls, infile, ignore_incomplete=False):
43         from librarian.parser import WLDocument
44         from django.core.files.base import ContentFile
45         xml = infile.get_string()
46         wldoc = WLDocument.from_string(xml)
47
48         lessons = []
49         for part in wldoc.book_info.parts:
50             try:
51                 lessons.append(Lesson.objects.get(slug=part.slug))
52             except Lesson.DoesNotExist, e:
53                 if not ignore_incomplete:
54                     raise cls.IncompleteError(part.slug)
55
56         slug = wldoc.book_info.url.slug
57         try:
58             section = cls.objects.get(slug=slug)
59         except cls.DoesNotExist:
60             section = cls(slug=slug, order=0)
61
62         # Save XML file
63         section.xml_file.save('%s.xml' % slug, ContentFile(xml), save=False)
64         section.title = wldoc.book_info.title
65         section.save()
66
67         section.lesson_set.all().update(section=None)
68         for i, lesson in enumerate(lessons):
69             lesson.section = section
70             lesson.order = i
71             lesson.save()
72
73         return section
74
75     def syntetic_lesson(self, level):
76         try:
77             return self.lesson_set.filter(type='synthetic', level=level)[0]
78         except IndexError:
79             return None
80
81
82 class Lesson(models.Model):
83     section = models.ForeignKey(Section, null=True, blank=True)
84     level = models.ForeignKey(Level)
85     title = models.CharField(max_length=255)
86     slug = models.SlugField(max_length=255, unique=True)
87     type = models.CharField(max_length=15, db_index=True)
88     order = models.IntegerField(db_index=True)
89     dc = JSONField(default='{}')
90     curriculum_courses = models.ManyToManyField(CurriculumCourse, blank=True)
91     description = models.TextField(null=True, blank=True)
92
93     xml_file = models.FileField(upload_to="catalogue/lesson/xml",
94         null=True, blank=True, max_length=255, storage=bofh_storage)
95     html_file = models.FileField(upload_to="catalogue/lesson/html",
96         null=True, blank=True, max_length=255, storage=bofh_storage)
97     package = models.FileField(upload_to="catalogue/lesson/pack",
98         null=True, blank=True, max_length=255, storage=bofh_storage)
99     student_package = models.FileField(upload_to="catalogue/lesson/student_pack",
100         null=True, blank=True, max_length=255, storage=bofh_storage)
101     pdf = models.FileField(upload_to="catalogue/lesson/pdf",
102         null=True, blank=True, max_length=255, storage=bofh_storage)
103     student_pdf = models.FileField(upload_to="catalogue/lesson/student_pdf",
104         null=True, blank=True, max_length=255, storage=bofh_storage)
105
106     class Meta:
107         ordering = ['section', 'level', 'order']
108
109     def __unicode__(self):
110         return self.title
111
112     @models.permalink
113     def get_absolute_url(self):
114         return ('catalogue_lesson', [self.slug])
115
116     @classmethod
117     def publish(cls, infile, ignore_incomplete=False):
118         from librarian.parser import WLDocument
119         from django.core.files.base import ContentFile
120         xml = infile.get_string()
121         wldoc = WLDocument.from_string(xml)
122
123         # Check if not section metadata block.
124         if wldoc.book_info.parts:
125             return Section.publish(infile, ignore_incomplete=ignore_incomplete)
126
127         slug = wldoc.book_info.url.slug
128         try:
129             lesson = cls.objects.get(slug=slug)
130             lesson.attachment_set.all().delete()
131         except cls.DoesNotExist:
132             lesson = cls(slug=slug, order=0)
133
134         # Save XML file
135         lesson.xml_file.save('%s.xml' % slug, ContentFile(xml), save=False)
136         lesson.title = wldoc.book_info.title
137
138         lesson.level = Level.objects.get(meta_name=wldoc.book_info.audience)
139         lesson.populate_dc()
140         lesson.populate_description(wldoc=wldoc)
141         lesson.build_html(infile=infile)
142         lesson.build_pdf()
143         lesson.build_package()
144         if lesson.type != 'project':
145             lesson.build_pdf(student=True)
146             lesson.build_package(student=True)
147         return lesson
148
149     def populate_dc(self):
150         from librarian.parser import WLDocument
151         wldoc = WLDocument.from_file(self.xml_file.path)
152         self.dc = wldoc.book_info.to_dict()
153         self.type = self.dc["type"]
154         assert self.type in ('appendix', 'course', 'synthetic', 'project', 'added', 'added-var'), \
155             u"Unknown lesson type: %s" % self.type
156         self.save()
157
158         courses = set()
159         for identifier in wldoc.book_info.curriculum:
160             identifier = (identifier or "").replace(' ', '')
161             if not identifier: continue
162             try:
163                 curr = Curriculum.objects.get(identifier__iexact=identifier)
164             except Curriculum.DoesNotExist:
165                 logging.warn('Unknown curriculum course %s in lesson %s' % (identifier, self.slug))
166                 pass
167             else:
168                 courses.add(curr.course)
169         self.curriculum_courses = courses
170
171     def populate_description(self, wldoc=None, infile=None):
172         if wldoc is None:
173             wldoc = self.wldocument(infile)
174         if self.type == 'project':
175             lookup = u'Zadanie'
176         else:
177             lookup = u'Pomysł na lekcję'
178         for header in wldoc.edoc.findall('.//naglowek_rozdzial'):
179             if (header.text or '').strip() == lookup:
180                 from lxml import etree
181                 self.description = etree.tostring(header.getnext(),
182                         method='text', encoding='unicode').strip()
183                 self.save()
184                 return
185
186     def wldocument(self, infile=None):
187         from librarian import IOFile
188         from librarian.parser import WLDocument
189         from .publish import OrmDocProvider
190
191         if infile is None:
192             infile = IOFile.from_filename(self.xml_file.path)
193             for att in self.attachment_set.all():
194                 infile.attachments["%s.%s" % (att.slug, att.ext)] = \
195                     IOFile.from_filename(att.file.path)
196         return WLDocument(infile, provider=OrmDocProvider())
197
198     def build_html(self, infile=None):
199         from .publish import HtmlFormat
200         wldoc = self.wldocument(infile)
201         html = HtmlFormat(wldoc).build()
202         self.html_file.save("%s.html" % self.slug,
203             File(open(html.get_filename())))
204
205     def build_pdf(self, student=False):
206         from .publish import PdfFormat
207         # PDF uses document with attachments already saved as media,
208         # otherwise sorl.thumbnail complains about SuspiciousOperations.
209         wldoc = self.wldocument()
210         if student:
211             pdf = PdfFormat(wldoc).build()
212             self.student_pdf.save("%s.pdf" % self.slug,
213                 File(open(pdf.get_filename())))
214         else:
215             pdf = PdfFormat(wldoc, teacher=True).build()
216             self.pdf.save("%s.pdf" % self.slug,
217                 File(open(pdf.get_filename())))
218
219     def add_to_zip(self, zipf, student=False, prefix=''):
220         pdf = self.student_pdf if student else self.pdf
221         if pdf:
222             zipf.write(pdf.path, 
223                 "%s%s%s.pdf" % (prefix, self.slug, "_student" if student else ""))
224             for attachment in self.attachment_set.all():
225                 zipf.write(attachment.file.path,
226                     u"%smaterialy/%s.%s" % (prefix, attachment.slug, attachment.ext))
227             zipf.write(self.xml_file.path,
228                 "%spliki-zrodlowe/%s.xml" % (prefix, self.slug))
229
230     def build_package(self, student=False):
231         from StringIO import StringIO
232         import zipfile
233         from django.core.files.base import ContentFile
234         buff = StringIO()
235         zipf = zipfile.ZipFile(buff, 'w', zipfile.ZIP_STORED)
236         self.add_to_zip(zipf, student)
237         zipf.close()
238         fieldname = "student_package" if student else "package"
239         getattr(self, fieldname).save(
240             "%s%s.zip" % (self.slug, "_student" if student else ""),
241             ContentFile(buff.getvalue()))
242
243     def get_syntetic(self):
244         if self.section is None: return None
245         return self.section.syntetic_lesson(self.level)
246
247     def get_other_level(self):
248         if self.section is None: return None
249         other_levels = self.section.lesson_set.exclude(level=self.level)
250         if other_levels.exists():
251             return other_levels[0].level
252
253     def get_previous(self):
254         if self.section is None: return None
255         try:
256             return self.section.lesson_set.filter(
257                 type=self.type, level=self.level,
258                 order__lt=self.order).order_by('-order')[0]
259         except IndexError:
260             return None
261
262     def get_next(self):
263         if self.section is None: return None
264         try:
265             return self.section.lesson_set.filter(
266                 type=self.type, level=self.level,
267                 order__gt=self.order).order_by('order')[0]
268         except IndexError:
269             return None
270
271     def requires_internet(self):
272         return 'internet' in self.dc.get('requires', [])
273
274
275 class Attachment(models.Model):
276     slug = models.CharField(max_length=255)
277     ext = models.CharField(max_length=15)
278     lesson = models.ForeignKey(Lesson)
279     file = models.FileField(upload_to="catalogue/attachment", storage=bofh_storage)
280
281     class Meta:
282         ordering = ['slug', 'ext']
283         unique_together = ['lesson', 'slug', 'ext']
284
285     def __unicode__(self):
286         return "%s.%s" % (self.slug, self.ext)
287
288
289 class Part(models.Model):
290     lesson = models.ForeignKey(Lesson)
291     pdf = models.FileField(upload_to="catalogue/part/pdf",
292         null=True, blank=True)
293     student_pdf = models.FileField(upload_to="catalogue/part/student_pdf",
294         null=True, blank=True)
295
296
297 class LessonStub(models.Model):
298     section = models.ForeignKey(Section, null=True, blank=True)
299     level = models.ForeignKey(Level)
300     title = models.CharField(max_length=255)
301     type = models.CharField(max_length=15, db_index=True)
302     order = models.IntegerField(db_index=True)
303
304     class Meta:
305         ordering = ['section', 'level', 'order']
306
307     def __unicode__(self):
308         return self.title
309
310     @property
311     def slug(self):
312         return ''
313
314     def add_to_zip(self, *args, **kwargs):
315         pass