Bit nicer source flow.
[redakcja.git] / src / depot / publishers / woblink.py
index 82a4375..3e1c78c 100644 (file)
@@ -20,8 +20,8 @@ class WoblinkError(ValueError):
 class NoPrice(WoblinkError):
     def as_html(self):
         return format_html(
 class NoPrice(WoblinkError):
     def as_html(self):
         return format_html(
-            'Brak <a href="/admin/depot/shop/{price}">określonej ceny</a>.',
-            price=self.args[0].id
+            'Brak <a href="/admin/depot/site/{site}">określonej ceny</a>.',
+            site=self.args[0].id
         )
 
 class NoIsbn(WoblinkError):
         )
 
 class NoIsbn(WoblinkError):
@@ -187,6 +187,7 @@ class Woblink(BasePublisher):
                 (self.ROLE_TRANSLATOR, meta.translators, False)
         ]:
             for person_literal in items:
                 (self.ROLE_TRANSLATOR, meta.translators, False)
         ]:
             for person_literal in items:
+                if person_literal is None: continue
                 if person_literal.lang != 'pl':
                     if errors is not None:
                         if obligatory:
                 if person_literal.lang != 'pl':
                     if errors is not None:
                         if obligatory:
@@ -220,6 +221,12 @@ class Woblink(BasePublisher):
             if errors is not None:
                 errors.append(NoMainThemaWarning())
         thema_codes.extend(meta.thema)
             if errors is not None:
                 errors.append(NoMainThemaWarning())
         thema_codes.extend(meta.thema)
+
+        thema_codes.extend(
+            Audience.objects.filter(code__in=meta.audiences).exclude(
+                thema='').values_list('thema', flat=True)
+        )
+
         if not thema_codes:
             if errors is not None:
                 errors.append(NoThema())
         if not thema_codes:
             if errors is not None:
                 errors.append(NoThema())
@@ -289,32 +296,36 @@ class Woblink(BasePublisher):
     def get_lang2code(self, meta, errors=None):
         return lang_code_3to2(meta.language)
 
     def get_lang2code(self, meta, errors=None):
         return lang_code_3to2(meta.language)
 
-    def get_price(self, shop, wldoc, errors=None):
+    def get_price(self, site, wldoc, errors=None):
         try:
             stats = wldoc.get_statistics()['total']
         except:
             if errors:
         try:
             stats = wldoc.get_statistics()['total']
         except:
             if errors:
-                errors.append(NoPrice(shop))
+                errors.append(NoPrice(site))
             return 0
         words = stats['words_with_fn']
         pages = stats['chars_with_fn'] / 1800
             return 0
         words = stats['words_with_fn']
         pages = stats['chars_with_fn'] / 1800
-        price = shop.get_price(words, pages)
+        price = site.get_price(words, pages)
         if price is None:
             if errors:
         if price is None:
             if errors:
-                errors.append(NoPrice(shop))
+                errors.append(NoPrice(site))
             return 0
 
         return price
 
             return 0
 
         return price
 
-    def can_publish(self, shop, book):
-        wldoc = book.wldocument(librarian2=True)
+    def can_publish(self, site, book):
         d = {
             'warnings': [],
             'errors': [],
             'info': [],
         }
         d = {
             'warnings': [],
             'errors': [],
             'info': [],
         }
+        try:
+            wldoc = book.wldocument(librarian2=True)
+        except:
+            d['errors'].append('Nieprawidłowy dokument.')
+            return d
         errors = []
         errors = []
-        book_data = self.get_book_data(shop, wldoc, errors)
+        book_data = self.get_book_data(site, wldoc, errors)
         for error in errors:
             if not isinstance(error, Warning):
                 errlist = d['errors']
         for error in errors:
             if not isinstance(error, Warning):
                 errlist = d['errors']
@@ -322,6 +333,12 @@ class Woblink(BasePublisher):
                 errlist = d['warnings']
             errlist.append(error.as_html())
 
                 errlist = d['warnings']
             errlist.append(error.as_html())
 
