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