-
Notifications
You must be signed in to change notification settings - Fork 581
/
navprocessor.py
444 lines (407 loc) · 17.2 KB
/
navprocessor.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
# Copyright (c) 2019-2020 Kevin B. Hendricks
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of
# conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list
# of conditions and the following disclaimer in the documentation and/or other materials
# provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
# WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import re
from quickparser import QuickXHTMLParser
SIGIL_REPLACE_LANDMARKS_HERE = "<!-- SIGIL_REPLACE_LANDMARKS_HERE -->"
SIGIL_REPLACE_PAGELIST_HERE = "<!-- SIGIL_REPLACE_PAGELIST_HERE -->"
SIGIL_REPLACE_TOC_HERE = "<!-- SIGIL_REPLACE_TOC_HERE -->"
NAV_TOC_PATTERN = re.compile(r'''^\s*<!--\s*SIGIL_REPLACE_TOC_HERE\s*-->\s*$''', re.M)
NAV_PAGELIST_PATTERN = re.compile(r'''^\s*<!--\s*SIGIL_REPLACE_PAGELIST_HERE\s*-->\s*$''', re.M)
NAV_LANDMARKS_PATTERN = re.compile(r'''^\s*<!--\s*SIGIL_REPLACE_LANDMARKS_HERE\s*-->\s*$''', re.M)
# encode/escape text to make it xml safe
def xmlencode(data):
if data is None:
return ''
newdata = xmldecode(data)
newdata = newdata.replace('&', '&')
newdata = newdata.replace('<', '<')
newdata = newdata.replace('>', '>')
newdata = newdata.replace('"', '"')
return newdata
# decode xml encoded/escaped strings
def xmldecode(data):
if data is None:
return ''
newdata = data
newdata = newdata.replace('"', '"')
newdata = newdata.replace('>', '>')
newdata = newdata.replace('<', '<')
newdata = newdata.replace('&', '&')
return newdata
class NavProcessor(object):
def __init__(self, navsrc, codec='utf-8'):
if navsrc is None:
navsrc = ""
if isinstance(navsrc, bytes):
self.content = navsrc.decode(codec)
else:
self.content = navsrc
# returns ordered list of tuples (play_order, nesting_level, href, title)
# href is in url encoded form (percent encodings used if needed)
# title has been xml decoded/unescaped
def getTOC(self):
# parse the nav to get the table of contents
navsrc = self.content
toclist = []
qp = QuickXHTMLParser()
qp.setContent(navsrc)
lvl = 0
po = 0
title = ""
nav_type = None
href = None
for txt, tp, tname, ttype, tattr in qp.parse_iter():
if txt is not None:
if ".a." in tp or tp.endswith(".a"):
title = title + txt
else:
title = ""
else:
if tname == "nav" and ttype == "begin":
nav_type = tattr.get("epub:type", None)
continue
if tname == "nav" and ttype == "end":
nav_type = None
continue
if nav_type is not None and nav_type == "toc":
if tname == "ol":
if ttype == "begin": lvl += 1
if ttype == "end": lvl -= 1
continue
if tname == "a" and ttype == "begin":
href = tattr.get("href", "")
# must leave all url hrefs in raw url encoded form
# if they can ever contain fragments
continue
if tname == "a" and ttype == "end":
po += 1
title = xmldecode(title)
toclist.append((po, lvl, href, title))
title = ""
href = None
continue
return toclist
# replace the TOC with ordered list of tuples (play_order, nesting_level, href, title)
# href should be url encoded (percent encodings present if needed)
# title should be xml decoded/unescaped
def setTOC(self, toclist):
toc_xhtml = self.buildTOC(toclist)
# replace the TOC in the current navsrc with a placeholder
navsrc = self.content
qp = QuickXHTMLParser()
qp.setContent(navsrc)
nav_type = None
res = []
skip_output = False
for txt, tp, tname, ttype, tattr in qp.parse_iter():
if txt is not None:
if not skip_output:
res.append(txt)
else:
if tname == "nav" and ttype == "begin":
nav_type = tattr.get("epub:type", None)
if nav_type is not None and nav_type == "toc":
res.append(SIGIL_REPLACE_TOC_HERE)
skip_output = True
continue
if tname == "nav" and ttype == "end" and nav_type == "toc":
nav_type = None
skip_output = False
continue
if not skip_output:
res.append(qp.tag_info_to_xml(tname, ttype, tattr))
navsrc = "".join(res)
m = re.search(NAV_TOC_PATTERN, navsrc)
if m is None:
return False
navsrc = navsrc[0:m.start()] + toc_xhtml + navsrc[m.end():]
self.content = navsrc
return True
# returns ordered list of tuples (epubtype, href, title)
# href is url encoded (percent encodings present if needed)
# title has been xml decoded/unescaped
def getLandmarks(self):
# parse the nav to get the landmarks
navsrc = self.content
landmarks = []
qp = QuickXHTMLParser()
qp.setContent(navsrc)
title = ""
nav_type = None
href = None
epubtype = None
for txt, tp, tname, ttype, tattr in qp.parse_iter():
if txt is not None:
if ".a." in tp or tp.endswith(".a"):
title = title + txt
else:
title = ""
else:
if tname == "nav" and ttype == "begin":
nav_type = tattr.get("epub:type", None)
continue
if tname == "nav" and ttype == "end":
nav_type = None
continue
if nav_type is not None and nav_type == "landmarks":
if tname == "a" and ttype == "begin":
href = tattr.get("href", "")
# must leave all hrefs in raw url encoded form
# if they can contain fragments
epubtype = tattr.get("epub:type", None)
continue
if tname == "a" and ttype == "end":
if epubtype is not None:
title = xmldecode(title)
landmarks.append((epubtype, href, title))
title = ""
epubtype = None
href = None
continue
return landmarks
# replace the landmarks with ordered list of tuples (epubtype, href, title)
# href should be url encoded (percent encodings present if needed)
# title should be xml decoded/unescaped
def setLandmarks(self, landmarks):
landmarks_xhtml = self.buildLandmarks(landmarks)
# replace the landmarks from the navsrc with a placeholer
navsrc = self.content
qp = QuickXHTMLParser()
qp.setContent(navsrc)
nav_type = None
res = []
skip_output = False
for txt, tp, tname, ttype, tattr in qp.parse_iter():
if txt is not None:
if not skip_output:
res.append(txt)
else:
if tname == "nav" and ttype == "begin":
nav_type = tattr.get("epub:type", None)
if nav_type is not None and nav_type == "landmarks":
res.append(SIGIL_REPLACE_LANDMARKS_HERE)
skip_output = True
continue
if tname == "nav" and ttype == "end" and nav_type == "landmarks":
nav_type = None
skip_output = False
continue
if not skip_output:
res.append(qp.tag_info_to_xml(tname, ttype, tattr))
navsrc = "".join(res)
m = re.search(NAV_LANDMARKS_PATTERN, navsrc)
if m is None:
return False
navsrc = navsrc[0:m.start()] + landmarks_xhtml + navsrc[m.end():]
self.content = navsrc
return True
# returns ordered list of tuples (page_number, href, title)
# href is url encoded (percent encodings if needed should be present))
# title has been xml decoded/unescaped
def getPageList(self):
# parse the nav source to get the page-list
navsrc = self.content
pagelist = []
qp = QuickXHTMLParser()
qp.setContent(navsrc)
pgcnt = 0
nav_type = None
href = None
title = ""
for txt, tp, tname, ttype, tattr in qp.parse_iter():
if txt is not None:
if ".a." in tp or tp.endswith(".a"):
title = title + txt
else:
title = ""
else:
if tname == "nav" and ttype == "begin":
nav_type = tattr.get("epub:type", None)
continue
if tname == "nav" and ttype == "end":
nav_type = None
continue
if nav_type is not None and nav_type == "page-list":
if tname == "a" and ttype == "begin" and nav_type == "page-list":
href = tattr.get("href", "")
# hrefs must be kept in raw urlencoded form that may contain fragments
continue
if tname == "a" and ttype == "end":
pgcnt += 1
title = xmldecode(title)
pagelist.append((pgcnt, href, title))
title = ""
continue
return pagelist
# replace the page with ordered list of tuples (page_number, href, title)
# href should be url encoded (percent encodings present if needed))
# title should be xml decoded/unescaped
def setPageList(self, pagelist):
pagelist_xhtml = self.buildPageList(pagelist)
# replace the pagelist from the navsrc with a placeholer
navsrc = self.content
qp = QuickXHTMLParser()
qp.setContent(navsrc)
nav_type = None
res = []
skip_output = False
found_page_list = False
for txt, tp, tname, ttype, tattr in qp.parse_iter():
if txt is not None:
if not skip_output:
res.append(txt)
else:
if tname == "nav" and ttype == "begin":
nav_type = tattr.get("epub:type", None)
if nav_type is not None and nav_type == "page-list":
res.append(SIGIL_REPLACE_PAGELIST_HERE)
found_page_list = True
skip_output = True
continue
if tname == "nav" and ttype == "end" and nav_type == "page-list":
nav_type = None
skip_output = False
continue
if tname == "body" and ttype == "end":
if not found_page_list and len(pagelist) > 0:
padding = res[-1]
res.append(SIGIL_REPLACE_PAGELIST_HERE)
res.append(padding)
found_page_list = True
if not skip_output:
res.append(qp.tag_info_to_xml(tname, ttype, tattr))
navsrc = "".join(res)
m = re.search(NAV_PAGELIST_PATTERN, navsrc)
if m is None:
return False
navsrc = navsrc[0:m.start()] + pagelist_xhtml + navsrc[m.end():]
self.content = navsrc
return True
# self.toclist is an ordered list of tuples (play_order, nesting_level, href, title)
# hrefs should be in url encoded form (percent encodings present if needed)
def buildTOC(self, toclist):
navres = []
ind = ' '
ibase = ind * 3
incr = ind * 2
# start with the toc
navres.append(ind * 2 + '<nav epub:type="toc" id="toc">\n')
navres.append(ind * 3 + '<h1>Table of Contents</h1>\n')
navres.append(ibase + '<ol>\n')
curlvl = 1
initial = True
for po, lvl, href, lbl in toclist:
lbl = xmlencode(lbl)
if lvl > curlvl:
while lvl > curlvl:
indent = ibase + incr * (curlvl)
navres.append(indent + '<ol>\n')
navres.append(indent + ind + '<li>\n')
navres.append(indent + ind * 2 + '<a href="%s">%s</a>\n' % (href, lbl))
curlvl += 1
elif lvl < curlvl:
while lvl < curlvl:
indent = ibase + incr * (curlvl - 1)
navres.append(indent + ind + '</li>\n')
navres.append(indent + '</ol>\n')
curlvl -= 1
indent = ibase + incr * (lvl - 1)
navres.append(indent + ind + '</li>\n')
navres.append(indent + ind + '<li>\n')
navres.append(indent + ind * 2 + '<a href="%s">%s</a>\n' % (href, lbl))
else:
indent = ibase + incr * (lvl - 1)
if not initial:
navres.append(indent + ind + '</li>\n')
navres.append(indent + ind + '<li>\n')
navres.append(indent + ind * 2 + '<a href="%s">%s</a>\n' % (href, lbl))
initial = False
curlvl = lvl
while(curlvl > 0):
indent = ibase + incr * (curlvl - 1)
navres.append(indent + ind + "</li>\n")
navres.append(indent + "</ol>\n")
curlvl -= 1
navres.append(ind * 2 + '</nav>\n')
return "".join(navres)
# self.pagelist is an ordered list of tuples (page_number, href, title)
# href should be url encoded (percent encodings present if needed)
def buildPageList(self, pagelist):
navres = []
ind = ' '
# add any existing page-list if need be
if len(pagelist) > 0:
navres.append(ind * 2 + '<nav epub:type="page-list" id="page-list" hidden="">\n')
navres.append(ind * 3 + '<ol>\n')
for pn, href, title in pagelist:
title = xmlencode(title)
navres.append(ind * 4 + '<li><a href="%s">%s</a></li>\n' % (href, title))
navres.append(ind * 3 + '</ol>\n')
navres.append(ind * 2 + '</nav>\n')
return "".join(navres)
# self.landmarks is an ordered list of tuples (epub_type, href, title)
# href should be url encoded (percent encodings present if needed)
def buildLandmarks(self, landmarks):
navres = []
ind = ' '
navres.append(ind * 2 + '<nav epub:type="landmarks" id="landmarks" hidden="">\n')
navres.append(ind * 3 + '<h2>Guide</h2>\n')
navres.append(ind * 3 + '<ol>\n')
for etyp, href, title in landmarks:
title = xmlencode(title)
navres.append(ind * 4 + '<li>\n')
navres.append(ind * 5 + '<a epub:type="%s" href="%s">%s</a>\n' % (etyp, href, title))
navres.append(ind * 4 + '</li>\n')
navres.append(ind * 3 + '</ol>\n')
navres.append(ind * 2 + '</nav>\n')
return "".join(navres)
# returns the nav source code as a unicode string in its current form
def getNavSrc(self):
return self.content
def main(argv=sys.argv):
if len(argv) != 2:
print("navprocessor.py nav_file_path")
return -1
navpath = argv[1]
navsrc = ""
with open(navpath, 'rb') as f:
navsrc = f.read()
navsrc = navsrc.decode('utf-8')
np = NavProcessor(navsrc)
landmarks = np.getLandmarks()
pagelist = np.getPageList()
toclist = np.getTOC()
print(toclist)
print(landmarks)
print(pagelist)
print(np.setLandmarks(landmarks))
print(np.setPageList(pagelist))
print(np.setTOC(toclist))
print(np.getNavSrc())
return 0
if __name__ == '__main__':
sys.exit(main())