+        if book_data.get('isbn'):
+            d['info'].append(format_html(
+                'ISBN: {isbn}',
+                isbn=book_data['isbn'],
+            ))
+
         if book_data.get('genres'):
             d['info'].append(format_html(
                 'W kategoriach: {cat} ({price} zł)',
         if book_data.get('genres'):
             d['info'].append(format_html(
                 'W kategoriach: {cat} ({price} zł)',
@@ -359,50 +376,53 @@ class Woblink(BasePublisher):
         if m is not None:
             return m.group(1)
 
         if m is not None:
             return m.group(1)
 
-    def send_book(self, shop, book, changes=None):
+    def send_book(self, site_book_publish, changes=None):
+        site_book = site_book_publish.site_book
+        book = site_book.book
+        site = site_book.site
         wldoc = book.wldocument(librarian2=True, changes=changes, publishable=False) # TODO pub
         meta = wldoc.meta
 
         wldoc = book.wldocument(librarian2=True, changes=changes, publishable=False) # TODO pub
         meta = wldoc.meta
 
-        book_data = self.get_book_data(shop, wldoc)
+        book_data = self.get_book_data(site, wldoc)
 
 
-        if not book.woblink_id:
-            #book.woblink_id = 2959868
+        if not site_book.external_id:
             woblink_id = self.create_book(book_data['isbn'])
             assert woblink_id
             woblink_id = self.create_book(book_data['isbn'])
             assert woblink_id
-            book.woblink_id = woblink_id
-            book.save(update_fields=['woblink_id'])
+            site_book.external_id = woblink_id
+            site_book.save(update_fields=['external_id'])
+        woblink_id = site_book.external_id
 
 
-        self.edit_step1(book.woblink_id, book_data)
-        self.edit_step2(book.woblink_id, book_data)
-        self.edit_step3(book.woblink_id, book_data)
-        cover_id = self.send_cover(book.woblink_id, wldoc)
+        self.edit_step1(woblink_id, book_data)
+        self.edit_step2(woblink_id, book_data)
+        self.edit_step3(woblink_id, book_data)
+        cover_id = self.send_cover(woblink_id, wldoc)
 
 
-        texts = shop.get_texts()
+        texts = site.get_texts()
         epub_id, epub_demo = self.send_epub(
         epub_id, epub_demo = self.send_epub(
-            book.woblink_id, wldoc, book.gallery_path(),
+            woblink_id, wldoc, book.gallery_path(),
             fundraising=texts
         )
         mobi_id, mobi_demo = self.send_mobi(
             fundraising=texts
         )
         mobi_id, mobi_demo = self.send_mobi(
-            book.woblink_id, wldoc, book.gallery_path(),
+            woblink_id, wldoc, book.gallery_path(),
             fundraising=texts
         )
         self.edit_step4(
             fundraising=texts
         )
         self.edit_step4(
-            book.woblink_id, book_data,
+            woblink_id, book_data,
             cover_id, epub_id, epub_demo, mobi_id, mobi_demo,
         )
             cover_id, epub_id, epub_demo, mobi_id, mobi_demo,
         )
-        self.edit_step5(book.woblink_id, book_data)
+        self.edit_step5(woblink_id, book_data)
 
 
-    def get_book_data(self, shop, wldoc, errors=None):
+    def get_book_data(self, site, wldoc, errors=None):
         return {
             "title": wldoc.meta.title,
             "isbn": self.get_isbn(wldoc.meta, errors=errors),
             "authors": self.get_authors_data(wldoc.meta, errors=errors),
             "abstract": self.get_abstract(
         return {
             "title": wldoc.meta.title,
             "isbn": self.get_isbn(wldoc.meta, errors=errors),
             "authors": self.get_authors_data(wldoc.meta, errors=errors),
             "abstract": self.get_abstract(
-                wldoc, errors=errors, description_add=shop.description_add
+                wldoc, errors=errors, description_add=site.description_add
             ),
             "lang2code": self.get_lang2code(wldoc.meta, errors=errors),
             "genres": self.get_genres(wldoc.meta, errors=errors),
             ),
             "lang2code": self.get_lang2code(wldoc.meta, errors=errors),
             "genres": self.get_genres(wldoc.meta, errors=errors),
-            "price": self.get_price(shop, wldoc, errors=errors),
+            "price": self.get_price(site, wldoc, errors=errors),
             "series": self.get_series(wldoc.meta, errors=errors),
         }
 
             "series": self.get_series(wldoc.meta, errors=errors),
         }
 
@@ -488,6 +508,7 @@ class Woblink(BasePublisher):
             'pubFileFormat': 'epub+mobi',
             'pubIsAcs': '0',
             'pubPublisherIndex': '',
             'pubFileFormat': 'epub+mobi',
             'pubIsAcs': '0',
             'pubPublisherIndex': '',
+            'save_and_continue': '',
         }
         d = self.with_form_name(d, 'EditPublicationStep3')
         return self.session.post(self.STEP3_URL % woblink_id, data=d)
         }
         d = self.with_form_name(d, 'EditPublicationStep3')
         return self.session.post(self.STEP3_URL % woblink_id, data=d)
@@ -501,12 +522,13 @@ class Woblink(BasePublisher):
             'pubMobiDemoResId': mobi_demo,
             'pubFileFormat': 'epub+mobi',
             'pubId': woblink_id,
             'pubMobiDemoResId': mobi_demo,
             'pubFileFormat': 'epub+mobi',
             'pubId': woblink_id,
+            'save_and_continue': '',
         }
         d = self.with_form_name(d, 'EditPublicationStep4')
         return self.session.post(self.STEP4_URL % woblink_id, data=d)
 
     def edit_step5(self, woblink_id, book_data):
         }
         d = self.with_form_name(d, 'EditPublicationStep4')
         return self.session.post(self.STEP4_URL % woblink_id, data=d)
 
     def edit_step5(self, woblink_id, book_data):
