forked from cisco-system-traffic-generator/trex-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHTMLInjector.py
663 lines (498 loc) · 18.7 KB
/
HTMLInjector.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
import lxml.html as LH
from StringIO import StringIO
from copy import deepcopy
class HTMLInjector(object):
TOC_BEGIN = """
<body class="book">
<div id="toc-section">
<div id="toctitle">
<img class="trex_logo" src="$IMGPATH$/images/trex_logo_toc.png"/>
Table of Contents
</div>
<div id="toggle">
<img src="$IMGPATH$/images/icons/toggle.png" title="click to toggle table of contents"/>
</div>
<div id="toc">
<div id="nav-tree">
</div>
</div>
</div>
<div id="content-section">
<!-- load the theme CSS file -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" rel="stylesheet"/>
<link href="https://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />
<!-- include the jQuery library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js">
</script>
<!-- include the jQuery UI library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js">
</script>
<!-- include the minified jstree source -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js">
</script>
<!-- Hide TOC on mobile -->
<script>
// Hide TOC when it is mobile
checkMobile();
// Hide TOC by default if it is mobile
function checkMobile(){
if(isMobileDevice()){
hideTOC();
}
}
// Check it it it is running on mobile device
function isMobileDevice() {
if(
navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/BlackBerry/i) ||
navigator.userAgent.match(/iPhone|iPad|iPod/i) ||
navigator.userAgent.match(/Opera Mini/i) ||
navigator.userAgent.match(/IEMobile/i) ||
navigator.userAgent.match(/iPhone|iPad|iPod/i)
)
{
return true;
}
else
{
return false;
}
}
// Hide TOC - for the first time in mobile
function hideTOC(){
$("#toc").hide();
$("#toctitle").hide();
// Show the show/hide button
$("#toggle").css("right", "-40px");
// Fil width
$("body").css("margin-left", "50px");
}
</script>
<div id="content-section-inner">
"""
TOC_END = """
<!--BODYEND-->
</div>
<!-- End Of Inner Content Section -->
</div>
<!-- End of Content Section -->
</body>
<style type="text/css">
#toc {
margin-bottom: 2.5em;
}
#toctitle {
color: #527bbd;
font-size: 1.1em;
font-weight: bold;
margin-top: 1.0em;
margin-bottom: 0.1em;
}
@media screen {
body {
margin-left: 20em;
}
#toc {
position: fixed;
top: 51px;
left: 0;
bottom: 0;
width: 18em;
padding-bottom: 1.5em;
margin: 0;
overflow-x: auto !important;
overflow-y: auto !important;
border-right: solid 2px #cfcfcf;
background-color: #FAFAFA;
white-space: nowrap;
}
#toctitle {
font-size: 17px !important;
color: #4d4d4d !important;
margin-top: 0px;
height: 36px;
line-height: 36px;
background-color: #e4e2e2;
padding: 8px 0px 7px 45px;
white-space: nowrap;
left: 0px;
display: block;
position: fixed;
z-index: 100;
width: 245px;
top: 0px;
overflow: hidden;
}
#toc .toclevel1 {
margin-top: 0.5em;
}
#toc .toclevel2 {
margin-top: 0.25em;
display: list-item;
color: #aaaaaa;
}
}
/* Custom for Nave Tree */
#nav-tree{
margin-left: 10px !important;
}
#nav-tree ul > li {
color: #000 !important;
}
.jstree-wholerow.jstree-wholerow-clicked {
background-image: url('$IMGPATH$/images/icons/selected_tab_bg.png');
background-repeat: repeat-x;
color: #fff !important;
text-shadow: 0px 1px 1px rgba(0, 0, 0, 1.0);
}
/* For side bar */
.ui-resizable-e{
height: 100%;
width: 4px !important;
position: fixed !important;
top: 0px !important;
cursor: e-resize !important;
background: url('$IMGPATH$/images/splitbar.png') repeat scroll right center transparent !important;
}
.jstree-default .jstree-themeicon{
display: none !important;
}
.jstree-anchor {
font-size: 12px !important;
color: #91A501 !important;
}
.jstree-clicked{
color: white !important;
}
#toggle {
position: fixed;
top: 14px;
left: 10px;
z-index: 210;
width: 24px;
}
#toggle img {
opacity:0.3;
}
#toggle img:hover {
opacity:0.9;
}
.trex_logo{
top: 6px;
position: relative;
}
html{
overflow: hidden;
}
body{
margin-right: 0px !important;
margin-top: 0px !important;
margin-bottom: 0px !important;
}
#toc-section{
position: absolute;
z-index: 200;
}
#content-section{
overflow: auto;
}
#content-section-inner{
max-width: 50em;
}
</style>
<script>
$(document).ready(function(){
var isOpen = true;
// Initialize NavTree
initializeNavTree();
// Drag TOC left and right
initResizable();
// Toggle TOC whe clicking on the menu icon
toggleTOC();
// Handle Mobile - close TOC
checkMobile();
function initializeNavTree() {
// TOC tree options
var toc_tree = $('#nav-tree');
var toc_tree_options = {
'core' : {
"animation" :false,
"themes" : { "stripes" : false },
'data' : {
"url" : "./input_replace_me.json",
"dataType" : "json" // needed only if you do not supply JSON headers
}
}
,
"plugins" : [ "wholerow" ]
};
$('#nav-tree').jstree(toc_tree_options) ;
toc_tree.on("changed.jstree", function (e, data) {
// filename
var filename = data.instance.get_selected(true)[0].original.link
$ONCLICK$
});
}
// a hook for selecting the first node if needed
$SELECTFIRST$
function initResizable() {
var toc = $("#toc");
var body = $("body");
// On resize
$("#toc").resizable({
resize: function(e, ui) {
resized();
},
handles: 'e'
});
// On zoom changed
$(window).resize(function() {
if(isOpen){
resized();
}
});
// Do it for the first time
var tocWidth = $(toc).outerWidth();
var windowHeight = $(window).height();
$(".ui-resizable-e").css({"right":$(window).width()-parseInt(tocWidth)+"px"});
$("#toctitle").css({"width":parseInt(tocWidth)-45+"px"});
$("#toc-section").css({"height":windowHeight + "px"});
$("#content-section").css({"height":windowHeight + "px"});
}
function resized(){
var body = $("body");
var tocWidth = $(toc).outerWidth();
var windowHeight = $(window).height();
body.css({"marginLeft":parseInt(tocWidth)+20+"px"});
$(".ui-resizable-e").css({"right":$(window).width()-parseInt(tocWidth)+"px"});
$("#toctitle").css({"width":parseInt(tocWidth)-45+"px"});
$("#toc-section").css({"height":windowHeight + "px"});
$("#content-section").css({"height":windowHeight + "px"});
}
function toggleTOC(){
$( "#toggle" ).click(function() {
if ( isOpen ) {
// Close it
closTOC();
} else {
// Open it
openTOC();
}
// Toggle status
isOpen = !isOpen;
});
}
// Close TOC by default if it is mobile
function checkMobile(){
if(isMobileDevice()){
isOpen=false;
$(".ui-resizable-e").hide();
}
}
// Check it it it is running on mobile device
function isMobileDevice() {
if(
navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/BlackBerry/i) ||
navigator.userAgent.match(/iPhone|iPad|iPod/i) ||
navigator.userAgent.match(/Opera Mini/i) ||
navigator.userAgent.match(/IEMobile/i) ||
navigator.userAgent.match(/iPhone|iPad|iPod/i)
)
{
return true;
}
else
{
return false;
}
}
// Close TOC
function closTOC(){
$("#toc").hide("slide", 500);
$("#toctitle").hide("slide", 500);
if(!isMobileDevice()){
$(".ui-resizable-e").hide("slide", 500);
}
// Show the show/hide button
$("#toggle").css("right", "-40px");
// Fil width
$("body").animate({"margin-left": "50px"}, 500);
}
// Open TOC
function openTOC(){
$("#toc").show("slide", 500);
$("#toctitle").show("slide", 500);
if(!isMobileDevice()){
$(".ui-resizable-e").show("slide", 500);
}
// Show the show/hide button
$("#toggle").css("right", "15px");
// Minimize page width
$("body").animate({"margin-left": $(toc).outerWidth()+20+"px"}, 500);
}
});
</script>
"""
ONCLICK_MULTIPAGE = """
$.get(filename, function(r) {
$("body").css("cursor", "progress");
// replace content
var els = $(r).find('.sect1');
$('#content').html(els);
$("body").css("cursor", "default");
// action could be "select_node" or "ready"
if (data.action == "select_node") {
document.location.hash = data.node.id
}
});
"""
ONCLICK_SINGLEPAGE = "window.location.href = filename"
DISQUS_HTML = """
<div id="disqus_thread"></div>
<script>
/**
* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/
if (typeof(DISQUS) == "undefined") {
var disqus_config = function () {
this.page.url = window.location.href + "$ID$"
this.page.identifier = "$ID$";
this.page.title = "$ID$";
};
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://trex-tgn.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
} else {
/* * * Disqus Reset Function * * */
var disqus_reset = function (newIdentifier, newUrl, newTitle, newLanguage) {
DISQUS.reset({
reload: true,
config: function () {
this.page.identifier = newIdentifier;
this.page.url = newUrl;
this.page.title = newTitle;
this.language = newLanguage;
}
});
};
disqus_reset("$ID$", window.location.href + "$ID$", "$ID$", 'en')
}
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
"""
SELECT_FIRST = """
// on loaded event
$('#nav-tree').on('loaded.jstree', function() {\
$("#nav-tree").jstree('open_all');
if (!document.location.hash) {
$('#nav-tree').jstree('select_node', 'j1_1');
} else {
hash = window.location.hash.substring(1)
$('#nav-tree').jstree('select_node', hash);
}
});
"""
GA = """
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-75220362-1', 'auto');
ga('send', 'pageview');
</script>
"""
def __init__ (self, input_filename, output_filename = None):
"""
Open filename for HTML injection
input_filename - file to process
output_filename - if non provided will override input
"""
self.input_filename = input_filename
self.output_filename = output_filename or input_filename
def __enter__ (self):
# read all the data from file as string
with open(self.input_filename) as f:
try:
self.xml_doc = LH.parse(StringIO(f.read()))
except Exception as e:
print('Could not parse %s, error: %s' % (self.input_filename, e))
return self
def __exit__ (self, exc_type, exc_val, exc_tb):
# save to file
with open(self.output_filename, "w") as f:
f.write(LH.tostring(self.xml_doc))
def inject_toc (self,
toc_json_filename,
fmt = "single",
image_path = "."):
"""
Inject TOC to an input file
toc_json_file - the JSON defining the TOC hierarchy
fmt - can be 'single' for single page or 'multi' for multipage
image_path - where can the images for the TOC be found ?
"""
toc_begin = HTMLInjector.TOC_BEGIN
toc_end = HTMLInjector.TOC_END
# fix image path
toc_begin = toc_begin.replace('$IMGPATH$', image_path)
toc_end = toc_end.replace('$IMGPATH$', image_path)
# fill up TOC JSON file
toc_end = toc_end.replace('input_replace_me.json', toc_json_filename)
# on click event
toc_end = toc_end.replace('$ONCLICK$', HTMLInjector.ONCLICK_MULTIPAGE if fmt == 'multi' else HTMLInjector.ONCLICK_SINGLEPAGE)
# select first on multipage
toc_end = toc_end.replace('$SELECTFIRST$', HTMLInjector.SELECT_FIRST if fmt == 'multi' else '')
# create TOC node
toc_node = LH.parse(StringIO(toc_begin + toc_end)).getroot()
# find the main node in the HTML page
main_node = (self.xml_doc.xpath('//body[@class = "article"]') or self.xml_doc.xpath('//body[@class = "book"]'))[0]
# find the right place to embed the data
toc_csi = toc_node.xpath('//div[@id = "content-section-inner"]')[0]
# take all the children of the main node and embed them in the CSI
for elem in main_node.getchildren():
toc_csi.append(deepcopy(elem))
# final step - replace all the elements with the TOC elements (body, style and etc.)
parent = main_node.getparent()
parent.remove(main_node)
for c in toc_node.getchildren():
parent.append(c)
def inject_disqus (self, page_id):
"""
Inject disqus to HTML
if the page has <disqus></disqus> it will be injected with disqus code
"""
disqus_injection_place = self.xml_doc.findall('.//disqus')
if len(disqus_injection_place) == 0:
return
elif len(disqus_injection_place) > 1:
raise Exception('Multiple disqus components in HTML page - aborting')
# take the first (and only) element
disqus_injection_place = disqus_injection_place[0]
# create the disqus node
disqus_node = LH.parse(StringIO(self.DISQUS_HTML.replace("$ID$", page_id))).getroot()
# inject
disqus_injection_place.getparent().replace(disqus_injection_place, disqus_node)
def inject_title (self, title):
title_elem = self.xml_doc.find(".//title")
if title_elem is None:
raise Exception('unable to find title')
title_elem.text = title
def clear_class (self, class_name):
c = self.xml_doc.xpath('.//div[@class = "{0}"]'.format(class_name))
if not c:
raise Exception('unable to find class {0}'.format(class_name))
c = c[0]
for child in c.getchildren():
c.remove(child)
def inject_ga (self):
# generate node
ga_node = LH.parse(StringIO(self.GA)).getroot()
# fetch the script
script = ga_node.xpath('//script')[0]
# append
self.xml_doc.getroot().append(script)