fix stats api
[redakcja.git] / src / depot / publishers / legimi.py
1 from datetime import date
2 import re
3 from django.conf import settings
4 from django.utils.html import escape
5 from django.utils.safestring import mark_safe
6 from librarian.functions import lang_code_3to2
7 from librarian.builders import EpubBuilder, MobiBuilder
8 from librarian.covers.marquise import MarquiseCover, LabelMarquiseCover
9 from catalogue.models import Audience
10 from .base import BasePublisher
11
12
13 class Legimi(BasePublisher):
14     BASE_URL = 'https://panel.legimi.pl'
15     LOGIN_URL = BASE_URL + '/publishers/membership'
16     UPLOAD_URL = BASE_URL + '/administration/upload/start'
17     CREATE_URL = BASE_URL + '/publishers/publications/create'
18     EDIT_URL = BASE_URL + '/publishers/publications/edit/%s'
19     EDIT_FILES_URL = BASE_URL + '/publishers/publications/editfiles/%s'
20     EDIT_SALE_URL = BASE_URL + '/publishers/publications/editsale/%s'
21
22     CATEGORIES = {
23         'Dla dzieci i młodzieży': 94,
24         'Książki dla dzieci': 15,
25         'Literatura młodzieżowa': 24,
26         'Kryminał': 29,
27         'Kryminał klasyczny': 31,
28         'Kryminał współczesny': 32,
29         'Kryminał historyczny': 30,
30         'default': 8886,
31         'Edukacja': 10,
32         'Słowniki i leksykony': 14,
33         'Encyklopedie': 13,
34         'Lektury': 11,
35         'Starożytność': 80,
36         'Barok': 83,
37         'Oświecenie': 84,
38         'Dwudziestolecie międzywojenne': 88,
39         'Średniowiecze': 81,
40         'Współczesność': 90,
41         'Modernizm': 87,
42         'Pozytywizm': 86,
43         'Renesans': 82,
44         'Romantyzm': 85,
45         'Młoda Polska': 89,
46         'Podręczniki': 52,
47         'Fantastyka i sci-fi': 25,
48         'Fantastyka': 26,
49         'Science fiction': 27,
50         'Języki obce': 59,
51         'Antyki i kolekcjonerstwo': 53,
52         'Astrologia i wróżbiarstwo': 54,
53         'Zdrowie i rodzina': 57,
54         'Hobby': 55,
55         'Medycyna i zdrowie': 58,
56         'Psychologiczne': 78,
57         'Styl': 56,
58         'Humanistyka': 97,
59         'Kultura i sztuka': 64,
60         'Film': 66,
61         'Muzyka': 65,
62         'Eseje literackie': 49,
63         'Historia': 60,
64         'Styl życia': 73,
65         'Wakacje i podróże': 69,
66         'Dla mężczyzn': 79,
67         'Sport': 76,
68         'Obyczajowe i romanse': 93,
69         'Humor': 68,
70         'Obyczajowe': 35,
71         'Powieść': 41,
72         'Powieść przygodowa': 42,
73         'Współczesna powieść przygodowa': 44,
74         'Historyczna powieść przygodowa': 43,
75         'Powieść historyczna': 46,
76         'Powieść psychologiczna': 47,
77         'Powieść religijna': 45,
78         'Romans': 36,
79         'Romans klasyczny': 38,
80         'Romans współczesny': 39,
81         'Literatura erotyczna': 40,
82         'Romans historyczny': 37,
83         'Dla kobiet': 77,
84         'Sensacja, thriller, horror': 91,
85         'Horror': 28,
86         'Sensacja': 33,
87         'Thriller': 34,
88         'Aktualności': 70,
89         'Czasopisma': 71,
90         'Literatura faktu, reportaże, biografie': 92,
91         'Literatura faktu': 16,
92         'Biografie': 17,
93         'Publicystyka': 20,
94         'Dzienniki': 19,
95         'Dokument, esej': 18,
96         'Historia literatury i krytyka literacka': 23,
97         'Literatura popularnonaukowa': 22,
98         'Reportaż': 21,
99         'Społeczno-polityczne': 72,
100         'Poezja i dramat': 95,
101         'Dramat': 48,
102         'Poezja': 50,
103         'Religia i duchowość': 51,
104         'Nauka i nowe technologie': 98,
105         'Nauka i technika': 61,
106         'Nauki ścisłe': 62,
107         'Nauki humanistyczne': 63,
108         'Technologia i Internet': 75,
109         'Specjalistyczne': 99,
110         'Biznes i finanse': 1,
111         'Ekonomia': 5,
112         'Finanse': 6,
113         'Zarządzanie': 3,
114         'Marketing': 2,
115         'Rozwój osobisty': 7,
116         'Kariera i sukces zawodowy': 8,
117         'Psychologia, motywacja': 9,
118         'PR': 4,
119         'Prawo': 67,
120         'Branżowe': 74,
121     }
122
123     def login(self):
124         self._session.post(
125             self.LOGIN_URL,
126             data={
127                 'ValidationTrue': 'true',
128                 'UserName': self.username,
129                 'Password': self.password,
130             })
131
132     def can_publish(self, shop, book):
133         meta = book.wldocument(librarian2=True).meta
134         d = {
135             'errors': [],
136             'warnings': [],
137             'info': []
138         }
139         thema = self.get_thema(meta)
140         if thema:
141             d['info'].append(mark_safe(
142                 "w kategorii " + ", ".join(
143                     "<b><tt>{code}</tt></b>".format(code=escape(t))
144                     for t in thema
145                 )
146             ))
147             if not meta.thema_main:
148                 d['warnings'].append('Brak głównej kategorii Thema')
149         else:
150             d['errors'].append('Brak kategorii Thema.')
151         return d
152
153     def list(self):
154         return self.session.get('https://wydawca.legimi.com/publishers/publications')
155
156     def upload(self, content):
157         response = self.session.post(
158             self.UPLOAD_URL,
159             files={
160                 "files": content,
161             })
162         model = response.json()['model']
163         return {
164             "name": model['Name'],
165             "token": model['Token'],
166             "url": model['Url'],
167         }
168
169     def get_thema(self, meta):
170         thema = []
171         if meta.thema_main:
172             thema.append(meta.thema_main)
173         thema.extend(meta.thema)
174
175         thema.extend(
176             Audience.objects.filter(code__in=meta.audiences).exclude(
177                 thema=None).values_list('thema', flat=True)
178         )
179         return thema
180
181     def send_book(self, shop, book, changes=None):
182         wlbook = book.wldocument(librarian2=True, changes=changes)
183         meta = wlbook.meta
184
185         cover = LabelMarquiseCover(meta, width=1200).output_file()
186         texts = shop.get_texts()
187         epub_file = EpubBuilder(
188             cover=MarquiseCover,
189             fundraising=texts,
190             base_url='file://' + book.gallery_path() + '/'
191         ).build(wlbook).get_file()
192         mobi_file = MobiBuilder(
193             cover=MarquiseCover,
194             fundraising=texts,
195             base_url='file://' + book.gallery_path() + '/'
196         ).build(wlbook).get_file()
197
198         book_data = {
199             "Title": meta.title,
200             "Author": ", ".join(p.readable() for p in meta.authors),
201             "Year": str(date.today().year),
202
203             'GenreId': str(self.get_genre(wlbook)),
204             'themaCategories': ';'.join(self.get_thema(meta)),
205             'thema-search': '',
206             'Isbn': '',
207             'LanguageLocale': lang_code_3to2(meta.language),
208
209             'Description': self.get_description(wlbook, shop.description_add),
210         }
211         if meta.isbn_html:
212             isbn = meta.isbn_html
213             if isbn.upper().startswith(('ISBN ', 'ISBN-')):
214                 isbn = isbn[5:]
215             isbn = isbn.strip()
216             book_data['Isbn'] = isbn
217
218         files_data = {}
219
220         cover_data = self.upload(
221             (meta.url.slug + '.jpg', cover.get_file(), 'image/jpeg')
222         )
223         book_data.update({
224             "Cover.Name": cover_data['name'],
225             "Cover.Token": cover_data['token'],
226             "Cover.Url": cover_data['url'],
227         })
228
229         epub_data = self.upload(
230             (meta.url.slug + '.epub', epub_file, 'application/epub+zip')
231         )
232         files_data.update({
233             'BookEpub.Token': epub_data['token'],
234             'BookEpub.Name': epub_data['name'],
235             'SampleEpubType': 'Generation',
236         })
237
238         mobi_data = self.upload(
239             (meta.url.slug + '.mobi', mobi_file, 'application/x-mobipocket-ebook')
240         )
241         files_data.update({
242             'BookMobi.Token': mobi_data['token'],
243             'BookMobi.Name': mobi_data['name'],
244         })
245
246         if book.legimi_id:
247             self.edit(
248                 book.legimi_id,
249                 book_data
250             )
251             self.edit_files(
252                 book.legimi_id,
253                 files_data
254             )
255         else:
256             legimi_id = self.create_book(book_data, files_data)
257             if legimi_id:
258                 book.legimi_id = legimi_id
259                 book.save(update_fields=['legimi_id'])
260
261         self.edit_sale(book)
262
263     def get_genre(self, wlbook):
264         if wlbook.meta.legimi and wlbook.meta.legimi in self.CATEGORIES:
265             return self.CATEGORIES[wlbook.meta.legimi]
266         for epoch in wlbook.meta.epochs:
267             if epoch in self.CATEGORIES:
268                 return self.CATEGORIES[epoch]
269         return self.CATEGORIES['Lektury']
270
271     def create_book(self, book_data, files_data):
272         data = {
273             'createValidationTrue': 'true',
274             'PublisherId': self.publisher_handle,
275             'IsLibraryPass': 'False',
276
277             'SamplesGenerationType': 'Quantity',
278             'SamplesGenerationPercent': '10',
279
280             'EnterToTheMarketType': 'No',
281             'EnterToTheMarketDate': '',
282             'HidingDate': '',
283             'SalesNoLimitOption': 'false',
284             'SalesNoLimitKindle': 'false',
285             'SalesInStoreEbookGrossValue': '0,00',
286             'SalesPromotion': 'False',
287             'SalesPromotionGrossValue': '0,00',
288             'SalesPromotionDatesRange.DateStart': '',
289             'SalesPromotionDatesRange.DateEnd': '',
290         }
291
292         for form in 'Epub', 'Mobi', 'Pdf':
293             data.update({
294                 f'Book{form}.Token': '',
295                 f'Book{form}.Name': '',
296                 f'Book{form}.StorageName': '',
297                 f'Book{form}.Order': '',
298
299                 f'Sample{form}Type': 'Files',
300                 f'Sample{form}.Token': '',
301                 f'Sample{form}.Name': '',
302                 f'Sample{form}.StorageName': '',
303                 f'Sample{form}.Order': '',
304             })
305
306         data.update(book_data)
307         data.update(files_data)
308
309         response = self.session.post(self.CREATE_URL, data=data)
310         m = re.search(r'/(\d+)$', response.url)
311         if m is not None:
312             return m.group(1)
313
314     def edit(self, legimi_id, data):
315         current = {
316             'ValidationTrue': 'true',
317             'Id': legimi_id
318         }
319
320         current.update(data)
321
322         self.session.post(
323             self.EDIT_URL % legimi_id,
324             data=current
325         )
326
327     def edit_files(self, legimi_id, files_data):
328         current = {
329             'ValidationTrue': 'true',
330             'Id': legimi_id,
331             'SamplesGenerationType': 'Quantity',
332             'SamplesGenerationPercent': '10',
333         }
334
335         for form in 'Epub', 'Mobi', 'Pdf':
336             current.update({
337                 f'Book{form}.Token': '',
338                 f'Book{form}.Name': '',
339                 f'Book{form}.StorageName': '',
340                 f'Book{form}.Order': '',
341
342                 f'Sample{form}.Type': 'Files',
343                 f'Sample{form}.Token': '',
344                 f'Sample{form}.Name': '',
345                 f'Sample{form}.StorageName': '',
346                 f'Sample{form}.Order': '',
347             })
348
349         current.update(files_data)
350
351         response = self.session.post(
352             self.EDIT_FILES_URL % legimi_id,
353             data=current
354         )
355
356     def edit_sale(self, book):
357         assert book.legimi_id
358
359         words = book.wldocument(librarian2=True).get_statistics()['total']['words_with_fn']
360
361         price = settings.LEGIMI_SMALL_PRICE
362         if words > settings.LEGIMI_SMALL_WORDS:
363             price = settings.LEGIMI_BIG_PRICE
364
365         abo = 'true' if words > settings.LEGIMI_BIG_WORDS else 'false'
366
367         data = {
368             'ValidationTrue': 'true',
369             'Id': book.legimi_id,
370             'SalesPromotionId': "0",
371             'IsLibraryPass': "False",
372             'OriginalEnterToTheMarketType': "No",
373             'OriginalHidingDate': "",
374             'OriginalEnterToTheMarketDate': "",
375             'EnterToTheMarketType': "Yes",
376             'EnterToTheMarketDate': "",
377             'HidingDate': "",
378             'SalesNoLimitOption': abo,
379             'SalesNoLimitKindle': abo,
380             'SalesInStoreEbookGrossValue': f'{price},00',
381             'SalesPromotion': "False",
382             'SalesPromotionGrossValue': "0,00",
383             'SalesPromotionDatesRange.DateStart': "",
384             'SalesPromotionDatesRange.DateEnd': "",
385         }
386
387         self.session.post(
388             self.EDIT_SALE_URL % book.legimi_id,
389             data=data
390         )