-
Notifications
You must be signed in to change notification settings - Fork 0
/
mobiunpack32_34.py
1773 lines (1573 loc) · 69.9 KB
/
mobiunpack32_34.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
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
# Changelog
# 0.11 - Version by adamselene
# 0.11pd - Tweaked version by pdurrant
# 0.12 - extracts pictures too, and all into a folder.
# 0.13 - added back in optional output dir for those who don't want it based on infile
# 0.14 - auto flush stdout and wrapped in main, added proper return codes
# 0.15 - added support for metadata
# 0.16 - metadata now starting to be output as an opf file (PD)
# 0.17 - Also created tweaked text as source for Mobipocket Creator
# 0.18 - removed raw mobi file completely but kept _meta.html file for ease of conversion
# 0.19 - added in metadata for ASIN, Updated Title and Rights to the opf
# 0.20 - remove _meta.html since no longer needed
# 0.21 - Fixed some typos in the opf output, and also updated handling
# of test for trailing data/multibyte characters
# 0.22 - Fixed problem with > 9 images
# 0.23 - Now output Start guide item
# 0.24 - Set firstimg value for 'TEXtREAd'
# 0.25 - Now added character set metadata to html file for utf-8 files.
# 0.26 - Dictionary support added. Image handling speed improved. For huge files create temp files to speed up decoding.
# Language decoding fixed. Metadata is now converted to utf-8 when written to opf file.
# 0.27 - Add idx:entry attribute "scriptable" if dictionary contains entry length tags. Don't save non-image sections
# as images. Extract and save source zip file included by kindlegen as kindlegensrc.zip.
# 0.28 - Added back correct image file name extensions, created FastConcat class to simplify and clean up
# 0.29 - Metadata handling reworked, multiple entries of the same type are now supported. Serveral missing types added.
# FastConcat class has been removed as in-memory handling with lists is faster, even for huge files.
# 0.30 - Add support for outputting **all** metadata values - encode content with hex if of unknown type
# 0.31 - Now supports Print Replica ebooks, outputting PDF and mysterious data sections
# 0.32 - Now supports NCX file extraction/building.
# Overhauled the structure of mobiunpack to be more class oriented.
DEBUG = False
DEBUG_NCX = False
""" Set to True to print debug information. """
WRITE_RAW_DATA = False
""" Set to True to create additional files with raw data for debugging/reverse engineering. """
EOF_RECORD = chr(0xe9) + chr(0x8e) + "\r\n"
""" The EOF record content. """
KINDLEGENSRC_FILENAME = "kindlegensrc.zip"
""" The name for the kindlegen source archive. """
class Unbuffered:
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
import sys
import binascii
sys.stdout = Unbuffered(sys.stdout)
import array, struct, os, re, imghdr
class unpackException(Exception):
pass
class fileNames:
def __init__(self, infile, outdir):
self.infile = infile
self.outdir = outdir
if not os.path.exists(outdir):
os.mkdir(outdir)
self.outsrc = os.path.join(outdir, os.path.splitext(os.path.split(infile)[1])[0]) + '.html'
self.outopf = os.path.join(outdir, os.path.splitext(os.path.split(infile)[1])[0]) + '.opf'
self.outncx = os.path.join(outdir, os.path.splitext(os.path.split(infile)[1])[0]) + '.ncx'
self.imgdir = os.path.join(outdir, 'images')
if not os.path.exists(self.imgdir):
os.mkdir(self.imgdir)
self.outsrcbasename = os.path.basename(self.outsrc)
self.outhtmlbasename = os.path.basename(self.outsrc)
def getOutRaw(self, ext):
return os.path.join(self.outdir, os.path.splitext(os.path.split(self.infile)[1])[0]) + ext
class UncompressedReader:
def unpack(self, data):
return data
class PalmdocReader:
def unpack(self, i):
o, p = '', 0
while p < len(i):
# c = ord(i[p])
c = i[p]
p += 1
if (c >= 1 and c <= 8):
# o += i[p:p + c]
o += str(i[p:p + c])
p += c
elif (c < 128):
o += chr(c);
elif (c >= 192):
o += ' ' + chr(c ^ 128);
else:
if p < len(i):
# c = (c << 8) | ord(i[p])
c = (c << 8) | i[p]
p += 1
m = (c >> 3) & 0x07ff
n = (c & 7) + 3
if (m > n):
o += o[-m:n - m]
else:
for _ in range(n):
o += o[-m]
return o
class HuffcdicReader:
q = struct.Struct('>Q').unpack_from
def loadHuff(self, huff):
if huff[0:8] != 'HUFF\x00\x00\x00\x18':
raise unpackException('invalid huff header')
off1, off2 = struct.unpack_from('>LL', huff, 8)
def dict1_unpack(v):
codelen, term, maxcode = v & 0x1f, v & 0x80, v >> 8
assert codelen != 0
if codelen <= 8:
assert term
maxcode = ((maxcode + 1) << (32 - codelen)) - 1
return (codelen, term, maxcode)
self.dict1 = map(dict1_unpack, struct.unpack_from('>256L', huff, off1))
dict2 = struct.unpack_from('>64L', huff, off2)
self.mincode, self.maxcode = (), ()
for codelen, mincode in enumerate((0,) + dict2[0::2]):
self.mincode += (mincode << (32 - codelen), )
for codelen, maxcode in enumerate((0,) + dict2[1::2]):
self.maxcode += (((maxcode + 1) << (32 - codelen)) - 1, )
self.dictionary = []
def loadCdic(self, cdic):
if cdic[0:8] != 'CDIC\x00\x00\x00\x10':
raise unpackException('invalid cdic header')
phrases, bits = struct.unpack_from('>LL', cdic, 8)
n = min(1 << bits, phrases - len(self.dictionary))
h = struct.Struct('>H').unpack_from
def getslice(off):
blen, = h(cdic, 16 + off)
slice = cdic[18 + off:18 + off + (blen & 0x7fff)]
return (slice, blen & 0x8000)
self.dictionary += map(getslice, struct.unpack_from('>%dH' % n, cdic, 16))
def unpack(self, data):
q = HuffcdicReader.q
bitsleft = len(data) * 8
data += "\x00\x00\x00\x00\x00\x00\x00\x00"
pos = 0
x, = q(data, pos)
n = 32
s = ''
while True:
if n <= 0:
pos += 4
x, = q(data, pos)
n += 32
code = (x >> n) & ((1 << 32) - 1)
codelen, term, maxcode = self.dict1[code >> 24]
if not term:
while code < self.mincode[codelen]:
codelen += 1
maxcode = self.maxcode[codelen]
n -= codelen
bitsleft -= codelen
if bitsleft < 0:
break
r = (maxcode - code) >> (32 - codelen)
slice, flag = self.dictionary[r]
if not flag:
self.dictionary[r] = None
slice = self.unpack(slice)
self.dictionary[r] = (slice, 1)
s += slice
return s
class Sectionizer:
def __init__(self, filename, perm):
# self.f = file(filename, perm)
self.f = open(filename, mode=perm)
header = self.f.read(78)
self.ident = header[0x3C:0x3C + 8]
self.num_sections, = struct.unpack_from('>H', header, 76)
sections = self.f.read(self.num_sections * 8)
self.sections = struct.unpack_from('>%dL' % (self.num_sections * 2), sections, 0)[::2] + (0xfffffff, )
def loadSection(self, section):
before, after = self.sections[section:section + 2]
self.f.seek(before)
return self.f.read(after - before)
class mobiUnpack:
def __init__(self, files):
self.infile = files.infile
self.outdir = files.outdir
self.sect = Sectionizer(self.infile, 'rb')
if self.sect.ident != b'BOOKMOBI' and self.sect.ident != b'TEXtREAd':
raise unpackException('invalid file format')
self.header = self.sect.loadSection(0)
self.records, = struct.unpack_from('>H', self.header, 0x8)
self.length, self.type, self.codepage, self.unique_id, self.version = struct.unpack('>LLLLL',
self.header[20:40])
self.crypto_type, = struct.unpack_from('>H', self.header, 0xC)
self.rawText = self.__getRawtext()
def processPrintReplica(self):
# read in number of tables, and so calculate the start of the indicies into the data
numTables, = struct.unpack_from('>L', self.rawText, 0x04)
tableIndexOffset = 8 + 4 * numTables
# for each table, read in count of sections, assume first section is a PDF
# and output other sections as binary files
paths = []
for i in xrange(numTables):
sectionCount, = struct.unpack_from('>L', self.rawText, 0x08 + 4 * i)
for j in xrange(sectionCount):
sectionOffset, sectionLength, = struct.unpack_from('>LL', self.rawText, tableIndexOffset)
tableIndexOffset += 8
if j == 0:
entryName = os.path.join(self.outdir, os.path.splitext(os.path.split(self.infile)[1])[0]) + (
'.%03d.pdf' % (i + 1))
paths.append(entryName)
else:
entryName = os.path.join(self.outdir, os.path.splitext(os.path.split(self.infile)[1])[0]) + (
'.%03d.%03d.data' % ((i + 1), j))
f = open(entryName, 'wb')
f.write(self.rawText[sectionOffset:(sectionOffset + sectionLength)])
f.close()
self.printReplicaPaths = paths
def __getSizeOfTrailingDataEntry(self, data):
num = 0
for v in data[-4:]:
if ord(v) & 0x80:
num = 0
num = (num << 7) | (ord(v) & 0x7f)
return num
def Language(self):
langcode = struct.unpack('!L', self.header[0x5c:0x60])[0]
langid = langcode & 0xFF
sublangid = (langcode >> 10) & 0xFF
return [getLanguage(langid, sublangid)]
def DictInLanguage(self):
langcode = struct.unpack('!L', self.header[0x60:0x64])[0]
langid = langcode & 0xFF
sublangid = (langcode >> 10) & 0xFF
if langid != 0:
return [getLanguage(langid, sublangid)]
return False
def DictOutLanguage(self):
langcode = struct.unpack('!L', self.header[0x64:0x68])[0]
langid = langcode & 0xFF
sublangid = (langcode >> 10) & 0xFF
if langid != 0:
return [getLanguage(langid, sublangid)]
return False
def getMetaData(self):
codec = self.codec
extheader = self.header[16 + self.length:]
id_map_strings = {
1: 'Drm Server Id',
2: 'Drm Commerce Id',
3: 'Drm Ebookbase Book Id',
100: 'Creator',
101: 'Publisher',
102: 'Imprint',
103: 'Description',
104: 'ISBN',
105: 'Subject',
106: 'Published',
107: 'Review',
108: 'Contributor',
109: 'Rights',
110: 'SubjectCode',
111: 'Type',
112: 'Source',
113: 'ASIN',
117: 'Adult',
118: 'Price',
119: 'Currency',
200: 'DictShortName',
208: 'Watermark',
501: 'CDE Type',
503: 'Updated Title',
}
id_map_values = {
116: 'StartOffset',
201: 'CoverOffset',
202: 'ThumbOffset',
203: 'Fake Cover',
204: 'Creator Software',
205: 'Creator Major Version',
206: 'Creator Minor Version',
207: 'Creator Build Number',
401: 'Clipping Limit',
402: 'Publisher Limit',
404: 'Text to Speech Disabled',
}
id_map_hexstrings = {
209: 'Tamper Proof Keys (hex)',
300: 'Font Signature (hex)',
}
metadata = {}
def addValue(name, value):
if name not in metadata:
metadata[name] = [value]
else:
metadata[name].append(value)
if DEBUG:
print("multiple values: metadata[%s]=%s" % (name, metadata[name]))
_length, num_items = struct.unpack('>LL', extheader[4:12])
extheader = extheader[12:]
pos = 0
for _ in range(num_items):
id, size = struct.unpack('>LL', extheader[pos:pos + 8])
content = extheader[pos + 8: pos + size]
if id in id_map_strings.keys():
name = id_map_strings[id]
# addValue(name, unicode(content, codec).encode("utf-8"))
addValue(name, content)
elif id in id_map_values.keys():
name = id_map_values[id]
if size == 9:
value, = struct.unpack('B', content)
addValue(name, str(value))
elif size == 10:
value, = struct.unpack('>H', content)
addValue(name, str(value))
elif size == 12:
value, = struct.unpack('>L', content)
addValue(name, str(value))
else:
print("Error: Value for %s has unexpected size of %s" % (name, size))
elif id in id_map_hexstrings.keys():
name = id_map_hexstrings[id]
# addValue(name, content.encode('hex'))
addValue(name, binascii.hexlify(content))
else:
print("Warning: Unknown metadata with id %s found" % id)
name = str(id) + ' (hex)'
# addValue(name, content.encode('hex'))
addValue(name, binascii.hexlify(content))
pos += size
return metadata
def __getRawtext(self):
multibyte = 0
trailers = 0
if self.sect.ident == 'BOOKMOBI':
mobi_length, = struct.unpack_from('>L', self.header, 0x14)
mobi_version, = struct.unpack_from('>L', self.header, 0x68)
if (mobi_length >= 0xE4) and (mobi_version >= 5):
flags, = struct.unpack_from('>H', self.header, 0xF2)
multibyte = flags & 1
while flags > 1:
if flags & 2:
trailers += 1
flags = flags >> 1
compression, = struct.unpack_from('>H', self.header, 0x0)
if compression == 0x4448:
print("Huffdic compression")
reader = HuffcdicReader()
huffoff, huffnum = struct.unpack_from('>LL', self.header, 0x70)
reader.loadHuff(self.sect.loadSection(huffoff))
for i in xrange(1, huffnum):
reader.loadCdic(self.sect.loadSection(huffoff + i))
unpack = reader.unpack
elif compression == 2:
print("Palmdoc compression")
unpack = PalmdocReader().unpack
elif compression == 1:
print("No compression")
unpack = UncompressedReader().unpack
else:
raise unpackException('invalid compression type: 0x%4x' % compression)
def trimTrailingDataEntries(data):
for _ in range(trailers):
num = self.__getSizeOfTrailingDataEntry(data)
data = data[:-num]
if multibyte:
num = (ord(data[-1]) & 3) + 1
data = data[:-num]
return data
# get raw mobi html-like markup languge
print("Unpack raw html")
dataList = []
for i in range(self.records):
data = trimTrailingDataEntries(self.sect.loadSection(1 + i))
dataList.append(unpack(data))
return "".join(dataList)
@property
def isPrintReplica(self):
return (self.rawText[0:4] == "%MOP")
@property
def isEncrypted(self):
if self.crypto_type != 0:
return True
return False
@property
def codec_map(self):
return {
1252: 'windows-1252',
65001: 'utf-8',
}
@property
def firstidx(self):
if self.sect.ident != 'TEXtREAd':
idx, = struct.unpack_from('>L', self.header, 0x50)
else:
idx = 0xFFFFFFFF
return idx
@property
def firstimg(self):
if self.sect.ident != 'TEXtREAd':
img, = struct.unpack_from('>L', self.header, 0x6C)
else:
img = self.records + 1
return img
@property
def codec(self):
if self.codepage in self.codec_map.keys():
return self.codec_map[self.codepage]
else:
return 'windows-1252'
@property
def title(self):
toff, tlen = struct.unpack('>II', self.header[0x54:0x5c])
tend = toff + tlen
return self.header[toff:tend]
@property
def hasExth(self):
exth_flag, = struct.unpack('>L', self.header[0x80:0x84])
return exth_flag & 0x40
class ncxExtract:
def __init__(self, header, sect, records, files):
self.header = header
self.sect = sect
self.records = records
self.isNCX = False
self.files = files
def parseINDX(self):
files = self.files
indx_data = False
indx_text = False
indx_num = 1
idnx_codec = '' #not used..
# get first INDX section
indx_first, = struct.unpack('>L', self.header[0xf4:0xf8])
if indx_first == 0xffffffff:
print("No ncx")
return False
# sanity check of indx_first
if indx_first > (self.sect.num_sections - 2) or indx_first <= self.records:
print("Warning: incorrect index section number:", \
self.records, '<', indx_first, '<', self.sect.num_sections)
return False
# read INDX0
data = self.sect.loadSection(indx_first)
if DEBUG_NCX:
outraw = os.path.join(files.outdir, 'indx0.dat')
f = open(outraw, 'wb')
f.write(data)
f.close()
indxHeader = self.parseINDXHeader(data)
if not indxHeader:
return False
#must be of type 0
if not indxHeader['type'] == 0:
print("Warning: INDX0 not type 0")
return False
#NOTE: the number of "DATA" indx is stored in here...
indx_num = indxHeader['count']
#TODO: use indxHeader "code" to set encoding...
indx_codec = indxHeader['code']
#NOTE: used to figure out the INDX structure
tagx = readTagSection(indxHeader['len'], data)
if DEBUG_NCX:
print("INDX0: ", indx_num, "INDX sections")
print("TAGX: ", tagx)
# read CTOC
if DEBUG_NCX:
print("CTOC")
data = self.sect.loadSection(indx_first + indx_num + 1)
if data[:4] == 'INDX':
print("Warning: CTOC is an INDX")
return False
indx_text = self.readCTOC(data)
# read all INDXx
indx_data = []
for n in range(indx_num):
indx_id = n + 1
if DEBUG_NCX:
print("INDX%d" % indx_id)
data = self.sect.loadSection(indx_first + indx_id)
if DEBUG_NCX:
#dump the whole section, not just the navdata part as before
outraw = os.path.join(files.outdir, 'indx%d.dat' % indx_id)
f = open(outraw, 'wb')
f.write(data)
f.close()
#parse header
indxHeader = self.parseINDXHeader(data)
if not indxHeader:
return False
#must be of type 1
if not indxHeader['type'] == 1:
print("Warning: INDX%d not type 1" % indx_id)
#parse IDXT (starts @ 'start')
#NOTE: IDXT contains the offset to each entry
idxt = self.parseIDXT(data[indxHeader['start']:])
if DEBUG_NCX:
print('IDXT', idxt)
# now process the indx
#(actually starts @ 'len' but we use the IDXT offset data to navigate)
#print "INDX1"
tmp = self.parseINDX1(data, idxt, indx_text, tagx)
if not tmp:
print("Warning: error parsing NCX data in INDX%d" % indx_id)
return False
indx_data = indx_data + tmp
if len(indx_data) < indxHeader['count']:
print("Warning: missing INDX entries %d/%d" % \
(len(indx_data), indxHeader['count']))
self.indx_data = indx_data
return indx_data
def parseINDXHeader(self, data):
"read INDX header"
#must be INDX
if not data[:4] == 'INDX':
print("Warning: index section is not INDX")
return False
words = (
'len', 'nul1', 'type', 'gen', 'start', 'count', 'code',
'lng', 'total', 'ordt', 'ligt', 'nligt', 'nctoc'
)
num = len(words)
values = struct.unpack('>%dL' % num, data[4:4 * (num + 1)])
header = {}
for n in range(num):
header[words[n]] = values[n]
if DEBUG_NCX:
print("parsed INDX header:")
for n in words:
print(n, "%X" % header[n],
print)
return header
def readCTOC(self, txtdata):
files = self.files
# read all blocks from CTOC
if DEBUG_NCX:
outraw = os.path.join(files.outdir, 'ctoc.dat')
f = open(outraw, 'wb')
f.write(txtdata)
f.close()
ctoc_data = {}
offset = 0
while offset < len(txtdata):
#stop if first byte is 0
if txtdata[offset] == '\0':
break
idx_offs = offset
#first n bytes: name len as vwi
pos, ilen = getVariableWidthValue(txtdata, offset)
offset += pos
#<len> next bytes: name
name = txtdata[offset:offset + ilen]
offset += ilen
# print idx_offs, name
ctoc_data[idx_offs] = name
return ctoc_data
def parseIDXT(self, data, pos_offset=0):
if not data[:4] == 'IDXT':
print("Warning: not IDXT")
return False
pos = []
offset = 4
while offset < len(data):
value, = struct.unpack_from('>H', data, offset)
offset += 2
#note: some files have a trailing 00 00
if value:
pos.append(value)
return pos
def parseINDX1(self, data, idxt, indx_txt, tagx):
#read all blocks from INDX1
tag_fieldname_map = {
1: 'pos',
2: 'len',
3: 'noffs',
4: 'hlvl',
5: 'koffs',
21: 'parent',
22: 'child1',
23: 'childn'
}
indx_data = []
num = 0
offset = 0
max_offset = len(data) - 1
taglst_cnt, taglst = tagx
if taglst_cnt > 1:
print("Error: multiple tagx taglist entries not handled")
for offset in idxt:
if offset > max_offset:
print('Warning: wrong IDXT entries, offset out of range', offset)
break
if data[offset] == '\0':
print('Warning: missing ncx entry @ %X' % offset)
break
tmp = {
'name': None,
'type': 0,
'pos': -1,
'len': 0,
'noffs': -1,
'text': "Unknown Text",
'hlvl': -1,
'kind': "Unknown Kind",
'parent': -1,
'child1': -1,
'childn': -1,
'num': num
}
#first byte: name len
ilen, = struct.unpack('B', data[offset])
offset += 1
#<len> next bytes: name
name = data[offset:offset + ilen]
offset += ilen
tmp['name'] = name
#next byte: type:
type, = struct.unpack('B', data[offset])
offset += 1
tmp['type'] = type
# The tagx info and the type byte is used to decipher which fields
# should be read in
for (tag, nvars, mask, stop) in taglst:
if stop:
break
if tag in tag_fieldname_map.keys():
fieldname = tag_fieldname_map[tag]
if type & mask == mask:
assert (nvars == 1)
pos, fieldvalue = getVariableWidthValue(data, offset)
offset += pos
tmp[fieldname] = fieldvalue
if tag == 3:
tmp['text'] = indx_txt.get(fieldvalue, 'Unknown Text')
if tag == 5:
tmp['kind'] = indx_txt.get(fieldvalue, 'Unknown Kind')
else:
# unknown tag so skip proper number of values if needed and continue
print('reading indx1 - unknown tag: ', tag, ' skipping it')
# NOTE: skipping should not be needed anymore with IDXT...
if type & mask == mask:
for i in range(nvars):
pos, temp = getVariableWidthValue(data, offset)
offset += pos
indx_data.append(tmp)
if DEBUG_NCX:
if True:
print("record number is ", num)
print("name is ", tmp['name'], "type is %x " % tmp['type'])
print("position is ", tmp['pos'], " and length is ", tmp['len'])
print("name offset is ", tmp['noffs'], " which is text ", tmp['text'])
print("kind is ", tmp['kind'], " and heading level is ", tmp['hlvl'])
print("parent is ", tmp['parent'])
print("first child is ", tmp['child1'], " and last child is ", tmp['childn'])
print("\n\n")
else:
fld_dbg = ('type', 'hlvl', 'parent', 'child1', 'childn')
print("\t".join(['%X' % tmp[f] for f in fld_dbg]))
num += 1
return indx_data
def buildNCX(self, htmlfile, title, ident):
indx_data = self.indx_data
ncx_header = \
'''<?xml version='1.0' encoding='utf-8'?>
<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" xml:lang="en">
<head>
<meta content="%s" name="dtb:uid"/>
<meta content="%d" name="dtb:depth"/>
<meta content="mobiunpack.py" name="dtb:generator"/>
<meta content="0" name="dtb:totalPageCount"/>
<meta content="0" name="dtb:maxPageNumber"/>
</head>
<docTitle>
<text>%s</text>
</docTitle>
<navMap>
'''
ncx_footer = \
''' </navMap>
</ncx>
'''
ncx_entry = \
'''<navPoint id="%s" playOrder="%d">
<navLabel>
<text>%s</text>
</navLabel>
<content src="%s"/>'''
#recursive part
def recursINDX(max_lvl=0, num=0, lvl=0, start=-1, end=-1):
if start > len(indx_data) or end > len(indx_data):
print("Warning: missing INDX child entries", start, end, len(indx_data))
return ''
if DEBUG_NCX:
print("recursINDX lvl %d from %d to %d" % (lvl, start, end))
xml = ''
if start <= 0:
start = 0
if end <= 0:
end = len(indx_data)
if lvl > max_lvl:
max_lvl = lvl
indent = ' ' * (2 + lvl)
for i in range(start, end):
e = indx_data[i]
if not e['hlvl'] == lvl:
continue
#open entry
num += 1
link = '%s#filepos%d' % (htmlfile, e['pos'])
tagid = 'np_%d' % num
entry = ncx_entry % (tagid, num, e['text'], link)
entry = re.sub(re.compile('^', re.M), indent, entry, 0)
xml += entry + '\n'
#recurs
if e['child1'] >= 0:
xmlrec, max_lvl, num = recursINDX(max_lvl, num, lvl + 1, \
e['child1'], e['childn'] + 1)
xml += xmlrec
#close entry
xml += indent + '</navPoint>\n'
return xml, max_lvl, num
body, max_lvl, num = recursINDX()
header = ncx_header % (ident, max_lvl + 1, title)
ncx = header + body + ncx_footer
if not len(indx_data) == num:
print("Warning: different number of entries in NCX", len(indx_data), num)
return ncx
def writeNCX(self, files, metadata):
# build the xml
self.isNCX = True
print("Write ncx")
xml = self.buildNCX(files.outsrcbasename, metadata['Title'][0], metadata['UniqueID'][0])
#write the ncx file ("outncx" is then used when building the opf)
f = open(files.outncx, 'wb')
f.write(xml)
f.close
class dictSupport:
def __init__(self, header, sect):
self.header = header
self.sect = sect
def getPositionMap(self):
header = self.header
sect = self.sect
positionMap = {}
metaOrthIndex, = struct.unpack_from('>L', header, 0x28)
metaInflIndex, = struct.unpack_from('>L', header, 0x2C)
decodeInflection = True
if metaOrthIndex != 0xFFFFFFFF:
print("Info: Document contains orthographic index, handle as dictionary")
if metaInflIndex == 0xFFFFFFFF:
decodeInflection = False
else:
metaInflIndexData = sect.loadSection(metaInflIndex)
metaIndexCount, = struct.unpack_from('>L', metaInflIndexData, 0x18)
if metaIndexCount != 1:
print("Error: Dictionary contains multiple inflection index sections, which is not yet supported")
decodeInflection = False
inflIndexData = sect.loadSection(metaInflIndex + 1)
inflNameData = sect.loadSection(metaInflIndex + 1 + metaIndexCount)
tagSectionStart, = struct.unpack_from('>L', metaInflIndexData, 0x04)
inflectionControlByteCount, inflectionTagTable = readTagSection(tagSectionStart, metaInflIndexData)
if DEBUG:
print("inflectionTagTable: %s" % inflectionTagTable)
if self.hasTag(inflectionTagTable, 0x07):
print("Error: Dictionary uses obsolete inflection rule scheme which is not yet supported")
decodeInflection = False
data = sect.loadSection(metaOrthIndex)
tagSectionStart, = struct.unpack_from('>L', data, 0x04)
controlByteCount, tagTable = readTagSection(tagSectionStart, data)
orthIndexCount, = struct.unpack_from('>L', data, 0x18)
if DEBUG:
print("orthTagTable: %s" % tagTable)
hasEntryLength = self.hasTag(tagTable, 0x02)
if not hasEntryLength:
print("Info: Index doesn't contain entry length tags")
print("Read dictionary index data")
for i in range(metaOrthIndex + 1, metaOrthIndex + 1 + orthIndexCount):
data = sect.loadSection(i)
idxtPos, = struct.unpack_from('>L', data, 0x14)
entryCount, = struct.unpack_from('>L', data, 0x18)
idxPositions = []
for j in range(entryCount):
pos, = struct.unpack_from('>H', data, idxtPos + 4 + (2 * j))
idxPositions.append(pos)
# The last entry ends before the IDXT tag (but there might be zero fill bytes we need to ignore!)
idxPositions.append(idxtPos)
for j in range(entryCount):
startPos = idxPositions[j]
endPos = idxPositions[j + 1]
textLength = ord(data[startPos])
text = data[startPos + 1:startPos + 1 + textLength]
tagMap = self.getTagMap(controlByteCount, tagTable, data, startPos + 1 + textLength, endPos)
if 0x01 in tagMap:
if decodeInflection and 0x2a in tagMap:
inflectionGroups = self.getInflectionGroups(text, inflectionControlByteCount,
inflectionTagTable, inflIndexData, inflNameData,
tagMap[0x2a])
else:
inflectionGroups = ""
assert len(tagMap[0x01]) == 1
entryStartPosition = tagMap[0x01][0]
if hasEntryLength:
# The idx:entry attribute "scriptable" must be present to create entry length tags.
ml = '<idx:entry scriptable="yes"><idx:orth value="%s">%s</idx:orth>' % (
text, inflectionGroups)
if entryStartPosition in positionMap:
positionMap[entryStartPosition] = positionMap[entryStartPosition] + ml
else:
positionMap[entryStartPosition] = ml
assert len(tagMap[0x02]) == 1
entryEndPosition = entryStartPosition + tagMap[0x02][0]
if entryEndPosition in positionMap:
positionMap[entryEndPosition] = "</idx:entry>" + positionMap[entryEndPosition]
else:
positionMap[entryEndPosition] = "</idx:entry>"
else:
indexTags = '<idx:entry>\n<idx:orth value="%s">\n%s</idx:entry>\n' % (
text, inflectionGroups)
if entryStartPosition in positionMap:
positionMap[entryStartPosition] = positionMap[entryStartPosition] + indexTags
else:
positionMap[entryStartPosition] = indexTags
return positionMap
def hasTag(self, tagTable, tag):
'''
Test if tag table contains given tag.
@param tagTable: The tag table.
@param tag: The tag to search.
@return: True if tag table contains given tag; False otherwise.
'''
for currentTag, _, _, _ in tagTable:
if currentTag == tag:
return True
return False
def getInflectionGroups(self, mainEntry, controlByteCount, tagTable, data, inflectionNames, groupList):
'''
Create string which contains the inflection groups with inflection rules as mobipocket tags.
@param mainEntry: The word to inflect.
@param controlByteCount: The number of control bytes.
@param tagTable: The tag table.
@param data: The inflection index data.
@param inflectionNames: The inflection rule name data.
@param groupList: The list of inflection groups to process.
@return: String with inflection groups and rules or empty string if required tags are not available.
'''
result = ""
idxtPos, = struct.unpack_from('>L', data, 0x14)
entryCount, = struct.unpack_from('>L', data, 0x18)
for value in groupList:
offset, = struct.unpack_from('>H', data, idxtPos + 4 + (2 * value))
if value + 1 < entryCount:
nextOffset, = struct.unpack_from('>H', data, idxtPos + 4 + (2 * (value + 1)))
else:
nextOffset = None
# First byte seems to be always 0x00 and must be skipped.
assert ord(data[offset]) == 0x00
tagMap = self.getTagMap(controlByteCount, tagTable, data, offset + 1, nextOffset)
# Make sure that the required tags are available.
if 0x05 not in tagMap:
print("Error: Required tag 0x05 not found in tagMap")
return ""
if 0x1a not in tagMap:
print("Error: Required tag 0x1a not found in tagMap")
return ""
result += "<idx:infl>"
for i in range(len(tagMap[0x05])):
# Get name of inflection rule.
value = tagMap[0x05][i]
consumed, textLength = getVariableWidthValue(inflectionNames, value)
inflectionName = inflectionNames[value + consumed:value + consumed + textLength]
# Get and apply inflection rule.
value = tagMap[0x1a][i]
offset, = struct.unpack_from('>H', data, idxtPos + 4 + (2 * value))
textLength = ord(data[offset])
inflection = self.applyInflectionRule(mainEntry, data, offset + 1, offset + 1 + textLength)
if inflection != None: