d7d55ea774e970cfbaa6ac28dc47c3fb58f948f5
[redakcja.git] / src / depot / publishers / woblink.py
1 from datetime import date
2 import io
3 import json
4 import re
5 from time import sleep
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
12 from .. import models
13 from .base import BasePublisher
14 from .woblink_constants import WOBLINK_CATEGORIES
15
16
17 class WoblinkError(ValueError):
18     pass
19
20 class NoPrice(WoblinkError):
21     def as_html(self):
22         return format_html(
23             'Brak <a href="/admin/depot/shop/{price}">określonej ceny</a>.',
24             price=self.args[0].id
25         )
26
27 class NoIsbn(WoblinkError):
28     def as_html(self):
29         return 'Brak ISBN.'
30
31 class AuthorLiteralForeign(WoblinkError):
32     def as_html(self):
33         return format_html(
34             'Nie obsługiwane: autor „{author}” w języku {lang}.',
35             author=str(self.args[0]),
36             lang=self.args[0].lang,
37         )
38
39 class AuthorNotInCatalogue(WoblinkError):
40     def as_html(self):
41         return format_html(
42             'Brak autora „{author}” w katalogu.',
43             author=str(self.args[0])
44         )
45
46 class AuthorNoWoblink(WoblinkError):
47     def as_html(self):
48         return format_html(
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
52         )
53
54 class NoThema(WoblinkError):
55     def as_html(self):
56         return format_html('Brak Thema.')
57
58 class UnknownThema(WoblinkError):
59     def as_html(self):
60         return format_html(
61             'Nieznana Thema {code}.',
62             code=self.args[0]
63         )
64
65
66 class ThemaUnknownWoblink(WoblinkError):
67     def as_html(self):
68         return format_html(
69             'Thema <a href="/admin/catalogue/thema/{id}/">{code}</a> przypisana do nieznanej kategorii Woblink.',
70             id=self.args[0].id,
71             code=self.args[0].code,
72         )
73
74 class NoWoblinkCategory(WoblinkError):
75     def as_html(self):
76         return 'Brak kategorii Woblink.'
77
78 class WoblinkWarning(Warning):
79     pass
80
81 class NoMainThemaWarning(WoblinkWarning):
82     def as_html(self):
83         return format_html(
84             'Brak głównej kategorii Thema.'
85         )
86
87 class ThemaNoWoblink(WoblinkWarning):
88     def as_html(self):
89         return format_html(
90             'Thema <a href="/admin/catalogue/thema/{id}/">{code}</a> nie przypisana do kategorii Woblink.',
91             id=self.args[0].id,
92             code=self.args[0].code,
93         )
94
95 class AuthorLiteralForeignWarning(WoblinkWarning):
96     def as_html(self):
97         return format_html(
98             'Nie obsługiwane: autor „{author}” w języku {lang}.',
99             author=str(self.args[0]),
100             lang=self.args[0].lang,
101         )
102
103 class AuthorNotInCatalogueWarning(WoblinkWarning):
104     def as_html(self):
105         return format_html(
106             'Brak autora „{author}” w katalogu.',
107             author=str(self.args[0])
108         )
109
110 class AuthorNoWoblinkWarning(WoblinkWarning):
111     def as_html(self):
112         return format_html(
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
116         )
117
118
119
120
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'
133
134     SEARCH_CATALOGUE_URL = BASE_URL + '{category}/autocomplete/{term}'
135
136     ROLE_AUTHOR = 1
137     ROLE_TRANSLATOR = 4
138
139     def login(self):
140         response = self.session.get('https://publisher.woblink.com/login')
141         token = re.search(
142             r'name="_csrf_token" value="([^"]+)"',
143             response.text
144         ).group(1)
145         data = {
146             '_csrf_token': token,
147             '_username': self.username,
148             '_password': self.password,
149         }
150         response = self.session.post(
151             'https://publisher.woblink.com/login_check',
152             data=data,
153         )
154
155     def search_catalogue(self, category, term):
156         return self.session.get(
157             self.SEARCH_CATALOGUE_URL.format(category=category, term=term)
158         ).json()
159
160     def search_author_catalogue(self, term):
161         return [
162             {
163                 'id': item['autId'],
164                 'text': item['autFullname']
165             }
166             for item in self.search_catalogue('author', term)
167         ]
168     def search_series_catalogue(self, term):
169         return [
170             {
171                 'id': item['id'],
172                 'text': item['name']
173             }
174             for item in self.search_catalogue('series', term)
175         ]
176         
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
182
183     def get_authors_data(self, meta, errors=None):
184         authors = []
185         for role, items, obligatory in [
186                 (self.ROLE_AUTHOR, meta.authors, True),
187                 (self.ROLE_TRANSLATOR, meta.translators, False)
188         ]:
189             for person_literal in items:
190                 if person_literal.lang != 'pl':
191                     if errors is not None:
192                         if obligatory:
193                              errors.append(AuthorLiteralForeign(person_literal))
194                         else:
195                             errors.append(AuthorLiteralForeignWarning(person_literal))
196                     continue
197                 aobj = Author.get_by_literal(str(person_literal))
198                 if aobj is None:
199                     if errors is not None:
200                         if obligatory:
201                              errors.append(AuthorNotInCatalogue(person_literal))
202                         else:
203                             errors.append(AuthorNotInCatalogueWarning(person_literal))
204                     continue
205                 if not aobj.woblink:
206                     if errors is not None:
207                         if obligatory:
208                              errors.append(AuthorNoWoblink(aobj))
209                         else:
210                             errors.append(AuthorNoWoblinkWarning(aobj))
211                     continue
212                 authors.append((role, aobj.woblink))
213         return authors
214
215     def get_genres(self, meta, errors=None):
216         thema_codes = []
217         if meta.thema_main:
218             thema_codes.append(meta.thema_main)
219         else:
220             if errors is not None:
221                 errors.append(NoMainThemaWarning())
222         thema_codes.extend(meta.thema)
223         if not thema_codes:
224             if errors is not None:
225                 errors.append(NoThema())
226         category_ids = []
227         for code in thema_codes:
228             try:
229                 thema = Thema.objects.get(code=code)
230             except Thema.DoesNotExist:
231                 if errors is not None:
232                     errors.append(UnknownThema(code))
233             else:
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)
242         if not category_ids:
243             if errors is not None:
244                 errors.append(NoWoblinkCategory())
245         return category_ids
246
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))
250
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)
258             if len(parts) == 2:
259                 p1 = parts[1][::-1] + '.'
260                 p2 = description[len(p1) + 1:]
261             else:
262                 # No sentence end found.
263                 # Just find a space.
264                 p1 = description[:240].rsplit(' ', 1)[0]
265                 p2 = description[len(p1) + 1:]
266                 p1 += '…'
267                 p2 = '…' + p2
268             parts = [p1, p2]
269
270         m = re.search(r'<[^>]+$', parts[0])
271         if m is not None:
272             parts[0] = parts[0][:-len(m.group(0))]
273             parts[1] = m.group(0) + parts[1]
274
275         opened = []
276         for tag in re.findall(r'<[^>]*[^/>]>', parts[0]):
277             if tag[1] == '/':
278                 opened.pop()
279             else:
280                 opened.append(tag)
281         for tag in reversed(opened):
282             parts[0] += '</' + tag[1:-1].split()[0] + '>'
283             parts[1] = tag + parts[1]
284         return {
285             'header': parts[0],
286             'rest': parts[1],
287         }
288
289     def get_lang2code(self, meta, errors=None):
290         return lang_code_3to2(meta.language)
291
292     def get_price(self, shop, wldoc, errors=None):
293         try:
294             stats = wldoc.get_statistics()['total']
295         except:
296             if errors:
297                 errors.append(NoPrice(shop))
298             return 0
299         words = stats['words_with_fn']
300         pages = stats['chars_with_fn'] / 1800
301         price = shop.get_price(words, pages)
302         if price is None:
303             if errors:
304                 errors.append(NoPrice(shop))
305             return 0
306
307         return price
308
309     def can_publish(self, shop, book):
310         wldoc = book.wldocument(librarian2=True)
311         d = {
312             'warnings': [],
313             'errors': [],
314             'info': [],
315         }
316         errors = []
317         book_data = self.get_book_data(shop, wldoc, errors)
318         for error in errors:
319             if not isinstance(error, Warning):
320                 errlist = d['errors']
321             else:
322                 errlist = d['warnings']
323             errlist.append(error.as_html())
324
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'],
330             ))
331         d['info'].append(mark_safe(
332             '<strong>' + book_data['abstract']['header'] +
333             '</strong><br/>' + book_data['abstract']['rest']
334         ))
335
336         return d
337
338     def describe_category(self, category):
339         t = []
340         while category:
341             c = WOBLINK_CATEGORIES[category]
342             t.append(c['name'])
343             category = c.get('parent')
344         return ' / '.join(reversed(t))
345
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(
350             self.ADD_URL,
351             data={
352                 'AddPublication[pubType]': 'ebook',
353                 'AddPublication[pubHasIsbn]': '1',
354                 'AddPublication[pubIsbn]': isbn,
355                  ##AddPubation[save]
356             }
357         )
358         m = re.search(r'/(\d+)$', response.url)
359         if m is not None:
360             return m.group(1)
361
362     def send_book(self, shop, book, changes=None):
363         wldoc = book.wldocument(librarian2=True, changes=changes, publishable=False) # TODO pub
364         meta = wldoc.meta
365
366         book_data = self.get_book_data(shop, wldoc)
367
368         if not book.woblink_id:
369             #book.woblink_id = 2959868
370             woblink_id = self.create_book(book_data['isbn'])
371             assert woblink_id
372             book.woblink_id = woblink_id
373             book.save(update_fields=['woblink_id'])
374
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         self.send_cover(book.woblink_id, wldoc)
379         texts = shop.get_texts()
380         self.send_epub(
381             book.woblink_id, wldoc, book.gallery_path(),
382             fundraising=texts
383         )
384         self.send_mobi(
385             book.woblink_id, wldoc, book.gallery_path(),
386             fundraising=texts
387         )
388         self.edit_step4(book.woblink_id, book_data)
389         self.edit_step5(book.woblink_id, book_data)
390
391     def get_book_data(self, shop, wldoc, errors=None):
392         return {
393             "title": wldoc.meta.title,
394             "isbn": self.get_isbn(wldoc.meta, errors=errors),
395             "authors": self.get_authors_data(wldoc.meta, errors=errors),
396             "abstract": self.get_abstract(
397                 wldoc, errors=errors, description_add=shop.description_add
398             ),
399             "lang2code": self.get_lang2code(wldoc.meta, errors=errors),
400             "genres": self.get_genres(wldoc.meta, errors=errors),
401             "price": self.get_price(shop, wldoc, errors=errors),
402             "series": self.get_series(wldoc.meta, errors=errors),
403         }
404
405     def with_form_name(self, data, name):
406         return {
407             f"{name}[{k}]": v
408             for (k, v) in data.items()
409         }
410
411     def edit_step1(self, woblink_id, book_data):
412         data = book_data
413
414         authors_data = [
415             {
416                 "AhpPubId": woblink_id,
417                 "AhpAutId": author_id,
418                 "AhpType": author_type,
419             }
420             for (author_type, author_id) in data['authors']
421         ]
422
423         series_data = [
424             {
425                 'PublicationId': woblink_id,
426                 'SeriesId': series_id,
427             }
428             for series_id in data['series']
429         ]
430
431         d = {
432             'pubTitle': book_data['title'],
433             'npwAuthorHasPublications': json.dumps(authors_data),
434             'pubShortNote': data['abstract']['header'],
435             'pubNote': data['abstract']['rest'],
436             'pubCulture': data['lang2code'],
437             'npwPublicationHasAwards': '[]',
438             'npwPublicationHasSeriess': json.dumps(series_data),
439         }
440         d = self.with_form_name(d, 'EditPublicationStep1')
441         d['roles'] = [author_type for (author_type, author_id) in data['authors']]
442         r = self.session.post(self.STEP1_URL % woblink_id, data=d)
443         return r
444
445
446     def edit_step2(self, woblink_id, book_data):
447         gd = {}
448         legacy = None
449         for i, g in enumerate(book_data['genres']):
450             gdata = WOBLINK_CATEGORIES[g]
451             if legacy is None:
452                 legacy = gdata.get('legacy')
453             if p := gdata.get('parent'):
454                 gd.setdefault(p, {'isMain': False})
455                 gd[p].setdefault('children', [])
456                 gd[p]['children'].append(str(g))
457                 gd[p].setdefault('mainChild', str(g))
458                 if legacy is None:
459                     legacy = WOBLINK_CATEGORIES[p].get('legacy')
460             else:
461                 gd.setdefault(g, {})
462                 gd[g]['isMain'] = True
463         gd = [
464             {
465                 "pubId": woblink_id,
466                 "category": str(k),
467                 **v
468             }
469             for k, v in gd.items()
470         ]
471
472         data = {
473             'npwPublicationHasNewGenres': json.dumps(gd),
474             'genre': legacy or '',
475         }
476         data = self.with_form_name(data, 'AddPublicationStep2')
477         return self.session.post(self.STEP2_URL % woblink_id, data=data)
478
479     def edit_step3(self, woblink_id, book_data):
480         d = {
481             'pubBasePrice': book_data['price'],
482             'pubPremiereDate': date.today().isoformat(),
483             'pubIsLicenseIndefinite': '1',
484             'pubFileFormat': 'epub+mobi',
485             'pubIsAcs': '0',
486             'pubPublisherIndex': '',
487         }
488         d = self.with_form_name(d, 'EditPublicationStep3')
489         return self.session.post(self.STEP3_URL % woblink_id, data=d)
490
491     def edit_step4(self, woblink_id, book_data):
492         d = {}
493         d = self.with_form_name(d, 'EditPublicationStep4')
494         return self.session.post(self.STEP4_URL % woblink_id, data=d)
495
496     def edit_step5(self, woblink_id, book_data):
497         d = {}
498         d = self.with_form_name(d, 'EditPublicationStep5')
499         return self.session.post(self.STEP5_URL % woblink_id, data=d)
500
501     def wait_for_job(self, job_id):
502         while True:
503             response = self.session.post(
504                 self.JOB_STATUS_URL,
505                 data={'ids[]': job_id}
506             )
507             data = response.json()[job_id]
508             if data['ready']:
509                 assert data['successful']
510                 return
511             sleep(2)
512
513     def upload_file(self, woblink_id, filename, content, form_name, field_name, mime_type):
514         data = {
515             'pubId': woblink_id,
516         }
517         files = {
518             field_name: (filename, content, mime_type)
519         }
520         response = self.session.post(
521             self.UPLOAD_URL % field_name,
522             data=self.with_form_name(data, form_name),
523             files=self.with_form_name(files, form_name),
524         )
525         resp_data = response.json()
526         assert resp_data['success'] is True
527         if 'jobId' in resp_data:
528             self.wait_for_job(resp_data['jobId'])
529
530     def generate_demo(self, woblink_id, file_format, check=True):
531         percent = 10
532         while True:
533             job_id = self.session.get(
534                 self.GENERATE_DEMO_URL % (file_format, woblink_id, percent),
535             ).json()['jobId']
536             try:
537                 self.wait_for_job(job_id)
538             except AssertionError:
539                 if percent < 50:
540                     percent += 10
541                 else:
542                     raise
543             else:
544                 break
545
546         if check:
547             self.wait_for_job(
548                 self.session.get(
549                     self.CHECK_DEMO_URL % (file_format, woblink_id)
550                 ).json()['jobId']
551             )
552
553     def send_epub(self, woblink_id, doc, gallery_path, fundraising=None):
554         from librarian.builders import EpubBuilder
555         content = EpubBuilder(
556             base_url='file://' + gallery_path + '/',
557             fundraising=fundraising or [],
558         ).build(doc).get_file()
559         self.upload_file(
560             woblink_id,
561             doc.meta.url.slug + '.epub',
562             content,
563             'UploadEpub',
564             'epub',
565             'application/epub+zip'
566         )
567         self.generate_demo(woblink_id, 'epub')
568
569     def send_mobi(self, woblink_id, doc, gallery_path, fundraising=None):
570         from librarian.builders import MobiBuilder
571         content = MobiBuilder(
572             base_url='file://' + gallery_path + '/',
573             fundraising=fundraising or [],
574         ).build(doc).get_file()
575         self.upload_file(
576             woblink_id,
577             doc.meta.url.slug + '.mobi',
578             content,
579             'UploadMobi',
580             'mobi',
581             'application/x-mobipocket-ebook'
582         )
583         self.generate_demo(woblink_id, 'mobi', check=False)
584
585     def send_cover(self, woblink_id, doc):
586         from librarian.cover import make_cover
587         # TODO Labe
588         # A5 @ 300ppi.
589         cover = make_cover(doc.meta, cover_class='m-label', width=1748, height=2480)
590         content = io.BytesIO()
591         cover.final_image().save(content, cover.format)
592         content.seek(0)
593         self.upload_file(
594             woblink_id,
595             doc.meta.url.slug + '.jpeg',
596             content,
597             'UploadCover',
598             'cover',
599             cover.mime_type()
600         )