2 from django.core.files.base import ContentFile
3 from django.core.files import File
4 from librarian import DocProvider, IOFile
5 from librarian.pyhtml import EduModuleFormat
6 from librarian.pypdf import EduModulePDFFormat
7 from .models import Lesson, Attachment
10 class HtmlFormat(EduModuleFormat):
11 def find_attachment(self, slug, fmt):
12 lesson_slug = self.wldoc.book_info.url.slug
14 # If already saved, use it.
15 att = Attachment.objects.get(lesson__slug=lesson_slug,
17 except Attachment.DoesNotExist, e:
18 # If attached to source IOFile, save now.
19 att_name = "%s.%s" % (slug, fmt)
21 att_file = self.wldoc.source.attachments[att_name]
23 print u"ATTACHMENT MISSING:", att_name
24 raise self.MaterialNotFound()
26 lesson = Lesson.objects.get(slug=lesson_slug)
27 att = lesson.attachment_set.create(slug=slug, ext=fmt)
28 att.file.save(att_name, File(att_file.get_file()))
33 def url_for_material(self, slug, fmt):
34 return self.find_attachment(slug, fmt).file.url
36 def url_for_image(self, slug, fmt, width=None):
38 return self.url_for_material(slug, fmt)
40 lesson_slug = self.wldoc.book_info.url.slug
41 th_slug = "thumb/%s__th%d" % (slug, width)
43 # If already saved, use it.
44 att = Attachment.objects.get(lesson__slug=lesson_slug,
45 slug=th_slug, ext=fmt)
46 except Attachment.DoesNotExist, e:
48 from StringIO import StringIO
49 # Find full image, create thumbnail, save.
50 src_att = self.find_attachment(slug, fmt)
51 simg = Image.open(src_att.file.path)
52 size = (width, simg.size[1]*width/simg.size[0])
53 simg = simg.resize(size, Image.ANTIALIAS)
56 img_format = "JPEG" if fmt.upper() == "JPG" else fmt
57 simg.save(tempfile, format=img_format)
58 att_name = "%s.%s" % (th_slug, fmt)
59 lesson = Lesson.objects.get(slug=lesson_slug)
60 att = lesson.attachment_set.create(slug=th_slug, ext=fmt)
61 att.file.save(att_name, ContentFile(tempfile.getvalue()))
64 class PdfFormat(EduModulePDFFormat):
68 class OrmDocProvider(DocProvider):
69 def by_slug(self, slug):
70 """Should return a file-like object with a WL document XML."""
71 return IOFile.from_filename(Lesson.objects.get(slug=slug).xml_file.path)