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 .models import Lesson, Attachment
9 class HtmlFormat(EduModuleFormat):
10 def find_attachment(self, slug, fmt):
11 lesson_slug = self.wldoc.book_info.url.slug
13 # If already saved, use it.
14 att = Attachment.objects.get(lesson__slug=lesson_slug,
16 except Attachment.DoesNotExist, e:
17 # If attached to source IOFile, save now.
18 att_name = "%s.%s" % (slug, fmt)
20 att_file = self.wldoc.source.attachments[att_name]
22 print u"ATTACHMENT MISSING:", att_name
23 raise self.MaterialNotFound()
25 lesson = Lesson.objects.get(slug=lesson_slug)
26 att = lesson.attachment_set.create(slug=slug, ext=fmt)
27 att.file.save(att_name, File(att_file.get_file()))
32 def url_for_material(self, slug, fmt):
33 return self.find_attachment(slug, fmt).file.url
35 def url_for_image(self, slug, fmt, width=None):
37 return self.url_for_material(slug, fmt)
39 lesson_slug = self.wldoc.book_info.url.slug
40 th_slug = "thumb/%s__th%d" % (slug, width)
42 # If already saved, use it.
43 att = Attachment.objects.get(lesson__slug=lesson_slug,
44 slug=th_slug, ext=fmt)
45 except Attachment.DoesNotExist, e:
47 from StringIO import StringIO
48 # Find full image, create thumbnail, save.
49 src_att = self.find_attachment(slug, fmt)
50 simg = Image.open(src_att.file.path)
51 size = (width, simg.size[1]*width/simg.size[0])
52 simg = simg.resize(size, Image.ANTIALIAS)
55 img_format = "JPEG" if fmt.upper() == "JPG" else fmt
56 simg.save(tempfile, format=img_format)
57 att_name = "%s.%s" % (th_slug, fmt)
58 lesson = Lesson.objects.get(slug=lesson_slug)
59 att = lesson.attachment_set.create(slug=th_slug, ext=fmt)
60 att.file.save(att_name, ContentFile(tempfile.getvalue()))
64 class OrmDocProvider(DocProvider):
65 def by_slug(self, slug):
66 """Should return a file-like object with a WL document XML."""
67 return IOFile.from_filename(Lesson.objects.get(slug=slug).xml_file.path)