f79a80983eebde1aa1ef1cb8e20dff28269cface
[edumed.git] / catalogue / publish.py
1 # -*- coding: utf-8
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
7
8
9 class HtmlFormat(EduModuleFormat):
10     def find_attachment(self, slug, fmt):
11         lesson_slug = self.wldoc.book_info.url.slug
12         try:
13             # If already saved, use it.
14             att = Attachment.objects.get(lesson__slug=lesson_slug,
15                                          slug=slug, ext=fmt)
16         except Attachment.DoesNotExist, e:
17             # If attached to source IOFile, save now.
18             att_name = "%s.%s" % (slug, fmt)
19             try:
20                 att_file = self.wldoc.source.attachments[att_name]
21             except KeyError:
22                 print u"ATTACHMENT MISSING:", att_name
23                 raise self.MaterialNotFound()
24             else:
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()))
28                 return att
29         else:
30             return att
31
32     def url_for_material(self, slug, fmt):
33         return self.find_attachment(slug, fmt).file.url
34
35     def url_for_image(self, slug, fmt, width=None):
36         if width is None:
37             return self.url_for_material(slug, fmt)
38
39         lesson_slug = self.wldoc.book_info.url.slug
40         th_slug = "thumb/%s__th%d" % (slug, width)
41         try:
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:
46             from PIL import Image
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)
53
54             tempfile = StringIO()
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()))
61         return att.file.url
62
63
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)