Merge branch 'production'
[wolnelektury.git] / apps / dictionary / models.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from django.db import models
6 from celery.task import task
7 from sortify import sortify
8
9 from catalogue.models import Book
10
11
12 class Note(models.Model):
13     """Represents a single annotation from a book."""
14     book = models.ForeignKey(Book)
15     anchor = models.CharField(max_length=64)
16     html = models.TextField()
17     sort_key = models.CharField(max_length=128, db_index=True)
18
19     class Meta:
20         ordering = ['sort_key']
21
22
23 @task(ignore_result=True)
24 def build_notes(book_id):
25     book = Book.objects.get(pk=book_id)
26     Note.objects.filter(book=book).delete()
27     if book.html_file:
28         from librarian import html
29         for anchor, text_str, html_str in html.extract_annotations(book.html_file.path):
30             Note.objects.create(book=book, anchor=anchor,
31                                html=html_str, 
32                                sort_key=sortify(text_str).strip()[:128])
33     
34 @Book.html_built.connect
35 def notes_from_book(sender, **kwargs):
36     build_notes.delat(sender)