-        d = {}
+        d = {'save': ''}
         d = self.with_form_name(d, 'EditPublicationStep5')
         return self.session.post(self.STEP5_URL % woblink_id, data=d)
 
         d = self.with_form_name(d, 'EditPublicationStep5')
         return self.session.post(self.STEP5_URL % woblink_id, data=d)
 
@@ -523,6 +545,10 @@ class Woblink(BasePublisher):
             sleep(2)
 
     def upload_file(self, woblink_id, filename, content, field_name, mime_type):
             sleep(2)
 
     def upload_file(self, woblink_id, filename, content, field_name, mime_type):
+        form_name = f'Upload{field_name}'
+        id_field = f'pub{field_name}ResId'
+        field_name = field_name.lower()
+
         data = {
             'pubId': woblink_id,
         }
         data = {
             'pubId': woblink_id,
         }
@@ -530,10 +556,6 @@ class Woblink(BasePublisher):
             field_name: (filename, content, mime_type)
         }
         
             field_name: (filename, content, mime_type)
         }
         
-        form_name = f'Upload{field_name}'
-        id_field = f'pub{field_name}ResId'
-        field_name = field_name.lower()
-
         response = self.session.post(
             self.UPLOAD_URL % field_name,
             data=self.with_form_name(data, form_name),
         response = self.session.post(
             self.UPLOAD_URL % field_name,
             data=self.with_form_name(data, form_name),
@@ -554,6 +576,12 @@ class Woblink(BasePublisher):
             ).json()['jobId']
             try:
                 file_id = self.wait_for_job(job_id)
             ).json()['jobId']
             try:
                 file_id = self.wait_for_job(job_id)
+                if check:
+                    self.wait_for_job(
+                        self.session.get(
+                            self.CHECK_DEMO_URL % (file_format, woblink_id)
+                        ).json()['jobId']
+                    )
             except AssertionError:
                 if percent < 50:
                     percent += 10
             except AssertionError:
                 if percent < 50:
                     percent += 10
@@ -562,12 +590,6 @@ class Woblink(BasePublisher):
             else:
                 break
 
             else:
                 break
 
-        if check:
-            self.wait_for_job(
-                self.session.get(
-                    self.CHECK_DEMO_URL % (file_format, woblink_id)
-                ).json()['jobId']
-            )
         return file_id
 
     def send_epub(self, woblink_id, doc, gallery_path, fundraising=None):
         return file_id
 
     def send_epub(self, woblink_id, doc, gallery_path, fundraising=None):
@@ -580,8 +602,7 @@ class Woblink(BasePublisher):
             woblink_id,
             doc.meta.url.slug + '.epub',
             content,
             woblink_id,
             doc.meta.url.slug + '.epub',
             content,
-            'UploadEpub',
-            'epub',
+            'Epub',
             'application/epub+zip'
         )
         demo_id = self.generate_demo(woblink_id, 'epub')
             'application/epub+zip'
         )
         demo_id = self.generate_demo(woblink_id, 'epub')
@@ -597,8 +618,7 @@ class Woblink(BasePublisher):
             woblink_id,
             doc.meta.url.slug + '.mobi',
             content,
             woblink_id,
             doc.meta.url.slug + '.mobi',
             content,
-            'UploadMobi',
-            'mobi',
+            'Mobi',
             'application/x-mobipocket-ebook'
         )
         demo_id = self.generate_demo(woblink_id, 'mobi', check=False)
             'application/x-mobipocket-ebook'
         )
         demo_id = self.generate_demo(woblink_id, 'mobi', check=False)
@@ -616,8 +636,7 @@ class Woblink(BasePublisher):
             woblink_id,
             doc.meta.url.slug + '.jpeg',
             content,
             woblink_id,
             doc.meta.url.slug + '.jpeg',
             content,
-            'UploadCover',
-            'cover',
+            'Cover',
             cover.mime_type()
         )
         return file_id
             cover.mime_type()
         )
         return file_id