-
Notifications
You must be signed in to change notification settings - Fork 11
/
epubsplit.py
1367 lines (1220 loc) · 51.7 KB
/
epubsplit.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__license__ = 'GPL v3'
__copyright__ = '2021, Jim Miller'
__docformat__ = 'restructuredtext en'
import sys, re, os, traceback, copy
from posixpath import normpath
import logging
logger = logging.getLogger(__name__)
from zipfile import ZipFile, ZIP_STORED, ZIP_DEFLATED
from xml.dom.minidom import parse, parseString, getDOMImplementation, Element
from time import time
import six
from six.moves.urllib.parse import unquote
from six import string_types, text_type as unicode
from six import unichr
from bs4 import BeautifulSoup
## font decoding code lifted from
## calibre/src/calibre/ebooks/conversion/plugins/epub_input.py
## copyright '2009, Kovid Goyal <[email protected]>'
## don't bug Kovid about this use of it.
ADOBE_OBFUSCATION = 'http://ns.adobe.com/pdf/enc#RC'
IDPF_OBFUSCATION = 'http://www.idpf.org/2008/embedding'
from itertools import cycle
class FontDecrypter:
def __init__(self, epub, content_dom):
self.epub = epub
self.content_dom = content_dom
self.encryption = {}
self.old_uuid = None
def get_file(self,href):
return self.epub.read(href)
def get_encrypted_fontfiles(self):
if not self.encryption:
## Find the .opf file.
try:
# <encryption xmlns="urn:oasis:names:tc:opendocument:xmlns:container"
# xmlns:enc="http://www.w3.org/2001/04/xmlenc#"
# xmlns:deenc="http://ns.adobe.com/digitaleditions/enc">
# <enc:EncryptedData>
# <enc:EncryptionMethod Algorithm="http://ns.adobe.com/pdf/enc#RC"/>
# <enc:CipherData>
# <enc:CipherReference URI="fonts/00017.ttf"/>
# </enc:CipherData>
# </enc:EncryptedData>
# </encryption>
encryption = self.epub.read("META-INF/encryption.xml")
encryptiondom = parseString(encryption)
# print(encryptiondom.toprettyxml(indent=' '))
for encdata in encryptiondom.getElementsByTagName('enc:EncryptedData'):
# print(encdata.toprettyxml(indent=' '))
algorithm = encdata.getElementsByTagName('enc:EncryptionMethod')[0].getAttribute('Algorithm')
if algorithm not in {ADOBE_OBFUSCATION, IDPF_OBFUSCATION}:
print("Unknown font encryption: %s"%algorithm)
else:
# print(algorithm)
for encref in encdata.getElementsByTagName('enc:CipherReference'):
# print(encref.getAttribute('URI'))
self.encryption[encref.getAttribute('URI')]=algorithm
except KeyError as ke:
self.encryption = {}
return self.encryption
def get_old_uuid(self):
if not self.old_uuid:
contentdom = self.content_dom
uidkey = contentdom.getElementsByTagName("package")[0].getAttribute("unique-identifier")
for dcid in contentdom.getElementsByTagName("dc:identifier"):
if dcid.getAttribute("id") == uidkey and dcid.getAttribute("opf:scheme") == "uuid":
self.old_uuid = dcid.firstChild.data
return self.old_uuid
def get_idpf_key(self):
# idpf key:urn:uuid:221c69fe-29f3-4cb4-bb3f-58c430261cc6
# idpf key:b'\xfb\xa9\x03N}\xae~\x12 \xaa\xe0\xc11\xe2\xe7\x1b\xf6\xa5\xcas'
idpf_key = self.get_old_uuid()
import uuid, hashlib
idpf_key = re.sub('[\u0020\u0009\u000d\u000a]', '', idpf_key)
idpf_key = hashlib.sha1(idpf_key.encode('utf-8')).digest()
return idpf_key
def get_adobe_key(self):
# adobe key:221c69fe-29f3-4cb4-bb3f-58c430261cc6
# adobe key:b'"\x1ci\xfe)\xf3L\xb4\xbb?X\xc40&\x1c\xc6'
adobe_key = self.get_old_uuid()
import uuid
adobe_key = adobe_key.rpartition(':')[-1] # skip urn:uuid:
adobe_key = uuid.UUID(adobe_key).bytes
return adobe_key
def get_decrypted_font_data(self, uri):
# print(self.get_old_uuid())
# print("idpf : %s"%self.get_idpf_key())
# print("adobe: %s"%self.get_adobe_key())
# print("uri:%s"%uri)
font_data = self.get_file(uri)
if uri in self.get_encrypted_fontfiles():
key = self.get_adobe_key() if self.get_encrypted_fontfiles()[uri] == ADOBE_OBFUSCATION else self.get_idpf_key()
font_data = self.decrypt_font_data(key, font_data, self.get_encrypted_fontfiles()[uri])
return font_data
def decrypt_font_data(self, key, data, algorithm):
is_adobe = algorithm == ADOBE_OBFUSCATION
crypt_len = 1024 if is_adobe else 1040
crypt = bytearray(data[:crypt_len])
key = cycle(iter(bytearray(key)))
decrypt = bytes(bytearray(x^next(key) for x in crypt))
return decrypt + data[crypt_len:]
def _unirepl(match):
"Return the unicode string for a decimal number"
if match.group(1).startswith('x'):
radix=16
s = match.group(1)[1:]
else:
radix=10
s = match.group(1)
try:
value = int(s, radix)
retval = "%s%s"%(unichr(value),match.group(2))
except:
# This way, at least if there's more of entities out there
# that fail, it doesn't blow the entire download.
print("Numeric entity translation failed, skipping: &#x%s%s"%(match.group(1),match.group(2)))
retval = ""
return retval
def _replaceNumberEntities(data):
# The same brokenish entity parsing in SGMLParser that inserts ';'
# after non-entities will also insert ';' incorrectly after number
# entities, including part of the next word if it's a-z.
# "Don't—ever—do—that—again," becomes
# "Don't—e;ver—d;o—that—a;gain,"
# Also need to allow for 5 digit decimal entities 法
# Last expression didn't allow for 2 digit hex correctly: é
p = re.compile(r'&#(x[0-9a-fA-F]{,4}|[0-9]{,5})([0-9a-fA-F]*?);')
return p.sub(_unirepl, data)
def _replaceNotEntities(data):
# not just \w or \S. regexp from c:\Python25\lib\sgmllib.py
# (or equiv), SGMLParser, entityref
p = re.compile(r'&([a-zA-Z][-.a-zA-Z0-9]*);')
return p.sub(r'&\1', data)
def stripHTML(soup):
return removeAllEntities(re.sub(r'<[^>]+>','',"%s" % soup)).strip()
def conditionalRemoveEntities(value):
if isinstance(value,string_types) :
return removeEntities(value).strip()
else:
return value
def removeAllEntities(text):
# Remove < < and &
return removeEntities(text).replace('<', '<').replace('>', '>').replace('&', '&')
def removeEntities(text):
if text is None:
return ""
if not (isinstance(text,string_types)):
return str(text)
try:
t = unicode(text) #.decode('utf-8')
except UnicodeEncodeError as e:
try:
t = text.encode ('ascii', 'xmlcharrefreplace')
except UnicodeEncodeError as e:
t = text
text = t
# replace numeric versions of [&<>] with named versions,
# then replace named versions with actual characters,
text = re.sub(r'�*38;','&',text)
text = re.sub(r'�*60;','<',text)
text = re.sub(r'�*62;','>',text)
# replace remaining � entities with unicode value, such as ' -> '
text = _replaceNumberEntities(text)
# replace several named entities with character, such as — -> -
# see constants.py for the list.
# reverse sort will put entities with ; before the same one without, when valid.
for e in reversed(sorted(entities.keys())):
v = entities[e]
try:
text = text.replace(e, v)
except UnicodeDecodeError as ex:
# for the pound symbol in constants.py
text = text.replace(e, v.decode('utf-8'))
# SGMLParser, and in turn, BeautifulStoneSoup doesn't parse
# entities terribly well and inserts (;) after something that
# it thinks might be an entity. AT&T becomes AT&T; All of my
# attempts to fix this by changing the input to
# BeautifulStoneSoup break something else instead. But at
# this point, there should be *no* real entities left, so find
# these not-entities and removing them here should be safe.
text = _replaceNotEntities(text)
# < < and & are the only html entities allowed in xhtml, put those back.
return text.replace('&', '&').replace('&lt', '<').replace('&gt', '>')
# entity list from http://code.google.com/p/doctype/wiki/CharacterEntitiesConsistent
entities = { 'á' : 'á',
'Á' : 'Á',
'Á' : 'Á',
'á' : 'á',
'â' : 'â',
'Â' : 'Â',
'Â' : 'Â',
'â' : 'â',
'´' : '´',
'´' : '´',
'Æ' : 'Æ',
'æ' : 'æ',
'Æ' : 'Æ',
'æ' : 'æ',
'à' : 'à',
'À' : 'À',
'À' : 'À',
'à' : 'à',
'ℵ' : 'ℵ',
'α' : 'α',
'Α' : 'Α',
'&' : '&',
'&' : '&',
'&' : '&',
'&' : '&',
'∧' : '∧',
'∠' : '∠',
'å' : 'å',
'Å' : 'Å',
'Å' : 'Å',
'å' : 'å',
'≈' : '≈',
'ã' : 'ã',
'Ã' : 'Ã',
'Ã' : 'Ã',
'ã' : 'ã',
'ä' : 'ä',
'Ä' : 'Ä',
'Ä' : 'Ä',
'ä' : 'ä',
'„' : '„',
'β' : 'β',
'Β' : 'Β',
'¦' : '¦',
'¦' : '¦',
'•' : '•',
'∩' : '∩',
'ç' : 'ç',
'Ç' : 'Ç',
'Ç' : 'Ç',
'ç' : 'ç',
'¸' : '¸',
'¸' : '¸',
'¢' : '¢',
'¢' : '¢',
'χ' : 'χ',
'Χ' : 'Χ',
'ˆ' : 'ˆ',
'♣' : '♣',
'≅' : '≅',
'©' : '©',
'©' : '©',
'©' : '©',
'©' : '©',
'↵' : '↵',
'∪' : '∪',
'¤' : '¤',
'¤' : '¤',
'†' : '†',
'‡' : '‡',
'↓' : '↓',
'⇓' : '⇓',
'°' : '°',
'°' : '°',
'δ' : 'δ',
'Δ' : 'Δ',
'♦' : '♦',
'÷' : '÷',
'÷' : '÷',
'é' : 'é',
'É' : 'É',
'É' : 'É',
'é' : 'é',
'ê' : 'ê',
'Ê' : 'Ê',
'Ê' : 'Ê',
'ê' : 'ê',
'è' : 'è',
'È' : 'È',
'È' : 'È',
'è' : 'è',
'∅' : '∅',
' ' : ' ',
' ' : ' ',
'ε' : 'ε',
'Ε' : 'Ε',
'≡' : '≡',
'η' : 'η',
'Η' : 'Η',
'ð' : 'ð',
'Ð' : 'Ð',
'Ð' : 'Ð',
'ð' : 'ð',
'ë' : 'ë',
'Ë' : 'Ë',
'Ë' : 'Ë',
'ë' : 'ë',
'€' : '€',
'∃' : '∃',
'ƒ' : 'ƒ',
'∀' : '∀',
'½' : '½',
'½' : '½',
'¼' : '¼',
'¼' : '¼',
'¾' : '¾',
'¾' : '¾',
'⁄' : '⁄',
'γ' : 'γ',
'Γ' : 'Γ',
'≥' : '≥',
#'>' : '>',
#'>' : '>',
#'>' : '>',
#'>' : '>',
'↔' : '↔',
'⇔' : '⇔',
'♥' : '♥',
'…' : '…',
'í' : 'í',
'Í' : 'Í',
'Í' : 'Í',
'í' : 'í',
'î' : 'î',
'Î' : 'Î',
'Î' : 'Î',
'î' : 'î',
'¡' : '¡',
'¡' : '¡',
'ì' : 'ì',
'Ì' : 'Ì',
'Ì' : 'Ì',
'ì' : 'ì',
'ℑ' : 'ℑ',
'∞' : '∞',
'∫' : '∫',
'ι' : 'ι',
'Ι' : 'Ι',
'¿' : '¿',
'¿' : '¿',
'∈' : '∈',
'ï' : 'ï',
'Ï' : 'Ï',
'Ï' : 'Ï',
'ï' : 'ï',
'κ' : 'κ',
'Κ' : 'Κ',
'λ' : 'λ',
'Λ' : 'Λ',
'«' : '«',
'«' : '«',
'←' : '←',
'⇐' : '⇐',
'⌈' : '⌈',
'“' : '“',
'≤' : '≤',
'⌊' : '⌊',
'∗' : '∗',
'◊' : '◊',
'‎' : '',
'‹' : '‹',
'‘' : '‘',
#'<' : '<',
#'<' : '<',
#'<' : '<',
#'<' : '<',
'¯' : '¯',
'¯' : '¯',
'—' : '—',
'µ' : 'µ',
'µ' : 'µ',
'·' : '·',
'·' : '·',
'−' : '−',
'μ' : 'μ',
'Μ' : 'Μ',
'∇' : '∇',
' ' : ' ',
' ' : ' ',
'–' : '–',
'≠' : '≠',
'∋' : '∋',
'¬' : '¬',
'¬' : '¬',
'∉' : '∉',
'⊄' : '⊄',
'ñ' : 'ñ',
'Ñ' : 'Ñ',
'Ñ' : 'Ñ',
'ñ' : 'ñ',
'ν' : 'ν',
'Ν' : 'Ν',
'ó' : 'ó',
'Ó' : 'Ó',
'Ó' : 'Ó',
'ó' : 'ó',
'ô' : 'ô',
'Ô' : 'Ô',
'Ô' : 'Ô',
'ô' : 'ô',
'Œ' : 'Œ',
'œ' : 'œ',
'ò' : 'ò',
'Ò' : 'Ò',
'Ò' : 'Ò',
'ò' : 'ò',
'‾' : '‾',
'ω' : 'ω',
'Ω' : 'Ω',
'ο' : 'ο',
'Ο' : 'Ο',
'⊕' : '⊕',
'∨' : '∨',
'ª' : 'ª',
'ª' : 'ª',
'º' : 'º',
'º' : 'º',
'ø' : 'ø',
'Ø' : 'Ø',
'Ø' : 'Ø',
'ø' : 'ø',
'õ' : 'õ',
'Õ' : 'Õ',
'Õ' : 'Õ',
'õ' : 'õ',
'⊗' : '⊗',
'ö' : 'ö',
'Ö' : 'Ö',
'Ö' : 'Ö',
'ö' : 'ö',
'¶' : '¶',
'¶' : '¶',
'∂' : '∂',
'‰' : '‰',
'⊥' : '⊥',
'φ' : 'φ',
'Φ' : 'Φ',
'π' : 'π',
'Π' : 'Π',
'ϖ' : 'ϖ',
'±' : '±',
'±' : '±',
'£' : '£',
'£' : '£',
'′' : '′',
'″' : '″',
'∏' : '∏',
'∝' : '∝',
'ψ' : 'ψ',
'Ψ' : 'Ψ',
'"' : '"',
'"' : '"',
'"' : '"',
'"' : '"',
'√' : '√',
'»' : '»',
'»' : '»',
'→' : '→',
'⇒' : '⇒',
'⌉' : '⌉',
'”' : '”',
'ℜ' : 'ℜ',
'®' : '®',
'®' : '®',
'®' : '®',
'®' : '®',
'⌋' : '⌋',
'ρ' : 'ρ',
'Ρ' : 'Ρ',
'‏' : '',
'›' : '›',
'’' : '’',
'‚' : '‚',
'š' : 'š',
'Š' : 'Š',
'⋅' : '⋅',
'§' : '§',
'§' : '§',
'­' : '', # strange optional hyphenation control character, not just a dash
'­' : '',
'σ' : 'σ',
'Σ' : 'Σ',
'ς' : 'ς',
'∼' : '∼',
'♠' : '♠',
'⊂' : '⊂',
'⊆' : '⊆',
'∑' : '∑',
'¹' : '¹',
'¹' : '¹',
'²' : '²',
'²' : '²',
'³' : '³',
'³' : '³',
'⊃' : '⊃',
'⊇' : '⊇',
'ß' : 'ß',
'ß' : 'ß',
'τ' : 'τ',
'Τ' : 'Τ',
'∴' : '∴',
'θ' : 'θ',
'Θ' : 'Θ',
'ϑ' : 'ϑ',
' ' : ' ',
'þ' : 'þ',
'Þ' : 'Þ',
'Þ' : 'Þ',
'þ' : 'þ',
'˜' : '˜',
'×' : '×',
'×' : '×',
'™' : '™',
'ú' : 'ú',
'Ú' : 'Ú',
'Ú' : 'Ú',
'ú' : 'ú',
'↑' : '↑',
'⇑' : '⇑',
'û' : 'û',
'Û' : 'Û',
'Û' : 'Û',
'û' : 'û',
'ù' : 'ù',
'Ù' : 'Ù',
'Ù' : 'Ù',
'ù' : 'ù',
'¨' : '¨',
'¨' : '¨',
'ϒ' : 'ϒ',
'υ' : 'υ',
'Υ' : 'Υ',
'ü' : 'ü',
'Ü' : 'Ü',
'Ü' : 'Ü',
'ü' : 'ü',
'℘' : '℘',
'ξ' : 'ξ',
'Ξ' : 'Ξ',
'ý' : 'ý',
'Ý' : 'Ý',
'Ý' : 'Ý',
'ý' : 'ý',
'¥' : '¥',
'¥' : '¥',
'ÿ' : 'ÿ',
'Ÿ' : 'Ÿ',
'ÿ' : 'ÿ',
'ζ' : 'ζ',
'Ζ' : 'Ζ',
'‍' : '', # strange spacing control character, not just a space
'‌' : '', # strange spacing control character, not just a space
}
class SplitEpub:
def __init__(self, inputio):
self.epub = ZipFile(inputio, 'r')
self.content_dom = None
self.content_relpath = None
self.manifest_items = None
self.guide_items = None
self.toc_dom = None
self.toc_relpath = None
self.toc_map = None
self.split_lines = None
self.origauthors = []
self.origtitle = None
def get_file(self,href):
return self.epub.read(href)
def get_content_dom(self):
if not self.content_dom:
## Find the .opf file.
container = self.epub.read("META-INF/container.xml")
containerdom = parseString(container)
rootfilenodelist = containerdom.getElementsByTagName("rootfile")
rootfilename = rootfilenodelist[0].getAttribute("full-path")
self.content_dom = parseString(self.epub.read(rootfilename))
self.content_relpath = get_path_part(rootfilename)
return self.content_dom
def get_content_relpath(self):
## Save the path to the .opf file--hrefs inside it are relative to it.
if not self.content_relpath:
self.get_content_dom() # sets self.content_relpath also.
return self.content_relpath
def get_toc_relpath(self):
## Save the path to the toc.ncx file--hrefs inside it are relative to it.
if not self.toc_relpath:
self.get_manifest_items() # sets self.toc_relpath also.
return self.toc_relpath
def get_manifest_items(self):
if not self.manifest_items:
self.manifest_items = {}
for item in self.get_content_dom().getElementsByTagName("item"):
fullhref=normpath(unquote(self.get_content_relpath()+item.getAttribute("href")))
#print("---- item fullhref:%s"%(fullhref))
self.manifest_items["h:"+fullhref]=(item.getAttribute("id"),item.getAttribute("media-type"))
self.manifest_items["i:"+item.getAttribute("id")]=(fullhref,item.getAttribute("media-type"))
if( item.getAttribute("media-type") == "application/x-dtbncx+xml" ):
# TOC file is only one with this type--as far as I know.
self.toc_relpath = get_path_part(fullhref)
self.toc_dom = parseString(self.epub.read(fullhref))
return self.manifest_items
def get_guide_items(self):
if not self.guide_items:
self.guide_items = {}
for item in self.get_content_dom().getElementsByTagName("reference"):
fullhref=normpath(unquote(self.get_content_relpath()+item.getAttribute("href")))
self.guide_items[fullhref]=(item.getAttribute("type"),item.getAttribute("title"))
#print("---- reference href:%s value:%s"%(fullhref,self.guide_items[fullhref],))
#self.guide_items[item.getAttribute("type")]=(fullhref,item.getAttribute("media-type"))
return self.guide_items
def get_toc_dom(self):
if not self.toc_dom:
self.get_manifest_items() # also sets self.toc_dom
return self.toc_dom
# dict() of href->[(text,anchor),...],...
# eg: "file0001.html"->[("Introduction","anchor01"),("Chapter 1","anchor02")],...
def get_toc_map(self):
if not self.toc_map:
self.toc_map = {}
# update all navpoint ids with bookid for uniqueness.
for navpoint in self.get_toc_dom().getElementsByTagName("navPoint"):
src = normpath(unquote(self.get_toc_relpath()+navpoint.getElementsByTagName("content")[0].getAttribute("src")))
if '#' in src:
(href,anchor)=src.split("#")
else:
(href,anchor)=(src,None)
# The first of these in each navPoint should be the appropriate one.
# (may be others due to nesting.
try:
text = unicode(navpoint.getElementsByTagName("text")[0].firstChild.data)
except:
#print("No chapter title found in TOC for (%s)"%src)
text = ""
if href not in self.toc_map:
self.toc_map[href] = []
if anchor == None:
# put file links ahead of ancher links. Otherwise
# a non-linear anchor link may take precedence,
# which will confuse EpubSplit. This will cause
# split lines to possibly be out of order from
# TOC, but the alternative is worse. Should be a
# rare corner case.
## Keep order of non-anchor entries to the same file.
idx=0
while idx < len(self.toc_map[href]) and self.toc_map[href][idx][1] is None: # [1] is anchor
# print(idx)
# print(self.toc_map[href][idx])
idx = idx+1
self.toc_map[href].insert(idx,(text,anchor))
else:
self.toc_map[href].append((text,anchor))
# print(self.toc_map)
return self.toc_map
# list of dicts with href, anchor & toc text.
# 'split lines' are all the points that the epub can be split on.
# Offer a split at each spine file and each ToC point.
def get_split_lines(self):
metadom = self.get_content_dom()
## Save indiv book title
try:
self.origtitle = metadom.getElementsByTagName("dc:title")[0].firstChild.data
except:
self.origtitle = "(Title Missing)"
## Save authors.
for creator in metadom.getElementsByTagName("dc:creator"):
try:
if( creator.getAttribute("opf:role") == "aut" or not creator.hasAttribute("opf:role") and creator.firstChild != None):
if creator.firstChild.data not in self.origauthors:
self.origauthors.append(creator.firstChild.data)
except:
pass
if len(self.origauthors) == 0:
self.origauthors.append("(Authors Missing)")
self.split_lines = [] # list of dicts with href, anchor and toc
# spin on spine files.
count=0
for itemref in metadom.getElementsByTagName("itemref"):
idref = itemref.getAttribute("idref")
(href,type) = self.get_manifest_items()["i:"+idref]
current = {}
self.split_lines.append(current)
current['href']=href
current['anchor']=None
current['toc'] = []
if href in self.get_guide_items():
current['guide'] = self.get_guide_items()[href]
current['id'] = idref
current['type'] = type
current['num'] = count
t=self.epub.read(href).decode('utf-8')
if len(t) > 1500 : t = t[:1500] + "..."
current['sample']=t
count += 1
#print("spine:%s->%s"%(idref,href))
# if href is in the toc.
if href in self.get_toc_map():
# For each toc entry, check to see if there's an anchor, if so,
# make a new split line.
for tocitem in self.get_toc_map()[href]:
(text,anchor) = tocitem
# XXX for outputing to screen in CLI--hopefully won't need in plugin?
try:
text = "%s"%text
except:
text = "(error text)"
if anchor:
#print("breakpoint: %d"%count)
current = {}
self.split_lines.append(current)
current['href']=href
current['anchor']=anchor
current['toc']=[]
current['id'] = idref
current['type'] = type
current['num'] = count
# anchor, need to split first, then reduce to 1500.
t=splitHtml(self.epub.read(href).decode('utf-8'),anchor,before=False)
if len(t) > 1500 : t = t[:1500] + "..."
current['sample']=t
count += 1
# There can be more than one toc to the same split line.
# This won't find multiple toc to the same anchor yet.
current['toc'].append(text)
#print("\ttoc:'%s' %s#%s"%(text,href,anchor))
return self.split_lines
# pass in list of line numbers(?)
def get_split_files(self,linenums):
self.filecache = FileCache(self.get_manifest_items())
# set include flag in split_lines.
if not self.split_lines:
self.get_split_lines()
lines = self.split_lines
lines_set = set([int(k) for k in linenums])
for j in range(len(lines)):
lines[j]['include'] = j in lines_set
# loop through finding 'chunks' -- contiguous pieces in the
# same file. Each included file is at least one chunk, but if
# parts are left out, one original file can end up being more
# than one chunk.
outchunks = [] # list of tuples=(filename,start,end) 'end' is not inclusive.
inchunk = False
currentfile = None
start = None
for line in lines:
if line['include']:
if not inchunk: # start new chunk
inchunk = True
currentfile = line['href']
start = line
else: # inchunk
# different file, new chunk.
if currentfile != line['href']:
outchunks.append((currentfile,start,line))
inchunk=True
currentfile=line['href']
start=line
else: # not include
if inchunk: # save previous chunk.
outchunks.append((currentfile,start,line))
inchunk=False
# final chunk for when last in list is include.
if inchunk:
outchunks.append((currentfile,start,None))
outfiles=[] # tuples, (filename,type,data) -- filename changed to unique
for (href,start,end) in outchunks:
filedata = self.epub.read(href).decode('utf-8')
# discard before start if anchor.
if start['anchor'] != None:
filedata = splitHtml(filedata,start['anchor'],before=False)
# discard from end anchor on(inclusive), but only if same file. If
# different file, keep rest of file. If no 'end', then it was the
# last chunk and went to the end of the last file.
if end != None and end['anchor'] != None and end['href']==href:
filedata = splitHtml(filedata,end['anchor'],before=True)
filename = self.filecache.add_content_file(href,filedata)
outfiles.append([filename,start['id'],start['type'],filedata])
# print("self.oldnew:%s"%self.filecache.oldnew)
# print("self.newold:%s"%self.filecache.newold)
# print("\nanchors:%s\n"%self.filecache.anchors)
# print("\nlinkedfiles:%s\n"%self.filecache.linkedfiles)
# print("relpath:%s"%get_path_part())
# Spin through to replace internal URLs
for fl in outfiles:
#print("file:%s"%fl[0])
soup = BeautifulSoup(fl[3],'html5lib')
changed = False
for a in soup.findAll('a'):
if a.has_attr('href'):
path = normpath(unquote("%s%s"%(get_path_part(fl[0]),a['href'])))
#print("full a['href']:%s"%path)
if path in self.filecache.anchors and self.filecache.anchors[path] != path:
a['href'] = self.filecache.anchors[path][len(get_path_part(fl[0])):]
#print("replacement path:%s"%a['href'])
changed = True
if changed:
fl[3] = unicode(soup)
return outfiles
def write_split_epub(self,
outputio,
linenums,
changedtocs={},
authoropts=[],
titleopt=None,
descopt=None,
tags=[],
languages=['en'],
coverjpgpath=None):
files = self.get_split_files(linenums)
## Write mimetype file, must be first and uncompressed.
## Older versions of python(2.4/5) don't allow you to specify
## compression by individual file.
## Overwrite if existing output file.
outputepub = ZipFile(outputio, "w", compression=ZIP_STORED)
outputepub.debug = 3
outputepub.writestr("mimetype", "application/epub+zip")
outputepub.close()
## Re-open file for content.
outputepub = ZipFile(outputio, "a", compression=ZIP_DEFLATED)
outputepub.debug = 3
## Create META-INF/container.xml file. The only thing it does is
## point to content.opf
containerdom = getDOMImplementation().createDocument(None, "container", None)
containertop = containerdom.documentElement
containertop.setAttribute("version","1.0")
containertop.setAttribute("xmlns","urn:oasis:names:tc:opendocument:xmlns:container")
rootfiles = containerdom.createElement("rootfiles")
containertop.appendChild(rootfiles)
rootfiles.appendChild(newTag(containerdom,"rootfile",{"full-path":"content.opf",
"media-type":"application/oebps-package+xml"}))
outputepub.writestr("META-INF/container.xml",containerdom.toprettyxml(indent=' ',encoding='utf-8'))
#### ## create content.opf file.
uniqueid="epubsplit-uid-%d" % time() # real sophisticated uid scheme.
contentdom = getDOMImplementation().createDocument(None, "package", None)
package = contentdom.documentElement
package.setAttribute("version","2.0")
package.setAttribute("xmlns","http://www.idpf.org/2007/opf")
package.setAttribute("unique-identifier","epubsplit-id")
metadata=newTag(contentdom,"metadata",
attrs={"xmlns:dc":"http://purl.org/dc/elements/1.1/",
"xmlns:opf":"http://www.idpf.org/2007/opf"})
metadata.appendChild(newTag(contentdom,"dc:identifier",text=uniqueid,attrs={"id":"epubsplit-id"}))
if( titleopt is None ):
titleopt = self.origtitle+" Split"
metadata.appendChild(newTag(contentdom,"dc:title",text=titleopt))
if( authoropts and len(authoropts) > 0 ):
useauthors=authoropts
else:
useauthors=self.origauthors
usedauthors=dict()
for author in useauthors:
if( author not in usedauthors ):
usedauthors[author]=author
metadata.appendChild(newTag(contentdom,"dc:creator",
attrs={"opf:role":"aut"},
text=author))
metadata.appendChild(newTag(contentdom,"dc:contributor",text="epubsplit",attrs={"opf:role":"bkp"}))
metadata.appendChild(newTag(contentdom,"dc:rights",text="Copyrights as per source stories"))
if languages:
for l in languages:
metadata.appendChild(newTag(contentdom,"dc:language",text=l))
else:
metadata.appendChild(newTag(contentdom,"dc:language",text="en"))
if not descopt:
# created now, but not filled in until TOC generation to save loops.
description = newTag(contentdom,"dc:description",text="Split from %s by %s."%(self.origtitle,", ".join(self.origauthors)))
else:
description = newTag(contentdom,"dc:description",text=descopt)
metadata.appendChild(description)
for tag in tags:
metadata.appendChild(newTag(contentdom,"dc:subject",text=tag))
package.appendChild(metadata)
manifest = contentdom.createElement("manifest")
package.appendChild(manifest)
spine = newTag(contentdom,"spine",attrs={"toc":"ncx"})
package.appendChild(spine)
manifest.appendChild(newTag(contentdom,"item",
attrs={'id':'ncx',
'href':'toc.ncx',
'media-type':'application/x-dtbncx+xml'}))
if coverjpgpath:
# <meta name="cover" content="cover.jpg"/>
metadata.appendChild(newTag(contentdom,"meta",{"name":"cover",
"content":"coverimageid"}))
# cover stuff for later:
# at end of <package>:
# <guide>
# <reference type="cover" title="Cover" href="Text/cover.xhtml"/>
# </guide>
guide = newTag(contentdom,"guide")
guide.appendChild(newTag(contentdom,"reference",attrs={"type":"cover",
"title":"Cover",
"href":"cover.xhtml"}))
package.appendChild(guide)
manifest.appendChild(newTag(contentdom,"item",
attrs={'id':"coverimageid",
'href':"cover.jpg",
'media-type':"image/jpeg"}))
# Note that the id of the cover xhmtl *must* be 'cover'
# for it to work on Nook.
manifest.appendChild(newTag(contentdom,"item",
attrs={'id':"cover",
'href':"cover.xhtml",
'media-type':"application/xhtml+xml"}))
spine.appendChild(newTag(contentdom,"itemref",
attrs={"idref":"cover",
"linear":"yes"}))
contentcount=0
for (filename,id,type,filedata) in files:
#filename = self.filecache.addHtml(href,filedata)
#print("writing :%s"%filename)
# add to manifest and spine
if coverjpgpath and filename == "cover.xhtml":
continue # don't dup cover.