Fixes for woblink.
[redakcja.git] / src / alerts / models.py
1 from django.db import models
2 from django.dispatch import receiver
3 from dvcs.models import post_commit
4 from .rules import rules, rules_by_tag
5
6
7 class Alert(models.Model):
8     book = models.ForeignKey('documents.Book', models.CASCADE)
9     tag = models.CharField(max_length=32)
10     comment = models.TextField(blank=True)
11
12     def get_absolute_url(self):
13         return self.book.get_absolute_url()
14
15     @property
16     def rule(self):
17         return rules_by_tag[self.tag]
18
19     @classmethod
20     def validate_book(cls, book):
21         cls.objects.filter(book=book).delete()
22         try:
23             wlbook = book.wldocument(publishable=False, librarian2=True)
24         except Exception as e:
25             cls.objects.create(book=book, tag='parse', comment=str(e))
26             return
27
28         try:
29             meta = wlbook.meta
30         except Exception as e:
31             cls.objects.create(book=book, tag='meta', comment=str(e))
32             return
33         
34         for rule in rules:
35             if rule.check_meta(meta):
36                 print(rule.tag, book)
37                 cls.objects.create(book=book, tag=rule.tag)
38
39
40 @receiver(post_commit)
41 def validate_post_commit(sender, **kwargs):
42     if hasattr(sender.tree, 'book'):
43         Alert.validate_book(sender.tree.book)