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 UPLOAD_URL = BASE_URL + 'file/upload-%s'
128 JOB_STATUS_URL = BASE_URL + 'task/status'
129 GENERATE_DEMO_URL = BASE_URL + 'task/run/generate-%s-demo/%s/%d'
130 CHECK_DEMO_URL = BASE_URL + 'task/run/check-%s-demo/%s'
132 SEARCH_CATALOGUE_URL = BASE_URL + '{category}/autocomplete/{term}'
138 response = self.session.get('https://publisher.woblink.com/login')
140 r'name="_csrf_token" value="([^"]+)"',
144 '_csrf_token': token,
145 '_username': self.username,
146 '_password': self.password,
148 response = self.session.post(
149 'https://publisher.woblink.com/login_check',
153 def search_catalogue(self, category, term):
154 return self.session.get(
155 self.SEARCH_CATALOGUE_URL.format(category=category, term=term)
158 def search_author_catalogue(self, term):
162 'text': item['autFullname']
164 for item in self.search_catalogue('author', term)
166 def search_series_catalogue(self, term):
172 for item in self.search_catalogue('series', term)
175 def get_isbn(self, meta, errors=None):
176 if not meta.isbn_epub:
177 if errors is not None:
178 errors.append(NoIsbn())
179 return meta.isbn_epub
181 def get_authors_data(self, meta, errors=None):
183 for role, items, obligatory in [
184 (self.ROLE_AUTHOR, meta.authors, True),
185 (self.ROLE_TRANSLATOR, meta.translators, False)
187 for person_literal in items:
188 if person_literal.lang != 'pl':
189 if errors is not None:
191 errors.append(AuthorLiteralForeign(person_literal))
193 errors.append(AuthorLiteralForeignWarning(person_literal))
195 aobj = Author.get_by_literal(str(person_literal))
197 if errors is not None:
199 errors.append(AuthorNotInCatalogue(person_literal))
201 errors.append(AuthorNotInCatalogueWarning(person_literal))
204 if errors is not None:
206 errors.append(AuthorNoWoblink(aobj))
208 errors.append(AuthorNoWoblinkWarning(aobj))
210 authors.append((role, aobj.woblink))
213 def get_genres(self, meta, errors=None):
216 thema_codes.append(meta.thema_main)
218 if errors is not None:
219 errors.append(NoMainThemaWarning())
220 thema_codes.extend(meta.thema)
222 if errors is not None:
223 errors.append(NoThema())
225 for code in thema_codes:
227 thema = Thema.objects.get(code=code)
228 except Thema.DoesNotExist:
229 if errors is not None:
230 errors.append(UnknownThema(code))
232 if thema.woblink_category is None:
233 if errors is not None:
234 errors.append(ThemaNoWoblink(thema))
235 elif thema.woblink_category not in WOBLINK_CATEGORIES:
236 if errors is not None:
237 errors.append(ThemaUnknownWoblink(thema))
238 elif thema.woblink_category not in category_ids:
239 category_ids.append(thema.woblink_category)
241 if errors is not None:
242 errors.append(NoWoblinkCategory())
245 def get_series(self, meta, errors=None):
246 return list(Audience.objects.filter(code__in=meta.audiences).exclude(
247 woblink=None).values_list('woblink', flat=True))
249 def get_abstract(self, wldoc, errors=None, description_add=None):
250 description = self.get_description(wldoc, description_add)
251 parts = description.split('\n', 1)
252 if len(parts) == 1 or len(parts[0]) > 240:
253 # No newline found here.
254 # Try to find last sentence end..
255 parts = re.split(r' \.', description[240::-1], 1)
257 p1 = parts[1][::-1] + '.'
258 p2 = description[len(p1) + 1:]
260 # No sentence end found.
262 p1 = description[:240].rsplit(' ', 1)[0]
263 p2 = description[len(p1) + 1:]
268 m = re.search(r'<[^>]+$', parts[0])
270 parts[0] = parts[:-len(m.group(0))]
271 parts[1] = m.group(0) + parts[1]
274 for tag in re.findall(r'<[^>]+[^/>]>', parts[0]):
279 for tag in reversed(opened):
280 parts[0] += '</' + tag[1:-1].split()[0] + '>'
281 parts[1] = tag + parts[1]
287 def get_lang2code(self, meta, errors=None):
288 return lang_code_3to2(meta.language)
290 def get_price(self, shop, wldoc, errors=None):
291 stats = wldoc.get_statistics()['total']
292 words = stats['words_with_fn']
293 pages = stats['chars_with_fn'] / 1800
294 price = shop.get_price(words, pages)
297 errors.append(NoPrice(shop))
302 def can_publish(self, shop, book):
303 wldoc = book.wldocument(librarian2=True)
309 book_data = self.get_book_data(shop, wldoc, errors)
311 if not isinstance(error, Warning):
312 errlist = d['errors']
314 errlist = d['warnings']
315 errlist.append(error.as_html())
317 if book_data.get('genres'):
318 d['comment'] = format_html(
319 'W kategoriach: {cat} ({price} zł)',
320 cat=', '.join(self.describe_category(g) for g in book_data['genres']),
321 price=book_data['price']
326 def describe_category(self, category):
329 c = WOBLINK_CATEGORIES[category]
331 category = c.get('parent')
332 return ' / '.join(reversed(t))
334 def create_book(self, isbn):
335 isbn = ''.join(c for c in isbn if c.isdigit())
336 assert len(isbn) == 13
337 response = self.session.post(
340 'AddPublication[pubType]': 'ebook',
341 'AddPublication[pubHasIsbn]': '1',
342 'AddPublication[pubIsbn]': isbn,
346 m = re.search(r'/(\d+)$', response.url)
350 def send_book(self, shop, book, changes=None):
351 wldoc = book.wldocument(librarian2=True, changes=changes, publishable=False) # TODO pub
354 book_data = self.get_book_data(shop, wldoc)
356 if not book.woblink_id:
357 #book.woblink_id = 2959868
358 woblink_id = self.create_book(book_data['isbn'])
360 book.woblink_id = woblink_id
361 book.save(update_fields=['woblink_id'])
363 self.edit_step1(book.woblink_id, book_data)
364 self.edit_step2(book.woblink_id, book_data)
365 self.edit_step3(book.woblink_id, book_data)
366 self.send_cover(book.woblink_id, wldoc)
367 texts = shop.get_texts()
369 book.woblink_id, wldoc, book.gallery_path(),
373 book.woblink_id, wldoc, book.gallery_path(),
377 def get_book_data(self, shop, wldoc, errors=None):
379 "title": wldoc.meta.title,
380 "isbn": self.get_isbn(wldoc.meta, errors=errors),
381 "authors": self.get_authors_data(wldoc.meta, errors=errors),
382 "abstract": self.get_abstract(
383 wldoc, errors=errors, description_add=shop.description_add
385 "lang2code": self.get_lang2code(wldoc.meta, errors=errors),
386 "genres": self.get_genres(wldoc.meta, errors=errors),
387 "price": self.get_price(shop, wldoc, errors=errors),
388 "series": self.get_series(wldoc.meta, errors=errors),
391 def with_form_name(self, data, name):
394 for (k, v) in data.items()
397 def edit_step1(self, woblink_id, book_data):
402 "AhpPubId": woblink_id,
403 "AhpAutId": author_id,
404 "AhpType": author_type,
406 for (author_type, author_id) in data['authors']
411 'PublicationId': woblink_id,
412 'SeriesId': series_id,
414 for series_id in data['series']
418 'pubTitle': book_data['title'],
419 'npwAuthorHasPublications': json.dumps(authors_data),
420 'pubShortNote': data['abstract']['header'],
421 'pubNote': data['abstract']['rest'],
422 'pubCulture': data['lang2code'],
423 'npwPublicationHasAwards': '[]',
424 'npwPublicationHasSeriess': json.dumps(series_data),
426 d = self.with_form_name(d, 'EditPublicationStep1')
427 d['roles'] = [author_type for (author_type, author_id) in data['authors']]
428 r = self.session.post(self.STEP1_URL % woblink_id, data=d)
432 def edit_step2(self, woblink_id, book_data):
435 for i, g in enumerate(book_data['genres']):
436 gdata = WOBLINK_CATEGORIES[g]
438 legacy = gdata.get('legacy')
439 if p := gdata.get('parent'):
440 gd.setdefault(p, {'isMain': False})
441 gd[p].setdefault('children', [])
442 gd[p]['children'].append(str(g))
443 gd[p].setdefault('mainChild', str(g))
445 legacy = WOBLINK_CATEGORIES[p].get('legacy')
448 gd[g]['isMain'] = True
455 for k, v in gd.items()
459 'npwPublicationHasNewGenres': json.dumps(gd),
460 'genre': legacy or '',
462 data = self.with_form_name(data, 'AddPublicationStep2')
463 return self.session.post(self.STEP2_URL % woblink_id, data=data)
465 def edit_step3(self, woblink_id, book_data):
467 'pubBasePrice': book_data['price'],
468 'pubPremiereDate': date.today().isoformat(),
469 'pubIsLicenseIndefinite': '1',
470 'pubFileFormat': 'epub+mobi',
472 'pubPublisherIndex': '',
474 d = self.with_form_name(d, 'EditPublicationStep3')
475 return self.session.post(self.STEP3_URL % woblink_id, data=d)
477 def wait_for_job(self, job_id):
479 response = self.session.post(
481 data={'ids[]': job_id}
483 data = response.json()[job_id]
485 assert data['successful']
489 def upload_file(self, woblink_id, filename, content, form_name, field_name, mime_type):
494 field_name: (filename, content, mime_type)
496 response = self.session.post(
497 self.UPLOAD_URL % field_name,
498 data=self.with_form_name(data, form_name),
499 files=self.with_form_name(files, form_name),
501 resp_data = response.json()
502 assert resp_data['success'] is True
503 if 'jobId' in resp_data:
504 self.wait_for_job(resp_data['jobId'])
506 def generate_demo(self, woblink_id, file_format, check=True):
509 job_id = self.session.get(
510 self.GENERATE_DEMO_URL % (file_format, woblink_id, percent),
513 self.wait_for_job(job_id)
514 except AssertionError:
525 self.CHECK_DEMO_URL % (file_format, woblink_id)
529 def send_epub(self, woblink_id, doc, gallery_path, fundraising=None):
530 from librarian.builders import EpubBuilder
531 content = EpubBuilder(
532 base_url='file://' + gallery_path + '/',
533 fundraising=fundraising or [],
534 ).build(doc).get_file()
537 doc.meta.url.slug + '.epub',
541 'application/epub+zip'
543 self.generate_demo(woblink_id, 'epub')
545 def send_mobi(self, woblink_id, doc, gallery_path, fundraising=None):
546 from librarian.builders import MobiBuilder
547 content = MobiBuilder(
548 base_url='file://' + gallery_path + '/',
549 fundraising=fundraising or [],
550 ).build(doc).get_file()
553 doc.meta.url.slug + '.mobi',
557 'application/x-mobipocket-ebook'
559 self.generate_demo(woblink_id, 'mobi', check=False)
561 def send_cover(self, woblink_id, doc):
562 from librarian.cover import make_cover
565 cover = make_cover(doc.meta, cover_class='m-label', width=1748, height=2480)
566 content = io.BytesIO()
567 cover.final_image().save(content, cover.format)
571 doc.meta.url.slug + '.jpeg',