1 from datetime import date
6 from django.conf import settings
7 from django.utils.html import escape, format_html
8 from django.utils.safestring import mark_safe
9 from librarian.builders.html import SnippetHtmlBuilder
10 from librarian.functions import lang_code_3to2
11 from catalogue.models import Audience, Author, Thema
13 from .base import BasePublisher
14 from .woblink_constants import WOBLINK_CATEGORIES
17 class WoblinkError(ValueError):
20 class NoPrice(WoblinkError):
23 'Brak <a href="/admin/depot/shop/{price}">określonej ceny</a>.',
27 class NoIsbn(WoblinkError):
31 class AuthorLiteralForeign(WoblinkError):
34 'Nie obsługiwane: autor „{author}” w języku {lang}.',
35 author=str(self.args[0]),
36 lang=self.args[0].lang,
39 class AuthorNotInCatalogue(WoblinkError):
42 'Brak autora „{author}” w katalogu.',
43 author=str(self.args[0])
46 class AuthorNoWoblink(WoblinkError):
49 'Autor <a href="/admin/catalogue/author/{author_id}/">{author}</a> bez identyfikatora Woblink.',
50 author_id=self.args[0].id,
51 author=self.args[0].name
54 class NoThema(WoblinkError):
56 return format_html('Brak Thema.')
58 class UnknownThema(WoblinkError):
61 'Nieznana Thema {code}.',
66 class ThemaUnknownWoblink(WoblinkError):
69 'Thema <a href="/admin/catalogue/thema/{id}/">{code}</a> przypisana do nieznanej kategorii Woblink.',
71 code=self.args[0].code,
74 class NoWoblinkCategory(WoblinkError):
76 return 'Brak kategorii Woblink.'
78 class WoblinkWarning(Warning):
81 class NoMainThemaWarning(WoblinkWarning):
84 'Brak głównej kategorii Thema.'
87 class ThemaNoWoblink(WoblinkWarning):
90 'Thema <a href="/admin/catalogue/thema/{id}/">{code}</a> nie przypisana do kategorii Woblink.',
92 code=self.args[0].code,
95 class AuthorLiteralForeignWarning(WoblinkWarning):
98 'Nie obsługiwane: autor „{author}” w języku {lang}.',
99 author=str(self.args[0]),
100 lang=self.args[0].lang,
103 class AuthorNotInCatalogueWarning(WoblinkWarning):
106 'Brak autora „{author}” w katalogu.',
107 author=str(self.args[0])
110 class AuthorNoWoblinkWarning(WoblinkWarning):
113 'Autor <a href="/admin/catalogue/author/{author_id}/">{author}</a> bez identyfikatora Woblink.',
114 author_id=self.args[0].id,
115 author=self.args[0].name
121 class Woblink(BasePublisher):
122 BASE_URL = 'https://publisher.woblink.com/'
123 ADD_URL = BASE_URL + 'catalog/add'
124 STEP1_URL = BASE_URL + 'catalog/edit/%s'
125 STEP2_URL = BASE_URL + 'catalog/edit/%s/2'
126 STEP3_URL = BASE_URL + 'catalog/edit/%s/3'
127 STEP4_URL = BASE_URL + 'catalog/edit/%s/4'
128 STEP5_URL = BASE_URL + 'catalog/edit/%s/5'
129 UPLOAD_URL = BASE_URL + 'file/upload-%s'
130 JOB_STATUS_URL = BASE_URL + 'task/status'
131 GENERATE_DEMO_URL = BASE_URL + 'task/run/generate-%s-demo/%s/%d'
132 CHECK_DEMO_URL = BASE_URL + 'task/run/check-%s-demo/%s'
134 SEARCH_CATALOGUE_URL = BASE_URL + '{category}/autocomplete/{term}'
140 response = self.session.get('https://publisher.woblink.com/login')
142 r'name="_csrf_token" value="([^"]+)"',
146 '_csrf_token': token,
147 '_username': self.username,
148 '_password': self.password,
150 response = self.session.post(
151 'https://publisher.woblink.com/login_check',
155 def search_catalogue(self, category, term):
156 return self.session.get(
157 self.SEARCH_CATALOGUE_URL.format(category=category, term=term)
160 def search_author_catalogue(self, term):
164 'text': item['autFullname']
166 for item in self.search_catalogue('author', term)
168 def search_series_catalogue(self, term):
174 for item in self.search_catalogue('series', term)
177 def get_isbn(self, meta, errors=None):
178 if not meta.isbn_epub:
179 if errors is not None:
180 errors.append(NoIsbn())
181 return meta.isbn_epub
183 def get_authors_data(self, meta, errors=None):
185 for role, items, obligatory in [
186 (self.ROLE_AUTHOR, meta.authors, True),
187 (self.ROLE_TRANSLATOR, meta.translators, False)
189 for person_literal in items:
190 if person_literal.lang != 'pl':
191 if errors is not None:
193 errors.append(AuthorLiteralForeign(person_literal))
195 errors.append(AuthorLiteralForeignWarning(person_literal))
197 aobj = Author.get_by_literal(str(person_literal))
199 if errors is not None:
201 errors.append(AuthorNotInCatalogue(person_literal))
203 errors.append(AuthorNotInCatalogueWarning(person_literal))
206 if errors is not None:
208 errors.append(AuthorNoWoblink(aobj))
210 errors.append(AuthorNoWoblinkWarning(aobj))
212 authors.append((role, aobj.woblink))
215 def get_genres(self, meta, errors=None):
218 thema_codes.append(meta.thema_main)
220 if errors is not None:
221 errors.append(NoMainThemaWarning())
222 thema_codes.extend(meta.thema)
224 if errors is not None:
225 errors.append(NoThema())
227 for code in thema_codes:
229 thema = Thema.objects.get(code=code)
230 except Thema.DoesNotExist:
231 if errors is not None:
232 errors.append(UnknownThema(code))
234 if thema.woblink_category is None:
235 if errors is not None:
236 errors.append(ThemaNoWoblink(thema))
237 elif thema.woblink_category not in WOBLINK_CATEGORIES:
238 if errors is not None:
239 errors.append(ThemaUnknownWoblink(thema))
240 elif thema.woblink_category not in category_ids:
241 category_ids.append(thema.woblink_category)
243 if errors is not None:
244 errors.append(NoWoblinkCategory())
247 def get_series(self, meta, errors=None):
248 return list(Audience.objects.filter(code__in=meta.audiences).exclude(
249 woblink=None).values_list('woblink', flat=True))
251 def get_abstract(self, wldoc, errors=None, description_add=None):
252 description = self.get_description(wldoc, description_add)
253 parts = description.split('\n', 1)
254 if len(parts) == 1 or len(parts[0]) > 240:
255 # No newline found here.
256 # Try to find last sentence end..
257 parts = re.split(r' \.', description[240::-1], 1)
259 p1 = parts[1][::-1] + '.'
260 p2 = description[len(p1) + 1:]
262 # No sentence end found.
264 p1 = description[:240].rsplit(' ', 1)[0]
265 p2 = description[len(p1) + 1:]
270 m = re.search(r'<[^>]+$', parts[0])
272 parts[0] = parts[0][:-len(m.group(0))]
273 parts[1] = m.group(0) + parts[1]
276 for tag in re.findall(r'<[^>]*[^/>]>', parts[0]):
281 for tag in reversed(opened):
282 parts[0] += '</' + tag[1:-1].split()[0] + '>'
283 parts[1] = tag + parts[1]
289 def get_lang2code(self, meta, errors=None):
290 return lang_code_3to2(meta.language)
292 def get_price(self, shop, wldoc, errors=None):
294 stats = wldoc.get_statistics()['total']
297 errors.append(NoPrice(shop))
299 words = stats['words_with_fn']
300 pages = stats['chars_with_fn'] / 1800
301 price = shop.get_price(words, pages)
304 errors.append(NoPrice(shop))
309 def can_publish(self, shop, book):
310 wldoc = book.wldocument(librarian2=True)
317 book_data = self.get_book_data(shop, wldoc, errors)
319 if not isinstance(error, Warning):
320 errlist = d['errors']
322 errlist = d['warnings']
323 errlist.append(error.as_html())
325 if book_data.get('genres'):
326 d['info'].append(format_html(
327 'W kategoriach: {cat} ({price} zł)',
328 cat=', '.join(self.describe_category(g) for g in book_data['genres']),
329 price=book_data['price'],
331 d['info'].append(mark_safe(
332 '<strong>' + book_data['abstract']['header'] +
333 '</strong><br/>' + book_data['abstract']['rest']
338 def describe_category(self, category):
341 c = WOBLINK_CATEGORIES[category]
343 category = c.get('parent')
344 return ' / '.join(reversed(t))
346 def create_book(self, isbn):
347 isbn = ''.join(c for c in isbn if c.isdigit())
348 assert len(isbn) == 13
349 response = self.session.post(
352 'AddPublication[pubType]': 'ebook',
353 'AddPublication[pubHasIsbn]': '1',
354 'AddPublication[pubIsbn]': isbn,
358 m = re.search(r'/(\d+)$', response.url)
362 def send_book(self, shop, book, changes=None):
363 wldoc = book.wldocument(librarian2=True, changes=changes, publishable=False) # TODO pub
366 book_data = self.get_book_data(shop, wldoc)
368 if not book.woblink_id:
369 #book.woblink_id = 2959868
370 woblink_id = self.create_book(book_data['isbn'])
372 book.woblink_id = woblink_id
373 book.save(update_fields=['woblink_id'])
375 self.edit_step1(book.woblink_id, book_data)
376 self.edit_step2(book.woblink_id, book_data)
377 self.edit_step3(book.woblink_id, book_data)
378 cover_id = self.send_cover(book.woblink_id, wldoc)
380 texts = shop.get_texts()
381 epub_id, epub_demo = self.send_epub(
382 book.woblink_id, wldoc, book.gallery_path(),
385 mobi_id, mobi_demo = self.send_mobi(
386 book.woblink_id, wldoc, book.gallery_path(),
390 book.woblink_id, book_data,
391 cover_id, epub_id, epub_demo, mobi_id, mobi_demo,
393 self.edit_step5(book.woblink_id, book_data)
395 def get_book_data(self, shop, wldoc, errors=None):
397 "title": wldoc.meta.title,
398 "isbn": self.get_isbn(wldoc.meta, errors=errors),
399 "authors": self.get_authors_data(wldoc.meta, errors=errors),
400 "abstract": self.get_abstract(
401 wldoc, errors=errors, description_add=shop.description_add
403 "lang2code": self.get_lang2code(wldoc.meta, errors=errors),
404 "genres": self.get_genres(wldoc.meta, errors=errors),
405 "price": self.get_price(shop, wldoc, errors=errors),
406 "series": self.get_series(wldoc.meta, errors=errors),
409 def with_form_name(self, data, name):
412 for (k, v) in data.items()
415 def edit_step1(self, woblink_id, book_data):
420 "AhpPubId": woblink_id,
421 "AhpAutId": author_id,
422 "AhpType": author_type,
424 for (author_type, author_id) in data['authors']
429 'PublicationId': woblink_id,
430 'SeriesId': series_id,
432 for series_id in data['series']
436 'pubTitle': book_data['title'],
437 'npwAuthorHasPublications': json.dumps(authors_data),
438 'pubShortNote': data['abstract']['header'],
439 'pubNote': data['abstract']['rest'],
440 'pubCulture': data['lang2code'],
441 'npwPublicationHasAwards': '[]',
442 'npwPublicationHasSeriess': json.dumps(series_data),
444 d = self.with_form_name(d, 'EditPublicationStep1')
445 d['roles'] = [author_type for (author_type, author_id) in data['authors']]
446 r = self.session.post(self.STEP1_URL % woblink_id, data=d)
450 def edit_step2(self, woblink_id, book_data):
453 for i, g in enumerate(book_data['genres']):
454 gdata = WOBLINK_CATEGORIES[g]
456 legacy = gdata.get('legacy')
457 if p := gdata.get('parent'):
458 gd.setdefault(p, {'isMain': False})
459 gd[p].setdefault('children', [])
460 gd[p]['children'].append(str(g))
461 gd[p].setdefault('mainChild', str(g))
463 legacy = WOBLINK_CATEGORIES[p].get('legacy')
466 gd[g]['isMain'] = True
473 for k, v in gd.items()
477 'npwPublicationHasNewGenres': json.dumps(gd),
478 'genre': legacy or '',
480 data = self.with_form_name(data, 'AddPublicationStep2')
481 return self.session.post(self.STEP2_URL % woblink_id, data=data)
483 def edit_step3(self, woblink_id, book_data):
485 'pubBasePrice': book_data['price'],
486 'pubPremiereDate': date.today().isoformat(),
487 'pubIsLicenseIndefinite': '1',
488 'pubFileFormat': 'epub+mobi',
490 'pubPublisherIndex': '',
492 d = self.with_form_name(d, 'EditPublicationStep3')
493 return self.session.post(self.STEP3_URL % woblink_id, data=d)
495 def edit_step4(self, woblink_id, book_data, cover_id, epub_id, epub_demo, mobi_id, mobi_demo):
497 'pubCoverResId': cover_id,
498 'pubEpubResId': epub_id,
499 'pubEpubDemoResId': epub_demo,
500 'pubMobiResId': mobi_id,
501 'pubMobiDemoResId': mobi_demo,
502 'pubFileFormat': 'epub+mobi',
505 d = self.with_form_name(d, 'EditPublicationStep4')
506 return self.session.post(self.STEP4_URL % woblink_id, data=d)
508 def edit_step5(self, woblink_id, book_data):
510 d = self.with_form_name(d, 'EditPublicationStep5')
511 return self.session.post(self.STEP5_URL % woblink_id, data=d)
513 def wait_for_job(self, job_id):
515 response = self.session.post(
517 data={'ids[]': job_id}
519 data = response.json()[job_id]
521 assert data['successful']
522 return data.get('returnValue')
525 def upload_file(self, woblink_id, filename, content, field_name, mime_type):
530 field_name: (filename, content, mime_type)
533 form_name = f'Upload{field_name}'
534 id_field = f'pub{field_name}ResId'
535 field_name = field_name.lower()
537 response = self.session.post(
538 self.UPLOAD_URL % field_name,
539 data=self.with_form_name(data, form_name),
540 files=self.with_form_name(files, form_name),
542 resp_data = response.json()
543 assert resp_data['success'] is True
544 file_id = resp_data[id_field]
545 if 'jobId' in resp_data:
546 self.wait_for_job(resp_data['jobId'])
549 def generate_demo(self, woblink_id, file_format, check=True):
552 job_id = self.session.get(
553 self.GENERATE_DEMO_URL % (file_format, woblink_id, percent),
556 file_id = self.wait_for_job(job_id)
557 except AssertionError:
568 self.CHECK_DEMO_URL % (file_format, woblink_id)
573 def send_epub(self, woblink_id, doc, gallery_path, fundraising=None):
574 from librarian.builders import EpubBuilder
575 content = EpubBuilder(
576 base_url='file://' + gallery_path + '/',
577 fundraising=fundraising or [],
578 ).build(doc).get_file()
579 file_id = self.upload_file(
581 doc.meta.url.slug + '.epub',
584 'application/epub+zip'
586 demo_id = self.generate_demo(woblink_id, 'epub')
587 return file_id, demo_id
589 def send_mobi(self, woblink_id, doc, gallery_path, fundraising=None):
590 from librarian.builders import MobiBuilder
591 content = MobiBuilder(
592 base_url='file://' + gallery_path + '/',
593 fundraising=fundraising or [],
594 ).build(doc).get_file()
595 file_id = self.upload_file(
597 doc.meta.url.slug + '.mobi',
600 'application/x-mobipocket-ebook'
602 demo_id = self.generate_demo(woblink_id, 'mobi', check=False)
603 return file_id, demo_id
605 def send_cover(self, woblink_id, doc):
606 from librarian.cover import make_cover
609 cover = make_cover(doc.meta, cover_class='m-label', width=1748, height=2480)
610 content = io.BytesIO()
611 cover.final_image().save(content, cover.format)
613 file_id = self.upload_file(
615 doc.meta.url.slug + '.jpeg',