-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlow_Chart_Generator.py
2624 lines (2275 loc) · 118 KB
/
Flow_Chart_Generator.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
import pyshark
import sys
import os
import subprocess
from io import StringIO
import ipaddress
import glob
import tkinter as tk
from tkinter import filedialog, messagebox,ttk
import webbrowser
import re
import datetime
import windnd
global folder_path,pcap_file_path,line_dict,chart_editing,ISUP_message_dict,MAP_message_dict,html_entities,html_entities_short,from_argv,ip_hostname_map
chart_editing=False
from_argv=False
def assign_color(input_string, assignments, colors):
if input_string not in assignments:
assignments[input_string] = colors[len(assignments) % len(colors)]
return assignments[input_string]
def remove_duplicates(input_list):
return list(dict.fromkeys(input_list))
def replace_special_chars(text):
global html_entities
for key, value in html_entities.items():
if key in text:
text=text.replace(key,value)
return text
def revert_special_chars(text):
global html_entities
for key, value in html_entities.items():
if value in text:
text=text.replace(value,key).replace(""",'"')
return text
def split_into_two(s, separator):
parts = s.split(separator, 1)
if len(parts) == 1: # If the separator was not found
parts.append('') # Append an empty string
return parts
def extract_nodes(text, separator='-->'):
# Pattern to match words with characters and underscore but must contain at least one letter
word_pattern = r'\w*[a-zA-Z]+\w*'
# Split text into lines
lines = text.split('\n')
# Initialize node lists
Node_A = []
Node_B = []
Message_label =[]
Protocol=[]
for line in lines:
# Split line into nodes based on separator
nodes = [node.strip() for node in line.split(separator)]
# Ignore lines with less than 2 nodes
if len(nodes) < 2: continue
# For each node, check if it contains a valid word
valid_nodes = [re.search(word_pattern, node) is not None for node in nodes]
# First node is appended to Node_A if it contains a valid word
if valid_nodes[0]:
trail=replace_special_chars(nodes[0]).strip()
A,garbage=split_into_two(trail, ':')
Node_A.append(A.strip().replace(' ','_'))
# For all middle nodes (if they exist), they are appended as is if they contain a valid word
for node, is_valid in zip(nodes[1:-1], valid_nodes[1:-1]):
if is_valid:
trail=replace_special_chars(node).strip()
B,label=split_into_two(trail, ':')
protocol,label=split_into_two(label, ':')
if not label:
label=protocol
protocol=''
if B:
Node_B.append(B.strip().replace(' ','_'))
Node_A.append(B.strip().replace(' ','_'))
Message_label.append(label.strip())
Protocol.append(protocol.strip())
# Last node is appended to Node_B if it contains a valid word
if valid_nodes[-1]:
trail=replace_special_chars(nodes[-1]).strip()
B,label=split_into_two(trail, ':')
protocol,label=split_into_two(label, ':')
if not label:
label=protocol
protocol=''
Node_B.append(B.strip().replace(' ','_'))
Message_label.append(label.strip())
Protocol.append(protocol.strip())
Node_A, Node_B,Message_label,Protocol = zip(*[(item1, item2,item3,item4) for item1, item2,item3,item4 in zip(Node_A, Node_B,Message_label,Protocol) if item1 and item2])
Node_A=list(Node_A)
Node_B=list(Node_B)
Message_label=list(Message_label)
Protocol=list(Protocol)
return Node_A, Node_B,Message_label,Protocol
def revert_special_chars(text):
global html_entities_short
for key, value in html_entities_short.items():
if value in text:
text=text.replace(value,key).replace(""",'"')
return text
def replace_special_chars_short(text):
global html_entities_short
result = []
for key, value in html_entities_short.items():
if key in text:
text=text.replace(key,value)
return text
def summarise(text):
try:
output=[]
lines = text.split('\n')
for line in lines:
if 'SIP ' not in line and 'Part:' not in line and 'Not supported' not in line and 'Not set' not in line and 'Vendor-Specific' not in line and 'Mandatory' not in line and 'Padding' not in line and 'AVP Length' not in line and 'AVP Code:' not in line and 'Vendor-Id:' not in line and 'Country Code:' not in line and 'URI parameter:' not in line and 'Host Port:' not in line and 'VendorId:' not in line and ' Userinfo:' not in line and 'E.164 number (MSISDN):' not in line and ' URI:' not in line and 'AVP Vendor Id:' not in line:
line=replace_special_chars_short(line)
output.append(line)
return '\n'.join(output)
except:
return ''
def text_to_html(text):
lines = text.split('\n')
html_lines = []
for line in lines:
if 'SIP ' not in line and 'Part:' not in line and 'Not supported' not in line and 'Not set' not in line and 'Vendor-Specific' not in line and 'Mandatory' not in line and 'Padding' not in line and 'AVP Length' not in line and 'AVP Code:' not in line and 'Vendor-Id:' not in line and 'Country Code:' not in line and 'URI parameter:' not in line and 'Host Port:' not in line and 'VendorId:' not in line and ' Userinfo:' not in line and 'E.164 number (MSISDN):' not in line and ' URI:' not in line and 'AVP Vendor Id:' not in line:
line=replace_special_chars_short(line)
if '==>' in line:
html_line = f'<p class="separator" style="font-weight:bold;font-family:Courier New;">{line}</p>'
elif 'Message Body' in line:
html_line = f'<p style="font-weight:bold;font-family:Courier New;">{line}</p>'
elif 'Command Code' in line or '-Line' in line:
html_line = re.sub(r'(\w+:)(.*)', r'\1<span style="color:blue;font-weight:bold;">\2</span>', line)
html_line = f'<p style="font-family:Courier New;">{html_line}</p>'
elif re.search(r'\w+:', line):
html_line = re.sub(r'(\w+:)(.*)', r'\1<span style="color:blue;">\2</span>', line)
html_line = f'<p style="font-family:Courier New;">{html_line}</p>'
elif '----' in line:
html_line = f'<p class="separator" style="font-weight:bold;color:green;font-family:Courier New;">{line}</p>'
else:
html_line = f'<p style="font-family:Courier New;">{line}</p>'
html_lines.append(html_line)
html_content = ''.join(html_lines)
html = f'<html>\n<head>\n<meta charset="utf-8" content="width=device-width, initial-scale=1.0">\n</head>\n<body>\n{html_content}\n</body>\n</html>'
html=html.replace('</head>','<style>\np{\nline-height:1;\nmargin:0;\npadding:0;\n}\n.separator{\nmargin-top:10px;\nmargin-bottom:10px;\n}\n</style></head>')
return html
global filter_str
thisdict = {
"1": "R",
"0": "A"
}
line_dict={
"solid-Unidirectionnel":"=>",
"dotted-Unidirectionnel":">>",
"solid-bidirectionnel":"<=>",
"dotted-bidirectionnel":"<<>>",
"solid-no-arrow":"--",
"dotted-no-arrow":"..",
"rounded-box":"rbox"}
diam_code={
"265": "AA",
"268": "DE",
"274": "AS",
"271": "AC",
"272": "CC",
"257": "CE",
"280": "DW",
"282": "DP",
"258": "RA",
"275": "ST",
"283": "UA",
"284": "SA",
"285": "LI",
"286": "MA",
"287": "RT",
"288": "PP",
"300": "UA",
"301": "SA",
"302": "LI",
"303": "MA",
"304": "RT",
"305": "PP",
"306": "UD",
"307": "PU",
"308": "SN",
"309": "PN",
"310": "BI",
"311": "MP",
"316": "UL",
"317": "CL",
"318": "AI",
"319": "ID",
"320": "DS",
"321": "PE",
"8388620": "PL",
"8388622": "RI",
"260": "AM",
"262": "HA",
"8388718": "CI",
"8388719": "RI",
"8388726": "NI"
}
ISUP_message_dict = {
"1": "IAM",
"2": "SAM",
"3": "INR",
"4": "INF",
"5": "COT",
"6": "ACM",
"7": "CON",
"8": "FOT",
"9": "ANM",
"B": "REL",
"C": "SUS",
"D": "RES",
"E": "RES",
"10": "RLC",
"11": "CCR",
"12": "RSC",
"13": "BLO",
"14": "UBL",
"15": "BLA",
"16": "UBA",
"1C": "CMR",
"1D": "CMC",
"1F": "FRJ",
"20": "FAA",
"21": "FAR",
"2C": "CPG",
"2D": "USR"
}
MAP_message_dict = {
1: "sendAuthenticationInfo",
2: "updateLocation",
3: "cancelLocation",
4: "provideRoamingNumber",
5:"noteSubscriberDataModified",
7:"insertSubscriberData",
8:"deleteSubscriberData",
9:"sendParameters",
10:"registerSS",
12:"activateSS",
16: "insertSubscriberData",
17: "deleteSubscriberData",
18: "getPassword",
19: "registerSS",
20: "eraseSS",
21: "activateSS",
22: "sendRoutingInfo",
23: "updateGprsLocation ",
24: "authenticationFailureReport",
27: "registerPassword",
28: "getPassword",
29: "updateGprsLocation",
30: "sendRoutingInfoForGprs",
31: "failureReport",
32: "noteMsPresentForGprs",
34: "sendAuthenticationInfo",
37:"reset",
38:"forwardCheckSS-Indication",
43:"checkIMEI",
44:"mt-ForwardSM",
45: "restoreData",
46: "sendEndSignal",
49: "processUnstructuredSS-Request",
50: "unstructuredSS-Request",
51: "unstructuredSS-Notify",
52: "anyTimeInterrogation",
53: "ssi-Activate",
55: "provideSubscriberInfo",
56: "sendAuthenticationInfo",
57: "restoreData",
58: "sendIMSI",
59: "cancelLocation-Sgsn",
60: "provideSubscriberLocation",
61: "sendRoutingInfoForLCS",
62: "subscriberLocationReport",
67: "purgeMS",
68: "mt-ForwardSM",
70: "provideSubscriberInfo",
72: "reportSMDeliveryStatus",
73: "activateTraceMode",
74: "deactivateTraceMode",
75: "sendIdentification",
76: "updateFaLang",
77: "sendRoutingInfoForGprs-Sgsn",
78: "failureReport-Sgsn",
79: "noteMsPresentForGprs-Sgsn",
80: "provideSubscriberLocation-Sgsn",
81: "provideSubscriberLocation-Msc",
82: "subscriberLocationReport-Sgsn",
83: "subscriberLocationReport-Msc",
84: "sendIdentification-Sgsn",
85: "reset",
86: "forwardCheckSS-Indication",
87: "prepareHandover",
88: "prepareSubsequentHandover",
89: "provideSIWFSNumber",
90: "sendRoutingInfoForLCS-Msc",
91: "sendRoutingInfoForLCS-Sgsn",
92: "subscriberLocationReport-LCS",
93: "cancelVcsgLocation",
94: "resetVcsg",
96: "forwardShortMessage",
97: "prepareGroupCall",
98: "sendGroupCallEndSignal",
99: "processGroupCallSignalling",
100: "forwardGroupCallSignalling",
101: "checkIMEI",
102: "mt-ForwardShortMessage",
103: "sendRoutingInfoForSM",
104: "mo-ForwardShortMessage",
105: "reportSM-DeliveryStatus",
106: "noteSubscriberPresent",
107: "alertServiceCentreWithoutResult",
108: "activateTraceMode",
109: "deactivateTraceMode",
110: "sendAuthenticationInfo",
111: "sendImsi",
112: "processUnstructuredSS-Data",
113: "unstructuredSS-Request",
114: "unstructuredSS-Notify",
115: "anyTimeInterrogation",
116: "setReportingState",
117: "statusReport",
118: "remoteUserFree",
119: "registerCC-Entry",
120: "eraseCC-Entry"
}
html_entities = {
"\"": "'",
""": "'",
"<": "<",
">": ">",
"ä": "ae",
"Ä": "AE",
"ü": "ue",
"Ü": "UE",
"ö": "oe",
"Ö": "OE",
"ß": "ss"
}
html_entities_short = {
"\"": "'",
""": "'" ,
"<": "<",
">": ">"
}
def generate_chart():
global folder_path,pcap_file_path,progress_bar,root,remaining_files_label,remaining_files_var,edit_chart_button,add_filter_combo,generate_button,add_filter_label,checkbox,filter_label,filter_entry
if pcap_file_path:
filter_str = filter_entry.get("1.0", "end-1c")
html_file_name=pcap_file_path.replace('.pcapng','.html').replace('.pcap','.html')
try:
os.remove(html_file_name)
except:
a=0
main(pcap_file_path, filter_str)
webbrowser.open(html_file_name)
edit_chart_button.config(state=tk.NORMAL)
elif folder_path:
filter_str = filter_entry.get("1.0", "end-1c")
progress_bar.grid()
remaining_files_label.grid()
root.update_idletasks()
total_lines = 0
total_txt_files = 0
processed_files = 0
for root_fold, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.pcap') or file.endswith('.pcapng'):
total_txt_files += 1
if total_txt_files == 0:
tk.messagebox.showinfo("No file", "No pcap files found in the selected folder and its sub-directories")
progress_bar.grid_remove() # Hide the progress bar
return
progress_bar['maximum'] = total_txt_files
for root_fold, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.pcap') or file.endswith('.pcapng'):
main(os.path.join(root_fold, file).replace('\\','/'), filter_str)
processed_files += 1
progress_bar['value'] = processed_files
remaining_files_var.set(f"Remaining files: {total_txt_files - processed_files}")
root.update_idletasks()
messagebox.showinfo("Information",'Chart generation completed')
progress_bar['value'] = 0
progress_bar.grid_remove()
remaining_files_label.grid_remove()
else:
messagebox.showerror("Error", "No PCAP file selected.")
def exit_application():
global ip_hostname_map
import os
root.destroy()
def edit_chart():
global chart_editing
chart_editing=True
create_edit_chart_window()
def load_clipboard():
global nodes,chart_editing,Node_A_table,Node_B_table, Protocol_table, Message_label_table, Message_content_table, Color_Table, Note_Table,current_message_index,Arrow_table,description,title
import pyperclip
from unidecode import unidecode
text = pyperclip.paste()
if text and text.strip():
try:
try:
own_chart_window.destroy()
except:
a=0
text=text.replace('\uf0e0', '->')
text=text.replace('\uf0e8', '->')
text=text.replace('\uf0f3', '->')
text=text.replace('\uf0df', '->')
text=text.replace('\uf0e7', '->')
text=unidecode(text)
text=text.replace('<-->','->').replace('<==>','->').replace('<=>','->').replace('<->','->').replace('-->','->').replace('==>','->').replace('<--','->').replace('<==','->').replace('<-','->').replace('<=','->').replace('=>','->').replace('(','_').replace(')','_').replace(',','_').replace(';',' ').replace('>>','->')
if '->' in text:
separator='->'
Node_A_table, Node_B_table,Message_label_table,Protocol_table = extract_nodes(text, separator)
Arrow_table=[]
Message_content_table=[]
Color_Table=[]
Note_Table=[]
description=''
title=''
for i in range(len(Node_A_table)):
Color_Table.append('black')
#Protocol_table.append('')
Message_content_table.append('')
#Message_label_table.append('')
Note_Table.append('')
if 'diameter' in Protocol_table[i].lower() or 'dns' in Protocol_table[i].lower() or 'camel' in Protocol_table[i].lower() or 'map' in Protocol_table[i].lower():
Arrow_table.append('dotted-Unidirectionnel')
else:
Arrow_table.append('solid-Unidirectionnel')
current_message_index=0
edit_chart_button.config(state=tk.NORMAL)
edit_chart()
else:
tk.messagebox.showinfo("Clipboard content not valid", """
Create a text file describing a chart and copy it to clipboard.
Example 1 :
UE => SBC
SBC => UE
SBC => PCRF
PCRF => SBC
Example 2 :
UE => SBC : SIP:INVITE
SBC=> UE : SIP:100 trying
SBC => PCRF : DIAMETER:AAR
PCRF => SBC : DIAMETER:AAA
Example 3 (same output as example 2 ):
UE => SBC : SIP:INVITE => UE: SIP:100 trying
SBC => PCRF : DIAMETER:AAR => SBC : DIAMETER:AAA
separators between node names could be => or -> or ==> or --> (same output)""")
except:
tk.messagebox.showinfo("Clipboard content not valid", """
Create a text file describing a chart and copy it to clipboard.
Example 1 :
UE => SBC
SBC => UE
SBC => PCRF
PCRF => SBC
Example 2 :
UE => SBC : SIP:INVITE
SBC=> UE : SIP:100 trying
SBC => PCRF : DIAMETER:AAR
PCRF => SBC : DIAMETER:AAA
Example 3 (same output as example 2 ):
UE => SBC : SIP:INVITE => UE: SIP:100 trying
SBC => PCRF : DIAMETER:AAR => SBC : DIAMETER:AAA
separators between node names could be => or -> or ==> or --> (same output)""")
else:
tk.messagebox.showinfo("Clipboard empty", """
Create a text file describing a chart and copy it to clipboard.
Example 1 :
UE => SBC
SBC => UE
SBC => PCRF
PCRF => SBC
Example 2 :
UE => SBC : SIP:INVITE
SBC=> UE : SIP:100 trying
SBC => PCRF : DIAMETER:AAR
PCRF => SBC : DIAMETER:AAA
Example 3 (same output as example 2 ):
UE => SBC : SIP:INVITE => UE: SIP:100 trying
SBC => PCRF : DIAMETER:AAR => SBC : DIAMETER:AAA
separators between node names could be => or -> or ==> or --> (same output)""")
def create_own_chart_window():
global chart_editing,pcap_file_path,folder_path,flowchart_file_path,generate_button,add_filter_combo,add_filter_label,checkbox,filter_label,filter_entry
try:
file_label.config(text='')
pcap_file_path=None
folder_path=None
flowchart_file_path=None
except:
a=0
chart_editing=False
edit_chart_button.config(state=tk.DISABLED)
generate_button.config(state=tk.DISABLED)
add_filter_combo.config(state=tk.DISABLED)
add_filter_label.config(state=tk.DISABLED)
filter_label.config(state=tk.DISABLED)
filter_entry.config(state=tk.DISABLED)
create_edit_chart_window()
def create_edit_chart_window():
global Node_A_table, Node_B_table,Protocol_table,Message_label_table,Message_content_table,Color_Table,Note_Table,current_message_index,Arrow_table,chart_editing,own_chart_window,description,title
try:
own_chart_window.destroy()
except:
a=0
protocol_var = tk.StringVar()
own_chart_window = tk.Toplevel()
#own_chart_window.geometry("800x800")
frame1 = tk.Frame(own_chart_window, bd=2, relief="groove")
frame1.grid(row=0, column=0, padx=10, pady=10, sticky="we")
frame2 = tk.Frame(own_chart_window, bd=2, relief="groove")
frame2.grid(row=1, column=0, padx=10, pady=10, sticky="we")
frame3 = tk.Frame(own_chart_window, bd=2, relief="groove")
frame3.grid(row=2, column=0, padx=10, pady=10, sticky="we")
frame3bis = tk.Frame(frame3, bd=2, relief="groove")
frame3bis.grid(row=0, column=4, padx=10, pady=10)
frame4 = tk.Frame(own_chart_window, bd=2, relief="groove")
frame4.grid(row=1, column=1, padx=10, pady=10)
frame5 = tk.Frame(own_chart_window)
frame5.grid(row=3, column=0, padx=10, pady=10, sticky="we") # expand frame horizontally
frame5.columnconfigure(1, weight=1) # make the middle column expandable
frame6 = tk.Frame(own_chart_window)
frame6.grid(row=4, column=0, padx=10, pady=10)
if not chart_editing:
Node_A_table = []
Node_B_table = []
Protocol_table = []
Message_label_table = []
Message_content_table = []
Arrow_table=[]
Note_Table= []
Color_Table=[]
description=''
title=''
current_message_index=0
class ToolTip(object):
def __init__(self, widget):
self.widget = widget
self.tipwindow = None
self.id = None
self.x = self.y = 0
def showtip(self, text):
"Display text in tooltip window"
self.text = text
if self.tipwindow or not self.text:
return
x, y, _, _ = self.widget.bbox("insert")
x = x + self.widget.winfo_rootx() + 57
y = y + self.widget.winfo_rooty() + 27
self.tipwindow = tw = tk.Toplevel(self.widget)
tw.wm_overrideredirect(1)
tw.wm_geometry("+%d+%d" % (x, y))
label = tk.Label(tw, text=self.text, background="#ffffe0", relief='solid', borderwidth=1,
font=("tahoma", "8", "normal"))
label.pack(ipadx=1)
def hidetip(self):
tw = self.tipwindow
self.tipwindow = None
if tw:
tw.destroy()
def createToolTip(widget, text):
toolTip = ToolTip(widget)
def enter(event):
toolTip.showtip(text)
def leave(event):
toolTip.hidetip()
widget.bind('<Enter>', enter)
widget.bind('<Leave>', leave)
def contains_zero_or_one_word(strings):
for s in strings:
words = s.split()
if len(words) > 1:
return False
return True
def load_hosts():
global nodes,chart_editing,Node_A_table,Node_B_table
import pyperclip
if chart_editing:
try:
if Node_A_table:
return remove_duplicates(Node_A_table+Node_B_table)
except:
return []
hosts = []
clipboard_content = pyperclip.paste()
if not clipboard_content:
# try:
# with open('hosts.txt', 'r') as f:
# for line in f.readlines():
# try:
# hosts.append(line.split()[1].replace('*',''))
# except:
# a=0
# except:
# a=0
# return sorted(list(set(hosts)))
return hosts
else:
lines = clipboard_content.split('\n')
if contains_zero_or_one_word(lines) :
hosts = [line.split()[0] for line in lines if line.strip() != '']
if len(hosts) >1:
return remove_duplicates(hosts)
else:
hosts=[]
return hosts
else:
return hosts
def update_combobox(event):
current_text = event.widget.get()
event.widget['values'] = [item for item in hosts if current_text.lower() in item.lower()]
def append_combobox_value(event):
current_text = event.widget.get()
if current_text not in hosts:
hosts.append(current_text)
#hosts.sort()
node_a_combo['values'] = hosts
node_b_combo['values'] = hosts
node_a_combo.set('')
node_b_combo.set('')
def disable_widget():
current= arrow_combo.get()
if current=='rounded-box':
protocol_combo.set('')
#protocol_combo.config(state='disabled')
note_content_text.delete("1.0", tk.END)
#note_content_text.config(state='disabled')
message_content_text.delete("1.0", tk.END)
#message_content_text.config(state='disabled')
else:
protocol_combo.set('SIP')
protocol_combo.config(state='normal')
#note_content_text.delete("1.0", tk.END)
note_content_text.config(state='normal')
#message_content_text.delete("1.0", tk.END)
message_content_text.config(state='normal')
def update_add_new_message_button():
if node_a_combo.get() and node_b_combo.get(): # if both are not empty
add_new_message_button.config(state='normal') # enable the button
overwrite_button.config(state='normal')
else:
add_new_message_button.config(state='disabled') # disable the button
overwrite_button.config(state='disabled')
if node_a_combo.get():
filter_nodea_button.config(state='normal')
filterout_nodea_button.config(state='normal')
else:
filter_nodea_button.config(state='disabled')
filterout_nodea_button.config(state='disabled')
if node_b_combo.get():
filter_nodeb_button.config(state='normal')
filterout_nodeb_button.config(state='normal')
else:
filter_nodeb_button.config(state='disabled')
filterout_nodeb_button.config(state='disabled')
if message_content_text.get("1.0", tk.END).strip():
filterout_message_button.config(state='normal')
filter_message_button.config(state='normal')
else:
filterout_message_button.config(state='disabled')
filter_message_button.config(state='disabled')
def append_protocol_value(event):
current_text = event.widget.get()
Valeurs=list(protocol_combo['values'])
if current_text not in Valeurs:
Valeurs.append(current_text)
#hosts.sort()
protocol_combo['values'] = Valeurs
protocol_combo.set('')
def add_new_message():
global current_message_index
Node_A_table.insert(current_message_index+1,replace_special_chars(node_a_combo.get()).replace(' ','_'))
Node_B_table.insert(current_message_index+1,replace_special_chars(node_b_combo.get()).replace(' ','_'))
Color_Table.insert(current_message_index+1,color_combo.get())
Protocol_table.insert(current_message_index+1,protocol_combo.get())
Message_label_table.insert(current_message_index+1,replace_special_chars(message_label_entry.get()))
Message_content_table.insert(current_message_index+1,replace_special_chars(message_content_text.get("1.0", tk.END).strip()))
Note_Table.insert(current_message_index+1,replace_special_chars(note_content_text.get("1.0", tk.END).strip()).replace('\n','\\n'))
Arrow_table.insert(current_message_index+1,arrow_combo.get())
current_message_index+=1
update_status_bar()
Valeurs=list(protocol_combo['values'])
if node_a_combo.get() not in hosts :
hosts.append(node_a_combo.get())
node_a_combo['values']=hosts
node_b_combo['values']=hosts
if node_b_combo.get() not in hosts :
hosts.append(node_b_combo.get())
node_a_combo['values']=hosts
node_b_combo['values']=hosts
if protocol_combo.get() and protocol_combo.get() not in Valeurs:
Valeurs.append(protocol_combo.get())
protocol_combo['values'] = Valeurs
def previous_message():
global current_message_index
if current_message_index > 0:
current_message_index -= 1
display_message(current_message_index)
update_status_bar()
# elif len(Node_A_table)>0:
# current_message_index=len(Node_A_table)-1
# display_message(current_message_index)
# update_status_bar()
if node_a_combo.get() and node_b_combo.get():
add_new_message_button.config(state="normal")
def first_message():
global current_message_index
try:
current_message_index =0
display_message(current_message_index)
update_status_bar()
except:
a=0
if node_a_combo.get() and node_b_combo.get():
add_new_message_button.config(state="normal")
def last_message():
global current_message_index
try:
current_message_index =len(Node_A_table) - 1
display_message(current_message_index)
update_status_bar()
except:
a=0
if node_a_combo.get() and node_b_combo.get():
add_new_message_button.config(state="normal")
def next_message():
global current_message_index
if current_message_index < len(Node_A_table) - 1:
current_message_index += 1
display_message(current_message_index)
update_status_bar()
# elif len(Node_A_table)>0:
# current_message_index=0
# display_message(current_message_index)
# update_status_bar()
if node_a_combo.get() and node_b_combo.get():
add_new_message_button.config(state="normal")
def display_message(index):
try:
node_a_combo.set(revert_special_chars(Node_A_table[index]))
node_b_combo.set(revert_special_chars(Node_B_table[index]))
color_combo.set(Color_Table[index])
protocol_combo.set(Protocol_table[index])
arrow_combo.set(Arrow_table[index])
message_label_entry.delete(0, tk.END)
message_label_entry.insert(0, revert_special_chars(Message_label_table[index]))
message_content_text.delete("1.0", tk.END)
message_content_text.insert("1.0", revert_special_chars(Message_content_table[index]))
note_content_text.delete("1.0", tk.END)
note_content_text.insert("1.0", revert_special_chars(Note_Table[index].replace('\\n','\n')))
update_status_bar()
except:
node_a_combo.set('')
node_b_combo.set('')
color_combo.set('black')
arrow_combo.set('solid-Unidirectionnel')
protocol_combo.set('SIP')
message_label_entry.delete(0, tk.END)
message_content_text.delete("1.0", tk.END)
note_content_text.delete("1.0", tk.END)
def update_current_message():
global current_message_index
if node_a_combo.get() and node_b_combo.get():
if 0 <= current_message_index < len(Node_A_table):
Node_A_table[current_message_index] = replace_special_chars(node_a_combo.get())
Node_B_table[current_message_index] = replace_special_chars(node_b_combo.get())
Color_Table[current_message_index] = color_combo.get()
Protocol_table[current_message_index] = protocol_combo.get()
Message_label_table[current_message_index] = replace_special_chars(message_label_entry.get())
Message_content_table[current_message_index] = replace_special_chars(message_content_text.get("1.0", tk.END).strip())
Note_Table[current_message_index] = replace_special_chars(note_content_text.get("1.0", tk.END).strip()).replace('\n','\\n')
Arrow_table[current_message_index] = arrow_combo.get()
else:
if 0 <= current_message_index < len(Node_A_table):
del Node_A_table[current_message_index]
del Node_B_table[current_message_index]
del Color_Table[current_message_index]
del Protocol_table[current_message_index]
del Arrow_table[current_message_index]
del Message_label_table[current_message_index]
del Message_content_table[current_message_index]
del Note_Table[current_message_index]
if 0 <= current_message_index+1 < len(Node_A_table):
current_message_index+=1
display_message(current_message_index)
elif 0 <= current_message_index-1 < len(Node_A_table):
current_message_index-=1
display_message(current_message_index)
if node_a_combo.get() and node_a_combo.get() not in hosts :
hosts.append(node_a_combo.get())
node_a_combo['values']=hosts
node_b_combo['values']=hosts
if node_b_combo.get() and node_b_combo.get() not in hosts :
hosts.append(node_b_combo.get())
node_a_combo['values']=hosts
node_b_combo['values']=hosts
update_status_bar()
def update_status_bar():
status_text.set(f"Number of messages in chart: {len(Node_A_table)}")
if len(Node_A_table) > 0:
message_number_text.set(f"Message {current_message_index + 1}")
else:
message_number_text.set('')
def overwrite_node():
global current_message_index,Node_A_table,Node_B_table,ip_hostname_map
if node_a_combo.get() and node_b_combo.get():
if len(Node_A_table) > 0:
new=node_a_combo.get()
try:
old=Node_A_table[current_message_index]
except:
old=Node_A_table[current_message_index-1]
if new!=old:
for i in range(len(Node_A_table)):
if Node_A_table[i] == old:
Node_A_table[i] = new
if Node_B_table[i] == old:
Node_B_table[i] = new
node_a_combo.set(new)
liste= node_a_combo['values']
liste =[new if item == old else item for item in liste]
liste=remove_duplicates(liste)
node_a_combo['values']=liste
node_b_combo['values']=liste
if is_valid_ip(old.replace('_','.')):
ip_hostname_map[old.replace('_','.')] = new
if is_valid_ip(old.replace('_',':')):
ip_hostname_map[old.replace('_',':')] = new
if len(Node_B_table) > 0:
new=node_b_combo.get()
try:
old=Node_B_table[current_message_index]
except:
old=Node_B_table[current_message_index-1]
if new!=old:
for i in range(len(Node_B_table)):
if Node_A_table[i] == old:
Node_A_table[i] = new
if Node_B_table[i] == old:
Node_B_table[i] = new
node_b_combo.set(new)
liste= node_a_combo['values']
liste =[new if item == old else item for item in liste]
liste=remove_duplicates(liste)
node_a_combo['values']=liste
node_b_combo['values']=liste
if is_valid_ip(old.replace('_','.')):
ip_hostname_map[old.replace('_','.')] = new
if is_valid_ip(old.replace('_',':')):
ip_hostname_map[old.replace('_',':')] = new
def clear_chart():
global Node_A_table, Node_B_table, Protocol_table, Message_label_table, Message_content_table, Color_Table, Note_Table,current_message_index,Arrow_table,description,title
Node_A_table.clear()
Node_B_table.clear()
Protocol_table.clear()
Arrow_table.clear()
Message_label_table.clear()
Message_content_table.clear()
Color_Table.clear()
Note_Table.clear()
description=''
title=''
current_message_index=0
update_status_bar()
edit_chart_button.config(state=tk.DISABLED)
def update_arrow_combo(protocol_var):