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
10 bofh_storage = BofhFileSystemStorage()
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(
18 upload_to="catalogue/section/xml",
19 null=True, blank=True, max_length=255,
21 image = models.ImageField(upload_to="catalogue/section/image", null=True, blank=True)
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)
27 summary = models.TextField(blank=True, null=True)
32 class IncompleteError(BaseException):
35 def __unicode__(self):
38 def get_absolute_url(self):
39 return "%s#gimnazjum_%s" % (reverse("catalogue_lessons"), self.slug)
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)
49 for part in wldoc.book_info.parts:
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)
56 slug = wldoc.book_info.url.slug
58 section = cls.objects.get(slug=slug)
59 except cls.DoesNotExist:
60 section = cls(slug=slug, order=0)
63 section.xml_file.save('%s.xml' % slug, ContentFile(xml), save=False)
64 section.title = wldoc.book_info.title
67 section.lesson_set.all().update(section=None)
68 for i, lesson in enumerate(lessons):
69 lesson.section = section
75 def syntetic_lesson(self, level):
77 return self.lesson_set.filter(type='synthetic', level=level)[0]
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)
93 xml_file = models.FileField(
94 upload_to="catalogue/lesson/xml",
95 null=True, blank=True, max_length=255, storage=bofh_storage)
96 html_file = models.FileField(
97 upload_to="catalogue/lesson/html",
98 null=True, blank=True, max_length=255, storage=bofh_storage)
99 package = models.FileField(
100 upload_to="catalogue/lesson/pack",
101 null=True, blank=True, max_length=255, storage=bofh_storage)
102 student_package = models.FileField(
103 upload_to="catalogue/lesson/student_pack",
104 null=True, blank=True, max_length=255, storage=bofh_storage)
105 pdf = models.FileField(
106 upload_to="catalogue/lesson/pdf",
107 null=True, blank=True, max_length=255, storage=bofh_storage)
108 student_pdf = models.FileField(
109 upload_to="catalogue/lesson/student_pdf",
110 null=True, blank=True, max_length=255, storage=bofh_storage)
113 ordering = ['section', 'level', 'order']
115 def __unicode__(self):
119 def get_absolute_url(self):
120 return 'catalogue_lesson', [self.slug]
123 def publish(cls, infile, ignore_incomplete=False):
124 from librarian.parser import WLDocument
125 from django.core.files.base import ContentFile
126 xml = infile.get_string()
127 wldoc = WLDocument.from_string(xml)
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(xml), 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 populate_dc(self):
156 from librarian.parser import WLDocument
157 wldoc = WLDocument.from_file(self.xml_file.path)
158 self.dc = wldoc.book_info.to_dict()
159 self.type = self.dc["type"]
160 assert self.type in ('appendix', 'course', 'synthetic', 'project', 'added', 'added-var'), \
161 u"Unknown lesson type: %s" % self.type
165 for identifier in wldoc.book_info.curriculum:
166 identifier = (identifier or "").replace(' ', '')
170 curr = Curriculum.objects.get(identifier__iexact=identifier)
171 except Curriculum.DoesNotExist:
172 logging.warn('Unknown curriculum course %s in lesson %s' % (identifier, self.slug))
175 courses.add(curr.course)
176 self.curriculum_courses = courses
178 def populate_description(self, wldoc=None, infile=None):
180 wldoc = self.wldocument(infile)
181 if self.type == 'project':
184 lookup = u'Pomysł na lekcję'
185 for header in wldoc.edoc.findall('.//naglowek_rozdzial'):
186 if (header.text or '').strip() == lookup:
187 from lxml import etree
188 self.description = etree.tostring(
189 header.getnext(), method='text', encoding='unicode').strip()
193 def wldocument(self, infile=None):
194 from librarian import IOFile
195 from librarian.parser import WLDocument
196 from .publish import OrmDocProvider
199 infile = IOFile.from_filename(self.xml_file.path)
200 for att in self.attachment_set.all():
201 infile.attachments["%s.%s" % (att.slug, att.ext)] = \
202 IOFile.from_filename(att.file.path)
203 return WLDocument(infile, provider=OrmDocProvider())
205 def build_html(self, infile=None):
206 from .publish import HtmlFormat
207 wldoc = self.wldocument(infile)
208 html = HtmlFormat(wldoc).build()
209 self.html_file.save("%s.html" % self.slug, File(open(html.get_filename())))
211 def build_pdf(self, student=False):
212 from .publish import PdfFormat
213 # PDF uses document with attachments already saved as media,
214 # otherwise sorl.thumbnail complains about SuspiciousOperations.
215 wldoc = self.wldocument()
217 pdf = PdfFormat(wldoc).build()
218 self.student_pdf.save("%s.pdf" % self.slug, File(open(pdf.get_filename())))
220 pdf = PdfFormat(wldoc, teacher=True).build()
221 self.pdf.save("%s.pdf" % self.slug, File(open(pdf.get_filename())))
223 def add_to_zip(self, zipf, student=False, prefix=''):
224 pdf = self.student_pdf if student else self.pdf
226 zipf.write(pdf.path, "%s%s%s.pdf" % (prefix, self.slug, "_student" if student else ""))
227 for attachment in self.attachment_set.all():
228 zipf.write(attachment.file.path, u"%smaterialy/%s.%s" % (prefix, attachment.slug, attachment.ext))
229 zipf.write(self.xml_file.path, "%spliki-zrodlowe/%s.xml" % (prefix, self.slug))
231 def build_package(self, student=False):
232 from StringIO import StringIO
234 from django.core.files.base import ContentFile
236 zipf = zipfile.ZipFile(buff, 'w', zipfile.ZIP_STORED)
237 self.add_to_zip(zipf, student)
239 fieldname = "student_package" if student else "package"
240 getattr(self, fieldname).save(
241 "%s%s.zip" % (self.slug, "_student" if student else ""),
242 ContentFile(buff.getvalue()))
244 def get_syntetic(self):
245 if self.section is None:
247 return self.section.syntetic_lesson(self.level)
249 def get_other_level(self):
250 if self.section is None:
252 other_levels = self.section.lesson_set.exclude(level=self.level)
253 if other_levels.exists():
254 return other_levels[0].level
256 def get_previous(self):
257 if self.section is None:
260 return self.section.lesson_set.filter(
261 type=self.type, level=self.level,
262 order__lt=self.order).order_by('-order')[0]
267 if self.section is None:
270 return self.section.lesson_set.filter(
271 type=self.type, level=self.level,
272 order__gt=self.order).order_by('order')[0]
276 def requires_internet(self):
277 return 'internet' in self.dc.get('requires', [])
280 class Attachment(models.Model):
281 slug = models.CharField(max_length=255)
282 ext = models.CharField(max_length=15)
283 lesson = models.ForeignKey(Lesson)
284 file = models.FileField(upload_to="catalogue/attachment", storage=bofh_storage)
287 ordering = ['slug', 'ext']
288 unique_together = ['lesson', 'slug', 'ext']
290 def __unicode__(self):
291 return "%s.%s" % (self.slug, self.ext)
294 class Part(models.Model):
295 lesson = models.ForeignKey(Lesson)
296 pdf = models.FileField(upload_to="catalogue/part/pdf", null=True, blank=True)
297 student_pdf = models.FileField(upload_to="catalogue/part/student_pdf", null=True, blank=True)
300 class LessonStub(models.Model):
301 section = models.ForeignKey(Section, null=True, blank=True)
302 level = models.ForeignKey(Level)
303 title = models.CharField(max_length=255)
304 type = models.CharField(max_length=15, db_index=True)
305 order = models.IntegerField(db_index=True)
308 ordering = ['section', 'level', 'order']
310 def __unicode__(self):
317 def add_to_zip(self, *args, **kwargs):