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
8 from curriculum.models import Level, Curriculum, CurriculumCourse
11 bofh_storage = BofhFileSystemStorage()
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,
22 image = models.ImageField(upload_to="catalogue/section/image", null=True, blank=True)
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)
28 summary = models.TextField(blank=True, null=True)
33 class IncompleteError(BaseException):
36 def __unicode__(self):
39 def get_absolute_url(self):
40 return "%s#gimnazjum_%s" % (reverse("catalogue_lessons"), self.slug)
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)
50 for part in wldoc.book_info.parts:
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)
57 slug = wldoc.book_info.url.slug
59 section = cls.objects.get(slug=slug)
60 except cls.DoesNotExist:
61 section = cls(slug=slug, order=0)
64 section.xml_file.save('%s.xml' % slug, ContentFile(xml), save=False)
65 section.title = wldoc.book_info.title
68 section.lesson_set.all().update(section=None)
69 for i, lesson in enumerate(lessons):
70 lesson.section = section
76 def syntetic_lesson(self, level):
78 return self.lesson_set.filter(type='synthetic', level=level)[0]
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)
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)
114 ordering = ['section', 'level', 'order']
116 def __unicode__(self):
120 def get_absolute_url(self):
121 return 'catalogue_lesson', [self.slug]
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)
129 # Check if not section metadata block.
130 if wldoc.book_info.parts:
131 return Section.publish(infile, ignore_incomplete=ignore_incomplete)
133 slug = wldoc.book_info.url.slug
135 lesson = cls.objects.get(slug=slug)
136 lesson.attachment_set.all().delete()
137 except cls.DoesNotExist:
138 lesson = cls(slug=slug, order=0)
141 lesson.xml_file.save('%s.xml' % slug, ContentFile(infile.get_string()), save=False)
142 lesson.title = wldoc.book_info.title
144 lesson.level = Level.objects.get(meta_name=wldoc.book_info.audience)
146 lesson.populate_description(wldoc=wldoc)
147 lesson.build_html(infile=infile)
149 lesson.build_package()
150 if lesson.type != 'project':
151 lesson.build_pdf(student=True)
152 lesson.build_package(student=True)
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)
160 self.level.build_packages()
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
172 for identifier in wldoc.book_info.curriculum:
173 identifier = (identifier or "").replace(' ', '')
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))
182 courses.add(curr.course)
183 self.curriculum_courses = courses
185 def populate_description(self, wldoc=None, infile=None):
187 wldoc = self.wldocument(infile)
188 if self.type == 'project':
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()
200 def wldocument(self, infile=None):
201 from librarian import IOFile
202 from librarian.parser import WLDocument
203 from .publish import OrmDocProvider
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())
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())))
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()
224 pdf = PdfFormat(wldoc).build()
225 self.student_pdf.save("%s.pdf" % self.slug, File(open(pdf.get_filename())))
227 pdf = PdfFormat(wldoc, teacher=True).build()
228 self.pdf.save("%s.pdf" % self.slug, File(open(pdf.get_filename())))
230 def add_to_zip(self, zipf, student=False, prefix=''):
231 pdf = self.student_pdf if student else self.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))
238 def build_package(self, student=False):
239 from StringIO import StringIO
241 from django.core.files.base import ContentFile
243 zipf = zipfile.ZipFile(buff, 'w', zipfile.ZIP_STORED)
244 self.add_to_zip(zipf, student)
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()))
251 def get_syntetic(self):
252 if self.section is None:
254 return self.section.syntetic_lesson(self.level)
256 def get_other_level(self):
257 if self.section is None:
259 other_levels = self.section.lesson_set.exclude(level=self.level)
260 if other_levels.exists():
261 return other_levels[0].level
263 def get_previous(self):
264 if self.section is None:
267 return self.section.lesson_set.filter(
268 type=self.type, level=self.level,
269 order__lt=self.order).order_by('-order')[0]
274 if self.section is None:
277 return self.section.lesson_set.filter(
278 type=self.type, level=self.level,
279 order__gt=self.order).order_by('order')[0]
283 def requires_internet(self):
284 return 'internet' in self.dc.get('requires', [])
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)
294 ordering = ['slug', 'ext']
295 unique_together = ['lesson', 'slug', 'ext']
297 def __unicode__(self):
298 return "%s.%s" % (self.slug, self.ext)
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)
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)
315 ordering = ['section', 'level', 'order']
317 def __unicode__(self):
324 def add_to_zip(self, *args, **kwargs):