-
Notifications
You must be signed in to change notification settings - Fork 34
/
check_epub.py
2121 lines (1871 loc) · 101 KB
/
check_epub.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import unicode_literals, division, absolute_import, print_function
__license__ = 'GPL v3'
__copyright__ = '2011, Grant Drake'
try:
load_translations()
except NameError:
pass # load_translations() added in calibre 1.9
from polyglot.builtins import unicode_type, is_py3
from six import text_type as unicode
from six.moves.urllib.parse import unquote as urlunquote
import traceback, os, posixpath, six.moves.urllib.request, six.moves.urllib.parse, six.moves.urllib.error, re
try:
from cgi import escape as esc
except:
from html import escape as esc
from lxml import etree
from calibre import guess_type
from calibre.gui2 import error_dialog
from calibre.ebooks.chardet import xml_to_unicode
from calibre.ebooks.conversion.preprocess import HTMLPreProcessor
from calibre.ebooks.metadata.epub import Encryption
from calibre.ebooks.oeb.base import XPath
from calibre.ebooks.oeb.parse_utils import RECOVER_PARSER, NotHTML, parse_html
from calibre.utils.zipfile import ZipFile, BadZipfile
from calibre_plugins.quality_check.check_base import BaseCheck
from calibre_plugins.quality_check.dialogs import SearchEpubDialog
from calibre_plugins.quality_check.helpers import get_title_authors_text
META_INF = {
'container.xml' : True,
'manifest.xml' : False,
'encryption.xml' : False,
'metadata.xml' : False,
'signatures.xml' : False,
'rights.xml' : False,
}
ITUNES_FILES = ['iTunesMetadata.plist', 'iTunesArtwork']
BOOKMARKS_FILES = ['META-INF/calibre_bookmarks.txt']
OS_FILES = ['.DS_Store', 'thumbs.db']
ALL_ARTIFACTS = ITUNES_FILES + BOOKMARKS_FILES + OS_FILES
IMAGE_FILES = ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.bmp']
FONT_FILES = ['.otf', '.ttf']
CSS_FILES = ['.xpgt', '.css']
OPF_FILES = ['.opf']
NCX_FILES = ['.ncx']
JAVASCRIPT_FILES = ['.js']
CRAP_FILES = ['.thmx','.plist']
EPUB_FILES = ['.epub']
NON_HTML_FILES = IMAGE_FILES + FONT_FILES + CSS_FILES + OPF_FILES + NCX_FILES + JAVASCRIPT_FILES + CRAP_FILES + EPUB_FILES
NCX_NS = 'http://www.daisy.org/z3986/2005/ncx/'
ENCRYPTION_PATH = 'META-INF/encryption.xml'
RE_HTML_BODY = re.compile(u'<body[^>]*>(.*)</body>', re.UNICODE | re.DOTALL)
RE_STRIP_MARKUP = re.compile(u'<[^>]+>', re.UNICODE)
RE_WHITESPACE = re.compile(r'\s+', re.UNICODE | re.DOTALL)
OCF_NS = 'urn:oasis:names:tc:opendocument:xmlns:container'
OPF_NS = 'http://www.idpf.org/2007/opf'
class InvalidEpub(ValueError):
pass
class EpubCheck(BaseCheck):
'''
All checks related to working with ePub formats.
'''
def __init__(self, gui):
BaseCheck.__init__(self, gui, 'formats:epub')
self.html_preprocessor = HTMLPreProcessor()
self.input_encoding = 'utf-8'
def perform_check(self, menu_key):
if menu_key == 'check_epub_jacket':
self.check_epub_jacket(check_has_jacket=True)
elif menu_key == 'check_epub_legacy_jacket':
self.check_epub_jacket(check_has_jacket=True, check_legacy_only=True)
elif menu_key == 'check_epub_multi_jacket':
self.check_epub_multiple_jacket()
elif menu_key == 'check_epub_no_jacket':
self.check_epub_jacket(check_has_jacket=False)
elif menu_key == 'check_epub_namespaces':
self.check_epub_namespaces()
elif menu_key == 'check_epub_non_dc_meta':
self.check_epub_non_dc_metadata()
elif menu_key == 'check_epub_files_missing':
self.check_epub_opf_files_missing()
elif menu_key == 'check_epub_xpgt':
self.check_epub_xpgt_margins()
elif menu_key == 'check_epub_inline_xpgt':
self.check_epub_inline_xpgt_links()
elif menu_key == 'check_epub_unman_files':
self.check_epub_unmanifested_files()
elif menu_key == 'check_epub_unused_css':
self.check_epub_unused_css_files()
elif menu_key == 'check_epub_unused_images':
self.check_epub_unused_images()
elif menu_key == 'check_epub_broken_images':
self.check_epub_broken_image_links()
elif menu_key == 'check_epub_itunes':
self.check_epub_files(ITUNES_FILES, _('iTunes files'), 'epub_itunes', show_log=True)
elif menu_key == 'check_epub_bookmark':
self.check_epub_files(BOOKMARKS_FILES, _('calibre bookmarks'), 'epub_calibre_bookmarks', show_log=False)
elif menu_key == 'check_epub_os_artifacts':
self.check_epub_files(OS_FILES, _('OS artifacts'), 'epub_os_artifacts', show_log=True)
elif menu_key == 'check_epub_repl_cover':
self.check_epub_replaceable_cover(check_has_cover=True)
elif menu_key == 'check_epub_no_repl_cover':
self.check_epub_replaceable_cover(check_has_cover=False)
elif menu_key == 'check_epub_svg_cover':
self.check_epub_calibre_svg_cover(check_has_svg_cover=True)
elif menu_key == 'check_epub_no_svg_cover':
self.check_epub_calibre_svg_cover(check_has_svg_cover=False)
elif menu_key == 'check_epub_toc_hierarchy':
self.check_epub_toc_hierarchical()
elif menu_key == 'check_epub_toc_size':
self.check_epub_toc_size()
elif menu_key == 'check_epub_toc_broken':
self.check_epub_toc_broken_links()
elif menu_key == 'check_epub_guide_broken':
self.check_epub_guide_broken_links()
elif menu_key == 'check_epub_html_size':
self.check_epub_html_size()
elif menu_key == 'check_epub_drm':
self.check_epub_drm()
elif menu_key == 'check_epub_drm_meta':
self.check_epub_drm_meta()
elif menu_key == 'check_epub_converted':
self.check_epub_conversion(check_converted=True)
elif menu_key == 'check_epub_not_converted':
self.check_epub_conversion(check_converted=False)
elif menu_key == 'check_epub_corrupt_zip':
self.check_epub_corrupt_zip()
elif menu_key == 'check_epub_no_container':
self.check_epub_no_container()
elif menu_key == 'check_epub_address':
self.check_epub_address()
elif menu_key == 'check_epub_fonts':
self.check_epub_embedded_fonts()
elif menu_key == 'check_epub_font_faces':
self.check_epub_font_faces()
elif menu_key == 'check_epub_css_justify':
self.check_epub_css_justify()
elif menu_key == 'check_epub_css_margins':
self.check_epub_css_margins()
elif menu_key == 'check_epub_css_no_margins':
self.check_epub_css_no_margins()
elif menu_key == 'check_epub_inline_margins':
self.check_epub_inline_margins()
elif menu_key == 'check_epub_javascript':
self.check_epub_javascript()
elif menu_key == 'check_epub_smarten_punc':
self.check_epub_smarten_punctuation()
elif menu_key == 'check_epub_inside_epub':
self.check_epub_inside_epub()
elif menu_key == 'search_epub':
self.search_epub()
else:
return error_dialog(self.gui, _('Quality Check failed'),
_('Unknown menu key for %s of \'%s\'')%('EpubCheck', menu_key),
show=True, show_copy_button=False)
def zf_read(self, zf, name):
data = zf.read(name)
if is_py3:
return data.decode('utf-8', errors='replace')
return data
def search_epub(self):
'''
Search epubs for text matching the user's criteria
'''
d = SearchEpubDialog(self.gui)
d.exec_()
if d.result() != d.Accepted:
return
self.search_opts = d.search_options
re_options = re.UNICODE + re.DOTALL
if self.search_opts['ignore_case']:
re_options |= re.IGNORECASE
self.log('*** Searching for expression: <span style="color:blue"><b>%s</b></span> ***' % esc(self.search_opts['previous_finds'][0]))
self.search_expression = re.compile(self.search_opts['previous_finds'][0], re_options)
def evaluate_book(book_id, db):
path_to_book = db.format_abspath(book_id, 'EPUB', index_is_id=True)
if not path_to_book:
self.log.error('ERROR: EPUB format is missing: ', get_title_authors_text(db, book_id))
return False
def search_for_match(text, show_all_matches):
matches = []
text = text.replace(' ', ' ')
for m in self.search_expression.finditer(text):
# Get the previous and following characters
CHARS = 25
prefix = suffix = ''
start = m.start()
end = start + len(m.group())
if start >= CHARS:
prefix = text[start-CHARS:start]
else:
prefix = text[0:start]
if end + CHARS <= len(text):
suffix = text[end:end+CHARS]
else:
suffix = text[end:len(text)]
prefix = RE_WHITESPACE.sub(' ', prefix)
suffix = RE_WHITESPACE.sub(' ', suffix)
matches.append('\t<span style="color:darkgray">%s</span> <span style="color:green">...%s<span style="color:orange"><b>%s</b></span>%s...</span>'%(
resource_name, esc(prefix), esc(m.group()), esc(suffix)))
if not show_all_matches:
break
if matches:
log_lines.extend(matches)
return bool(matches)
try:
show_all_matches = self.search_opts['show_all_matches']
with ZipFile(path_to_book, 'r') as zf:
contents = zf.namelist()
log_lines = []
for resource_name in contents:
extension = resource_name[resource_name.rfind('.'):].lower()
check_file = extract_body_text = False
if extension not in NON_HTML_FILES:
extract_body_text = self.search_opts['scope_plaintext']
check_file = self.search_opts['scope_html'] or extract_body_text
elif extension in CSS_FILES:
check_file = self.search_opts['scope_css']
elif extension in OPF_FILES:
check_file = self.search_opts['scope_opf']
elif extension in NCX_FILES:
check_file = self.search_opts['scope_ncx']
if check_file:
content = zf.read(resource_name).decode('utf-8',errors='replace')
if extract_body_text:
content = self._extract_body_text(content)
if search_for_match(content, show_all_matches):
if not show_all_matches:
break
if self.search_opts['scope_zip']:
filename = os.path.basename(resource_name)
if search_for_match(filename, show_all_matches):
if not show_all_matches:
break
if log_lines:
if show_all_matches:
self.log('%s '%len(log_lines) + _('Matches in book: <b>%s</b>')%get_title_authors_text(db, book_id))
else:
self.log(_('First match in book: <b>%s</b>')%get_title_authors_text(db, book_id))
for log_line in log_lines:
self.log(log_line)
return True
return False
except InvalidEpub as e:
self.log.error(_('Invalid epub:'), e)
return False
except:
self.log.error(_('ERROR parsing book: '), path_to_book)
self.log(traceback.format_exc())
return False
self.check_all_files(evaluate_book,
no_match_msg=_('No searched ePub books have your search text'),
marked_text='epub_search_text',
status_msg_type=_('ePub books for search text'))
def check_epub_jacket(self, check_has_jacket, check_legacy_only=False):
def evaluate_book(book_id, db):
path_to_book = db.format_abspath(book_id, 'EPUB', index_is_id=True)
if not path_to_book:
self.log.error(_('ERROR: EPUB format is missing: '), get_title_authors_text(db, book_id))
return not check_has_jacket
try:
with ZipFile(path_to_book, 'r') as zf:
for resource_name in self._manifest_worthy_names(zf):
if 'jacket' in resource_name and resource_name.endswith('.xhtml'):
html = zf.read(resource_name).decode('utf-8')
if not check_legacy_only and self._is_current_jacket(html):
return check_has_jacket
if self._is_legacy_jacket(html):
return check_has_jacket
return not check_has_jacket
except InvalidEpub as e:
self.log.error(_('Invalid epub:'), e)
return not check_has_jacket
except:
self.log.error(_('ERROR parsing book: '), path_to_book)
self.log(traceback.format_exc())
return not check_has_jacket
if check_legacy_only:
msg = _('No searched ePub books have legacy jackets')
marked_text = 'epub_has_legacy_jacket'
elif check_has_jacket:
msg = _('No searched ePub books have jackets')
marked_text = 'epub_has_jacket'
else:
msg = _('All searched ePub books have jackets')
marked_text = 'epub_missing_jacket'
self.check_all_files(evaluate_book,
status_msg_type=_('ePub books for jackets'),
no_match_msg=msg, marked_text=marked_text)
def check_epub_multiple_jacket(self):
def evaluate_book(book_id, db):
path_to_book = db.format_abspath(book_id, 'EPUB', index_is_id=True)
if not path_to_book:
self.log.error(_('ERROR: EPUB format is missing: '), get_title_authors_text(db, book_id))
return False
try:
jacket_count = 0
with ZipFile(path_to_book, 'r') as zf:
for resource_name in self._manifest_worthy_names(zf):
if 'jacket' in resource_name and resource_name.endswith('.xhtml'):
html = self.zf_read(zf, resource_name)
if self._is_current_jacket(html) or \
self._is_legacy_jacket(html):
jacket_count += 1
return jacket_count > 1
except InvalidEpub as e:
self.log.error(_('Invalid epub:'), e)
return False
except:
self.log.error(_('ERROR parsing book: '), path_to_book)
self.log(traceback.format_exc())
return False
self.check_all_files(evaluate_book,
no_match_msg=_('No searched ePub books have multiple jackets'),
marked_text='epub_multiple_jacket',
status_msg_type=_('ePub books for multiple jackets'))
def _is_legacy_jacket(self, html):
if html.find('<h1 class="calibrerescale') != -1 or \
html.find('<h2 class="calibrerescale') != -1:
return True
return False
def _is_current_jacket(self, html):
if html.find('<meta content="jacket" name="calibre-content"') != -1 or \
html.find('<meta name="calibre-content" content="jacket"') != -1:
return True
return False
def check_epub_xpgt_margins(self):
TEMPLATE_MIME_TYPES = ['application/adobe-page-template+xml',
'application/vnd.adobe-page-template+xml',
'application/vnd.adobe.page-template+xml']
def evaluate_book(book_id, db):
path_to_book = db.format_abspath(book_id, 'EPUB', index_is_id=True)
if not path_to_book:
self.log.error(_('ERROR: EPUB format is missing: '), get_title_authors_text(db, book_id))
return False
try:
displayed_path = False
with ZipFile(path_to_book, 'r') as zf:
opf_name = self._get_opf_xml(path_to_book, zf)
if opf_name:
for mt in TEMPLATE_MIME_TYPES:
xpgt_name = self._get_opf_item(zf, opf_name,
xpath=unicode_type(r'child::opf:manifest/opf:item'
'[@media-type="%s"]')%mt)
if xpgt_name:
if not displayed_path:
displayed_path = True
self.log('<b>%s</b>'%get_title_authors_text(db, book_id))
xpgt_content = self.zf_read(zf, xpgt_name)
if 'margin' in xpgt_content:
self.log('\t<span style="color:darkgray">Margins still present in: %s</span>'%xpgt_name)
return True
self.log('\t<span style="color:darkgray">XPGT has no margins: %s</span>'%xpgt_name)
break
return False
except InvalidEpub as e:
self.log.error('Invalid epub:', e)
return False
except:
self.log.error('ERROR parsing book: ', path_to_book)
self.log(traceback.format_exc())
return False
self.check_all_files(evaluate_book,
no_match_msg=_('No searched ePub books have non-zero .xpgt margins'),
marked_text='epub_xpgt_margins',
status_msg_type=_('ePub books for .xpgt margins'))
def check_epub_inline_xpgt_links(self):
RE_LINK = re.compile(r'<link[^>]+?href\s*=\s*".*?\.xpgt"[^>]*?>', re.UNICODE)
RE_CSS_IMPORT1 = re.compile(r'@import url\([\'\"]*(.*?)[\'"]*\)', re.UNICODE | re.DOTALL)
RE_CSS_IMPORT2 = re.compile(r'@import\s+"(.*?)"', re.UNICODE | re.DOTALL)
def check_for_import_xpgt(data):
for match in RE_CSS_IMPORT1.finditer(data):
self.log('Match1', match.group(0))
if match.group(1).lower().endswith('.xpgt'):
return True
for match in RE_CSS_IMPORT2.finditer(data):
self.log('Match2', match.group(0))
if match.group(1).lower().endswith('.xpgt'):
return True
def evaluate_book(book_id, db):
path_to_book = db.format_abspath(book_id, 'EPUB', index_is_id=True)
if not path_to_book:
self.log.error('ERROR: EPUB format is missing: ', get_title_authors_text(db, book_id))
return False
try:
with ZipFile(path_to_book, 'r') as zf:
contents = zf.namelist()
for resource_name in contents:
extension = resource_name[resource_name.rfind('.'):].lower()
if extension in CSS_FILES:
data = self.zf_read(zf, resource_name).lower()
self.log(_('Checking css import'), resource_name)
if check_for_import_xpgt(data):
return True
elif extension in NON_HTML_FILES:
continue
else:
data = self.zf_read(zf, resource_name).lower()
if RE_LINK.search(data):
return True
self.log(_('Checking html import'), resource_name)
if check_for_import_xpgt(data):
return True
return False
except InvalidEpub as e:
self.log.error('Invalid epub:', e)
return False
except:
self.log.error('ERROR parsing book: ', path_to_book)
self.log(traceback.format_exc())
return False
self.check_all_files(evaluate_book,
no_match_msg=_('No searched ePub books have inline xpgt links'),
marked_text='epub_inline_xpgt_links',
status_msg_type=_('ePub books for inline xpgt links'))
def check_epub_unmanifested_files(self):
all_artifacts = [f.lower() for f in ALL_ARTIFACTS]
def evaluate_book(book_id, db):
path_to_book = db.format_abspath(book_id, 'EPUB', index_is_id=True)
if not path_to_book:
self.log.error('ERROR: EPUB format is missing: ', get_title_authors_text(db, book_id))
return False
try:
displayed_path = False
with ZipFile(path_to_book, 'r') as zf:
opf_name = self._get_opf_xml(path_to_book, zf)
if opf_name:
manifest_items_map = self._get_opf_items_map(zf, opf_name)
resource_names = list(self._manifest_worthy_names(zf))
for resource_name in resource_names:
if resource_name not in manifest_items_map:
# Special exclusion for bookmarks, itunes files and other OS artifacts
known_artifact = False
if resource_name.lower() in all_artifacts:
known_artifact = True
if not known_artifact:
for a in all_artifacts:
if resource_name.lower().endswith('/'+a):
known_artifact = True
break
if known_artifact:
if not displayed_path:
displayed_path = True
self.log('<b>%s</b>'%get_title_authors_text(db, book_id))
self.log('\t<span style="color:darkgray">Ignoring unmanifested file: %s</span>'%resource_name)
continue
if not displayed_path:
displayed_path = True
self.log('<b>%s</b>'%get_title_authors_text(db, book_id))
self.log('\t<span style="color:darkgray">Unmanifested file: %s</span>'%resource_name)
return True
return False
except InvalidEpub as e:
self.log.error('Invalid epub:', e)
return False
except:
self.log.error('ERROR parsing book: ', path_to_book)
self.log(traceback.format_exc())
return False
self.check_all_files(evaluate_book,
no_match_msg=_('No searched ePub books have unmanifested files'),
marked_text='epub_unmanifested_files',
status_msg_type=_('ePub books for unmanifested files'))
def check_epub_unused_css_files(self):
RE_CSS = r'<\s*link.*?\s+href\s*=\s*"[^"]*%s"'
def evaluate_book(book_id, db):
path_to_book = db.format_abspath(book_id, 'EPUB', index_is_id=True)
if not path_to_book:
self.log.error('ERROR: EPUB format is missing: ', get_title_authors_text(db, book_id))
return False
try:
with ZipFile(path_to_book, 'r') as zf:
contents = zf.namelist()
if self._is_drm_encrypted(zf, contents):
self.log.error(_('SKIPPING BOOK (DRM Encrypted): '), get_title_authors_text(db, book_id))
return False
# Build a list of regexes for all the css files in this epub
css_regexes = {}
html_resource_names = []
for resource_name in self._manifest_worthy_names(zf):
extension = resource_name[resource_name.rfind('.'):].lower()
if extension in CSS_FILES:
try:
css = os.path.basename(resource_name).lower()
css_enc = six.moves.urllib.request.pathname2url(css).lower()
except:
self.log.error(_('ERROR parsing book: '), path_to_book)
self.log.error(_('\tIssue with CSS name: '), resource_name)
self.log(traceback.format_exc())
return False
css_regexes[resource_name] = [re.compile(RE_CSS % css, re.UNICODE)]
if css_enc != css:
css_regexes[resource_name].append(re.compile(RE_CSS % css_enc, re.UNICODE))
elif extension not in NON_HTML_FILES:
html_resource_names.append(resource_name)
if css_regexes and html_resource_names:
for resource_name in html_resource_names:
data = self.zf_read(zf, resource_name).lower()
css_keys = list(css_regexes.keys())
for css_key in css_keys:
regexes = css_regexes[css_key]
for css_regex in regexes:
if css_regex.search(data):
css_regexes.pop(css_key)
break
if not css_regexes:
break
if css_regexes:
self.log(get_title_authors_text(db, book_id))
for resource_name in css_regexes.keys():
self.log(_('\tUnused CSS file: %s')%resource_name)
return True
return False
except InvalidEpub as e:
self.log.error('Invalid epub:', e)
return False
except:
self.log.error('ERROR parsing book: ', path_to_book)
self.log(traceback.format_exc())
return False
self.check_all_files(evaluate_book,
no_match_msg=_('No searched ePub books have unused CSS files'),
marked_text='epub_unused_css_files',
status_msg_type=_('ePub books for unused CSS files'))
def check_epub_unused_images(self):
RE_IMAGE = r'<(?:[a-z]*?\:)*?ima?ge?[^>]*?"[^"]*?%s"'
RE_IMAGE_STYLE = r'background-image:[^\'>]*?url\(\'?[^\)]*?%s\'?\)'
def check_for_images_in_html_resources(zf, image_regexes, image_name_regexes, resource_names):
for resource_name in resource_names:
data = self.zf_read(zf, resource_name)
image_keys = list(image_regexes.keys())
for image_key in image_keys:
regexes = image_regexes[image_key]
for image_regex in regexes:
if image_regex.search(data):
#self.log.info('\tFOUND (HTML): ', image_key, ' in: ', resource_name)
image_regexes.pop(image_key)
image_name_regexes.pop(image_key)
break
if not image_regexes:
break
def check_for_images_in_css_resources(zf, image_regexes, image_name_regexes, resource_names):
#self.log.info('*** Scanning CSS for images')
for resource_name in resource_names:
data = self.zf_read(zf, resource_name)
image_keys = list(image_name_regexes.keys())
for image_key in image_keys:
image_regex = image_name_regexes[image_key]
#self.log.info(' Scanning css for image: ', image_key, ' regex: ', image_regex)
if image_regex.search(data):
#self.log.info('\tFOUND (CSS): ', image_key, ' in: ', resource_name)
image_name_regexes.pop(image_key)
image_regexes.pop(image_key)
if not image_name_regexes:
break
def check_for_images_in_opf_cover_meta(path_to_book, zf, image_regexes, image_name_regexes):
#self.log.info('*** Scanning OPF for images')
opf_name = self._get_opf_xml(path_to_book, zf)
if not opf_name:
return
opf_xml = self._get_opf_tree(zf, opf_name)
covers = opf_xml.xpath(r'child::opf:metadata/opf:meta[@name="cover" and @content]',
namespaces={'opf':OPF_NS})
cover_id = None
if covers:
cover_id = covers[0].get('content')
if cover_id:
items = opf_xml.xpath(r'child::opf:manifest/opf:item',
namespaces={'opf':OPF_NS})
image_keys = list(image_name_regexes.keys())
for item in items:
if item.get('id', None) == cover_id:
item_href = item.get('href', None)
for image_key in image_keys:
image_regex = image_name_regexes[image_key]
#self.log.info(' Scanning opf meta for image: ', image_key, ' regex: ', image_regex)
if image_regex.search(item_href):
#self.log.info('\tFOUND (OPF): ', image_key)
image_name_regexes.pop(image_key)
image_regexes.pop(image_key)
if not image_name_regexes:
break
def evaluate_book(book_id, db):
path_to_book = db.format_abspath(book_id, 'EPUB', index_is_id=True)
if not path_to_book:
self.log.error(_('ERROR: EPUB format is missing: '), get_title_authors_text(db, book_id))
return False
try:
with ZipFile(path_to_book, 'r') as zf:
contents = zf.namelist()
if self._is_drm_encrypted(zf, contents):
self.log.error(_('SKIPPING BOOK (DRM Encrypted): '), get_title_authors_text(db, book_id))
return False
# Build a list of regexes for all the image files in this epub
image_regexes = {}
image_name_regexes = {}
html_resource_names = []
css_resource_names = []
for resource_name in self._manifest_worthy_names(zf):
extension = resource_name[resource_name.rfind('.'):].lower()
if extension in IMAGE_FILES:
# Use the base name for the image since relative path might differ from html
# compared to the opf manifest
try:
image = os.path.basename(resource_name)
image_enc = six.moves.urllib.request.pathname2url(image)
#self.log.info('Image: ', image)
except:
self.log.error('ERROR parsing book: ', path_to_book)
self.log.error(_('\tIssue with image name: '), resource_name)
self.log(traceback.format_exc())
return False
image_name_regexes[resource_name] = re.compile(image, re.UNICODE | re.IGNORECASE)
image_regexes[resource_name] = [re.compile(RE_IMAGE % image, re.UNICODE | re.IGNORECASE)]
image_regexes[resource_name].append(re.compile(RE_IMAGE_STYLE % image, re.UNICODE | re.IGNORECASE))
if image_enc != image:
image_regexes[resource_name].append(re.compile(RE_IMAGE % image_enc, re.UNICODE | re.IGNORECASE))
image_regexes[resource_name].append(re.compile(RE_IMAGE_STYLE % image_enc, re.UNICODE | re.IGNORECASE))
elif extension in CSS_FILES:
css_resource_names.append(resource_name)
elif extension not in NON_HTML_FILES:
html_resource_names.append(resource_name)
if image_regexes or html_resource_names:
check_for_images_in_html_resources(zf, image_regexes, image_name_regexes, html_resource_names)
if image_regexes or css_resource_names:
check_for_images_in_css_resources(zf, image_regexes, image_name_regexes, css_resource_names)
if image_regexes:
check_for_images_in_opf_cover_meta(path_to_book, zf, image_regexes, image_name_regexes)
if image_regexes:
self.log('----------------------------------------------------')
self.log(get_title_authors_text(db, book_id))
for resource_name in image_regexes.keys():
self.log(_('\tUNUSED image file: %s')%resource_name)
return True
return False
except InvalidEpub as e:
self.log.error('Invalid epub:', e)
return False
except:
self.log.error('ERROR parsing book: ', path_to_book)
self.log(traceback.format_exc())
return False
self.check_all_files(evaluate_book,
no_match_msg=_('No searched ePub books have unused image files'),
marked_text='epub_unused_images',
status_msg_type=_('ePub books for unused image files'))
def check_epub_broken_image_links(self):
RE_IMAGE = re.compile(r'<(?:[a-z]*?\:)*?image[^>]*href=?"([^"]*?)"', re.UNICODE)
RE_IMG = re.compile(r'<(?:[a-z]*?\:)*?img[^>]*src="([^"]*?)"', re.UNICODE)
def evaluate_book(book_id, db):
path_to_book = db.format_abspath(book_id, 'EPUB', index_is_id=True)
if not path_to_book:
self.log.error(_('ERROR: EPUB format is missing: '), get_title_authors_text(db, book_id))
return False
try:
with ZipFile(path_to_book, 'r') as zf:
contents = zf.namelist()
if self._is_drm_encrypted(zf, contents):
self.log.error(_('SKIPPING BOOK (DRM Encrypted): '), get_title_authors_text(db, book_id))
return False
# Build a list of all the image files in this epub
image_map = {}
html_resource_names = []
for resource_name in self._manifest_worthy_names(zf):
extension = resource_name[resource_name.rfind('.'):].lower()
if extension in IMAGE_FILES:
# Use the base name for the image since relative path might differ from html
# compared to the opf manifest
try:
image = six.moves.urllib.request.url2pathname(resource_name.lower())
except:
self.log.error('ERROR parsing book: ', path_to_book)
self.log.error('\tIssue with image name: ', resource_name)
self.log(traceback.format_exc())
return False
image_map[image] = resource_name
elif extension not in NON_HTML_FILES:
html_resource_names.append(resource_name)
found_broken = False
if html_resource_names:
for resource_name in html_resource_names:
raw_data = self.zf_read(zf, resource_name)
data = raw_data.lower()
html_dir = os.path.dirname(resource_name).lower()
if html_dir:
html_dir += os.sep
img_tag_matches = RE_IMG.findall(data)
image_tag_matches = RE_IMAGE.findall(data)
for match in img_tag_matches + image_tag_matches:
rel_path = os.path.normpath(html_dir + match)
normalised_image_name = six.moves.urllib.request.url2pathname(rel_path)
if normalised_image_name not in image_map:
if not found_broken:
self.log(get_title_authors_text(db, book_id))
found_broken = True
self.log(_('\tBroken image link in:'), resource_name, _(' of '), match)
return found_broken
except InvalidEpub as e:
self.log.error('Invalid epub:', e)
return False
except:
self.log.error('ERROR parsing book: ', path_to_book)
self.log(traceback.format_exc())
return False
self.check_all_files(evaluate_book,
no_match_msg=_('No searched ePub books have broken image links'),
marked_text='epub_broken_image_links',
status_msg_type=_('ePub books for broken image links'))
def check_epub_files(self, files, text, marked, show_log=True):
match_files = [f.lower() for f in files]
def evaluate_book(book_id, db):
path_to_book = db.format_abspath(book_id, 'EPUB', index_is_id=True)
if not path_to_book:
self.log.error('ERROR: EPUB format is missing: ', get_title_authors_text(db, book_id))
return False
try:
match = False
displayed_path = False
with ZipFile(path_to_book, 'r') as zf:
contents = zf.namelist()
for resource_name in contents:
found = False
if resource_name.lower() in match_files:
found = True
else:
for a in match_files:
if resource_name.lower().endswith('/'+a):
found = True
break
if found:
if show_log:
if not displayed_path:
displayed_path = True
self.log('Match found in: <b>%s</b>'%get_title_authors_text(db, book_id))
self.log('\t<span style="color:darkgray">%s</span>'%resource_name)
match = True
return match
except InvalidEpub as e:
self.log.error('Invalid epub:', e)
return False
except:
self.log.error('ERROR parsing book: ', path_to_book)
self.log(traceback.format_exc())
return False
self.check_all_files(evaluate_book,
no_match_msg=_('No searched ePub books have ')+text,
marked_text=marked,
status_msg_type=_('ePub books for ')+text)
def check_epub_replaceable_cover(self, check_has_cover):
def raster_cover(opf_xml):
covers = opf_xml.xpath(r'child::opf:metadata/opf:meta[@name="cover" and @content]',
namespaces={'opf':OPF_NS})
if covers:
cover_id = covers[0].get('content')
items = opf_xml.xpath(r'child::opf:manifest/opf:item',
namespaces={'opf':OPF_NS})
for item in items:
if item.get('id', None) == cover_id:
mt = item.get('media-type', '')
if 'xml' not in mt:
return item.get('href', None)
for item in items:
if item.get('href', None) == cover_id:
mt = item.get('media-type', '')
if mt.startswith('image/'):
return item.get('href', None)
def evaluate_book(book_id, db):
path_to_book = db.format_abspath(book_id, 'EPUB', index_is_id=True)
if not path_to_book:
self.log.error('ERROR: EPUB format is missing: ', get_title_authors_text(db, book_id))
return not check_has_cover
try:
with ZipFile(path_to_book, 'r') as zf:
opf_name = self._get_opf_xml(path_to_book, zf)
if not opf_name:
self.log.error(_('No OPF file in:'), get_title_authors_text(db, book_id))
return not check_has_cover
opf_xml = self._get_opf_tree(zf, opf_name)
rcover = raster_cover(opf_xml)
if not rcover:
self.log(_('No supported meta tag or non-xml cover in:'), get_title_authors_text(db, book_id))
return not check_has_cover
cpath = posixpath.join(posixpath.dirname(opf_name), rcover)
is_encrypted_cover = self._get_encryption_meta(zf).is_encrypted(cpath)
if is_encrypted_cover:
self.log(_('DRM Encrypted cover in:'), get_title_authors_text(db, book_id))
return check_has_cover
image_extension = os.path.splitext(cpath)[1].lower()
if image_extension not in ('.png', '.jpg', '.jpeg'):
self.log(_('Invalid cover image extension (%s) in:')%image_extension, get_title_authors_text(db, book_id))
return not check_has_cover
return check_has_cover
except InvalidEpub as e:
self.log.error('Invalid epub:', e)
return not check_has_cover
except:
self.log.error('ERROR parsing book: ', path_to_book)
self.log(traceback.format_exc())
return not check_has_cover
if check_has_cover:
msg = _('No searched ePub books have replaceable covers')
marked_text = 'epub_has_replaceable_cover'
else:
msg = _('All searched ePub books have replaceable covers')
marked_text = 'epub_not_replaceable_cover'
self.check_all_files(evaluate_book,
no_match_msg=msg, marked_text=marked_text,
status_msg_type=_('ePub books for replaceable covers'))
def check_epub_calibre_svg_cover(self, check_has_svg_cover):
def evaluate_book(book_id, db):
path_to_book = db.format_abspath(book_id, 'EPUB', index_is_id=True)
if not path_to_book:
self.log.error('ERROR: EPUB format is missing: ', get_title_authors_text(db, book_id))
return not check_has_svg_cover
try:
with ZipFile(path_to_book, 'r') as zf:
opf_name = self._get_opf_xml(path_to_book, zf)
if opf_name:
cover_name = self._get_opf_item(zf, opf_name,
xpath=r'child::opf:guide/opf:reference'
'[@type="cover"and @href]')
if cover_name and cover_name.endswith('.xhtml'):
html = self.zf_read(zf, cover_name)
data = self._parse_xhtml(html, cover_name)
metas = XPath('//h:meta[@content="true" and @name="calibre:cover"]')(data)
if len(metas):
svg = XPath('//svg:svg')(data)
if len(svg):
return check_has_svg_cover
return not check_has_svg_cover
except InvalidEpub as e:
self.log.error('Invalid epub:', e)
return not check_has_svg_cover
except:
self.log.error('ERROR parsing book: ', path_to_book)
self.log(traceback.format_exc())
return not check_has_svg_cover
if check_has_svg_cover:
msg = _('No searched ePub books have calibre SVG covers embedded')
marked_text = 'epub_has_calibre_svg_cover'
else:
msg = _('All searched ePub books have calibre SVG covers embedded')
marked_text = 'epub_missing_calibre_svg_cover'
self.check_all_files(evaluate_book,
no_match_msg=msg, marked_text=marked_text,
status_msg_type=_('ePub books for calibre SVG covers'))
def check_epub_calibre_cover(self, check_has_cover):
'''
This function is DEPRECATED by check_epub_replaceable_cover above
Keeping only in case someone decides they want this check resurrected
'''
def evaluate_book(book_id, db):
path_to_book = db.format_abspath(book_id, 'EPUB', index_is_id=True)
if not path_to_book:
self.log.error('ERROR: EPUB format is missing: ', get_title_authors_text(db, book_id))
return not check_has_cover
try:
with ZipFile(path_to_book, 'r') as zf:
opf_name = self._get_opf_xml(path_to_book, zf)
if opf_name:
cover_name = self._get_opf_item(zf, opf_name,
xpath=r'child::opf:guide/opf:reference'
'[@type="cover"and @href]')
if cover_name and cover_name.endswith('.xhtml'):
html = self.zf_read(zf, cover_name)
if html.find('<meta content="true" name="calibre:cover"') != -1 or \
html.find('<meta name="calibre:cover" content="true"') != -1:
return check_has_cover
return not check_has_cover
except InvalidEpub as e:
self.log.error('Invalid epub:', e)
return not check_has_cover
except:
self.log.error('ERROR parsing book: ', path_to_book)
self.log(traceback.format_exc())
return not check_has_cover
if check_has_cover:
msg = _('No searched ePub books have calibre covers embedded')
marked_text = 'epub_has_calibre_cover'
else:
msg = _('All searched ePub books have calibre covers embedded')
marked_text = 'epub_missing_calibre_cover'
self.check_all_files(evaluate_book,
no_match_msg=msg, marked_text=marked_text,
status_msg_type=_('ePub books for calibre covers'))