legimi fix
[redakcja.git] / src / depot / publishers / legimi.py
index c7fa26d..6802d14 100644 (file)
@@ -6,6 +6,7 @@ from django.utils.safestring import mark_safe
 from librarian.functions import lang_code_3to2
 from librarian.builders import EpubBuilder, MobiBuilder
 from librarian.covers.marquise import MarquiseCover, LabelMarquiseCover
+from catalogue.models import Audience
 from .base import BasePublisher
 
 
@@ -128,30 +129,22 @@ class Legimi(BasePublisher):
                 'Password': self.password,
             })
 
-    def can_publish(self, shop, book):
+    def can_publish(self, site, book):
         meta = book.wldocument(librarian2=True).meta
         d = {
             'errors': [],
             'warnings': [],
+            'info': []
         }
-        if meta.thema_main or meta.thema:
-            if meta.thema_main:
-                comment = "w kategorii <b><tt>{code}</tt></b>".format(
-                    code=escape(meta.thema_main)
-                )
-                if meta.thema:
-                    comment += " oraz: " + ", ".join(
-                        "<b><tt>{code}</tt></b>".format(code=escape(t))
-                        for t in meta.thema
-                    )
-                d['comment'] = mark_safe(comment)
-            elif meta.thema:
-                d['comment'] = mark_safe(
-                    "w kategorii " + ", ".join(
-                        "<b><tt>{code}</tt></b>".format(code=escape(t))
-                        for t in meta.thema
-                    )
+        thema = self.get_thema(meta)
+        if thema:
+            d['info'].append(mark_safe(
+                "w kategorii " + ", ".join(
+                    "<b><tt>{code}</tt></b>".format(code=escape(t))
+                    for t in thema
                 )
+            ))
+            if not meta.thema_main:
                 d['warnings'].append('Brak głównej kategorii Thema')
         else:
             d['errors'].append('Brak kategorii Thema.')
@@ -173,12 +166,27 @@ class Legimi(BasePublisher):
             "url": model['Url'],
         }
 
-    def send_book(self, shop, book, changes=None):
+    def get_thema(self, meta):
+        thema = []
+        if meta.thema_main:
+            thema.append(meta.thema_main)
+        thema.extend(meta.thema)
+
+        thema.extend(
+            Audience.objects.filter(code__in=meta.audiences).exclude(
+                thema=None).values_list('thema', flat=True)
+        )
+        return thema
+
+    def send_book(self, site_book_publish, changes=None):
+        site_book = site_book_publish.site_book
+        site = site_book.site
+        book = site_book.book
         wlbook = book.wldocument(librarian2=True, changes=changes)
         meta = wlbook.meta
 
         cover = LabelMarquiseCover(meta, width=1200).output_file()
-        texts = shop.get_texts()
+        texts = site.get_texts()
         epub_file = EpubBuilder(
             cover=MarquiseCover,
             fundraising=texts,
@@ -190,23 +198,18 @@ class Legimi(BasePublisher):
             base_url='file://' + book.gallery_path() + '/'
         ).build(wlbook).get_file()
 
-        thema = []
-        if meta.thema_main:
-            thema.append(meta.thema_main)
-        thema.extend(meta.thema)
-
         book_data = {
             "Title": meta.title,
             "Author": ", ".join(p.readable() for p in meta.authors),
             "Year": str(date.today().year),
 
             'GenreId': str(self.get_genre(wlbook)),
-            'themaCategories': ';'.join(thema),
+            'themaCategories': ';'.join(self.get_thema(meta)),
             'thema-search': '',
             'Isbn': '',
             'LanguageLocale': lang_code_3to2(meta.language),
 
-            'Description': self.get_description(wlbook, shop.description_add),
+            'Description': self.get_description(wlbook, site.description_add),
         }
         if meta.isbn_html:
             isbn = meta.isbn_html
@@ -243,20 +246,20 @@ class Legimi(BasePublisher):
             'BookMobi.Name': mobi_data['name'],
         })
 
-        if book.legimi_id:
+        if site_book.external_id:
             self.edit(
-                book.legimi_id,
+                site_book.external_id,
                 book_data
             )
             self.edit_files(
-                book.legimi_id,
+                site_book.external_id,
                 files_data
             )
         else:
             legimi_id = self.create_book(book_data, files_data)
             if legimi_id:
-                book.legimi_id = legimi_id
-                book.save(update_fields=['legimi_id'])
+                site_book.external_id = legimi_id
+                site_book.save(update_fields=['external_id'])
 
         self.edit_sale(book)
 
@@ -353,10 +356,11 @@ class Legimi(BasePublisher):
             data=current
         )
 
-    def edit_sale(self, book):
-        assert book.legimi_id
+    def edit_sale(self, site_book):
+        book = site_book.book
+        assert site_book.external_id
 
-        words = book.wldocument().get_statistics()['total']['words_with_fn']
+        words = book.wldocument(librarian2=True).get_statistics()['total']['words_with_fn']
 
         price = settings.LEGIMI_SMALL_PRICE
         if words > settings.LEGIMI_SMALL_WORDS:
@@ -366,7 +370,7 @@ class Legimi(BasePublisher):
 
         data = {
             'ValidationTrue': 'true',
-            'Id': book.legimi_id,
+            'Id': site_book.external_id,
             'SalesPromotionId': "0",
             'IsLibraryPass': "False",
             'OriginalEnterToTheMarketType': "No",
@@ -385,6 +389,6 @@ class Legimi(BasePublisher):
         }
 
         self.session.post(
-            self.EDIT_SALE_URL % book.legimi_id,
+            self.EDIT_SALE_URL % site_book.external_id,
             data=data
         )