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