-
Notifications
You must be signed in to change notification settings - Fork 0
/
exmsearch
executable file
·2980 lines (2736 loc) · 111 KB
/
exmsearch
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/python2.7
# -*- coding: utf-8 -*-
import urwid
import datetime
import io
import os
import subprocess
import sys
import json
import re
import shlex
import gzip
import time
import logging
import collections
import socket
import threading
import getpass
from itertools import islice
from multiprocessing import Pool, Queue, current_process, connection, cpu_count
from multiprocessing.pool import ThreadPool
from datetime import datetime, timedelta
os.nice(10)
FORMAT = '%(lineno)d :: %(funcName)s :: %(message)s'
if getpass.getuser() == 'root':
logpath = '/root/eximsearch.log'
else:
logpath = '/home/' + getpass.getuser() + '/eximsearch.log'
logging.basicConfig(
format=FORMAT,
filename=logpath,
filemode='a',
level=logging.DEBUG)
ACTIVE = 'active'
PREV = 'prev'
BODY = 'body'
HEADER = 'header'
FOOTER = 'footer'
urwid.set_encoding("UTF-8")
info = logging.info
debug = logging.debug
warning = logging.warning
PYTHONIOENCODING = "utf-8"
debug('Encoding Type: %s', PYTHONIOENCODING)
"""
SETTINGS / DEFAULT VALUE CLASSES
"""
class GlobalSettings():
def __init__(self):
"""This class contains general settings / default variables for the application
"""
self.dt = DateTimeSettings()
self.lf = LogFileSettings()
self.rl = ResultListSettings()
self.df = DisplayFrameSettings()
self.menus = Menus()
self.hostname = socket.gethostname()
self.menuEnabled = True
self.divChars = 1
self.filterGuide = (
"You can have multiple filters per filter "
"type(ie. multiple senders, multiple recipients, etc) "
"and these will be filtered as OR. \nEx: "
"Two sender filters of user1@domain.com and user2@domain.com, "
"will show all query results that were sent by user1@domain.com "
"OR user2@domain.com.\nFilters of different types are filtered "
"as AND. Ex: Sender filter user1@domain.com and Date filter "
"of 2019-05-24, will show all query results that were sent by "
"user1@domain.com on the date 2019-05-24\nAcceptable "
"Date-time Formats:MM-DD-YYYY or MM-DD-YYYY_HH:MM:SS\n"
"Date Range formats: Start date,End date with NO SPACES. "
"Ex: 2019-05-01,2019-05-31\nMessage Type Options: "
"Incoming, Outgoing, Local"
)
self.filterTypes = [
'sender',
'recipient',
'date',
'type'
]
def dyn_debug(self, *args):
# print('Current User: ' + getpass.getuser())
# queryLogProcess2(['wolfindva.com','/var/log/exim_mainlog-20190421'])
with open('debug.json', 'r') as debug_file:
x = json.load(debug_file, 'utf-8')
try:
eval(x['command'])
except Exception as e:
debug('Exception is : %s', e)
else:
pass
return eval(x['command'])
def unhandled_input(self, key):
if type(key) == str:
if key in 'ctrl e':
views.activate('quit_loop', focus_position=BODY)
if 'ctrl n' in key:
views.activate('new_search', focus_position=BODY)
if 'ctrl f' in key:
views.activate('add_remove_filters', focus_position=BODY)
if key in ('B', 'b'):
if 'single_entry' in state.get_view_name(ACTIVE):
views.activate('results_list', focus_position='body')
if key in 'tab':
if frame.focus_position == 'footer':
frame.focus_position = 'body'
else:
if self.menuEnabled:
frame.focus_position = 'footer'
if 'home' in key:
state.go_back()
if 'end' in key:
state.go_forward()
if key in 'f5':
debug('Current View: %s', state.get_view_name(ACTIVE))
if hasattr(state, 'prev_view'):
if state.prev_view:
debug('Previous View: %s', state.get_view_name(PREV))
if key in 'f6':
debug('Active Filters: %s', state.get_active_filters())
if key in 'f7':
debug('Current Query: %s', state.get_query(ACTIVE))
if hasattr(state, 'prev_query'):
debug('Previous Query: %s', state.get_query(PREV))
if key in 'f3':
self.dyn_debug()
# debug('Body: %s', self.dyn_debug())
if key in 'f1':
debug(
'Current Result List: %s',
state.get_result_list_name(ACTIVE))
if hasattr(state, 'prev_result_list'):
debug(
'Previous Result List: %s',
state.get_result_list_name(PREV))
if key in 'f2':
debug(
'Current View Chain Position: %s',
state.get_view_chain_pos())
debug(
'Current View Chain Name: %s',
state.get_view_from_chain(
state.get_view_chain_pos()).view_name)
class DateTimeSettings():
def __init__(self):
"""Settings for DateTime functions / formatting
"""
self.logDateFormat = "%Y-%m-%d"
self.displayDateFormat = "%m-%d-%Y"
self.stringToDateFormat = "%Y-%m-%d"
self.logDateTimeFormat = "%Y-%m-%d_%H:%M:%S.%f"
self.displayDateTimeFormat = "%m-%d-%Y_%H:%M:%S"
def stringToDate(self, newFilter):
try:
datetime.strptime(newFilter, self.displayDateTimeFormat)
except ValueError:
try:
datetime.strptime(newFilter, self.displayDateFormat)
except:
return False
else:
return datetime.strptime(newFilter, self.displayDateFormat)
else:
return datetime.strptime(newFilter, self.displayDateTimeFormat)
class DisplayFrameSettings():
def __init__(self):
"""Settings & Defaults for the Applications Interface
"""
self.mainTitle = 'Exim Search Utility'
self.mainSubTitle = 'If you can do it better, then do it'
self.palette = [
# Name , foreground, background
('header', 'black', 'light gray'),
('footer', 'black', 'light gray'),
('body', 'white', 'default'),
('bold', 'dark green, bold', 'black'),
('blue', 'bold', 'dark blue'),
('highlight', 'dark green', 'default'),
('alert', 'dark red, bold', 'default'),
]
class Menus():
def __init__(self):
self.choose_logs = [
['(Q)uit', 'quit_loop']]
self.coming_soon = [
[' (H)ome ', 'home']]
self.stat_summary_results = self.coming_soon
self.home = [
[' New Search ', 'new_search'],
[' Add / Remove Filters ', 'add_remove_filters'],
[' cPanel User Stats ', 'stat_summary'],
[' Change Log Selection ', 'choose_logs'],
[' Quit ', 'quit_loop']]
self.new_search = self.home
self.search_progress = self.home
self.stat_summary = self.home
self.results_list = [
['Filter Current Results', 'add_remove_filters'],
[' Clear Applied Filters', 'clear_applied_filters'],
[' Home ', 'home'],
[' New Search ', 'new_search'],
[' Quit ', 'quit_loop']]
self.results_summary = self.results_list
self.apply_filters = self.results_list
self.clear_applied_filters = self.results_list
self.single_entry = [
[' Back To Result List ', 'results_list'],
[' Home ', 'home'],
[' New Search ', 'new_search'],
[' Quit ', 'quit_loop']]
self.add_remove_filters = [
['Apply Current Filters ', 'apply_filters'],
[' Back To Result List ', 'results_list'],
[' Home ', 'home'],
[' New Search ', 'new_search'],
[' Quit ', 'quit_loop']]
self.add_remove_filters_no_apply = [
[' New Search ', 'new_search'],
[' Home ', 'home'],
[' Quit ', 'quit_loop']]
self.quit_loop = []
self.legend = [
['Prev. Screen', 'Home'],
['Next Screen', 'End'],
['Change Fields', '← / ↑ / ↓ / →'],
['Move to / from Menu', 'Tab'],
['New Search', 'Ctrl + N'],
['Add / Remove Filters', 'Ctrl + F'],
['Exit', 'Ctrl + E']
]
class LogFileSettings():
def __init__(self):
"""Settings for the LogFile class / objects
"""
self.dir = '/var/log/'
self.mainLogName = 'exim_mainlog'
self.mainLogPath = os.path.join(self.dir, self.mainLogName)
self.selectedLogs = []
class ResultListSettings():
def __init__(self):
"""Settings specific to the ResultList view
"""
self.ButtonColWidth = 7
self.divChars = 1
self.resultOverflow = False
s = GlobalSettings()
"""
CUSTOM WIDGET CLASSES
"""
class ButtonLabel(urwid.SelectableIcon):
def __init__(self, text):
"""Subclassing for urwid.Button's labeling
This customization removes the cursor from
the active button
This should only need to be called by the
FixedButton class.
Arguments:
urwid {class} -- urwid base class
text {str} -- Button Label
"""
curs_pos = len(text) + 1
urwid.SelectableIcon.__init__(
self,
text,
cursor_position=curs_pos)
class FixedButton(urwid.Button):
"""SubClass of the urwid.Button class used
along with ButtonLabel in order to customize
the appearance and behavior of buttons.
Arguments:
urwid {class} -- urwid base class
Returns:
urwid.Button -- a standard urwid Button
"""
_selectable = True
signals = ["click"]
def __init__(self, thisLabel, on_press=None, user_data=None):
"""Creates a new Button
Arguments:
thisLabel {text} -- Button Label
Keyword Arguments:
on_press {callback} -- function to be executed on click
(default: {None})
user_data {tuple} -- tuple (or list) that contains any arguments
or data to be passed to on_ress function (default: {None})
"""
self._label = ButtonLabel(thisLabel)
# you could combine the ButtonLabel object with other widgets here
self.user_data = user_data
self.on_press = on_press
display_widget = self._label
urwid.WidgetWrap.__init__(
self,
urwid.AttrMap(
display_widget,
None,
focus_map="header"))
self.callback = on_press
def keypress(self, size, key):
"""Overrides default urwid.Button.keypress method
Arguments:
size {int} -- size of widget
key {bytes or unicode} -- [a single keystroke value]
Returns:
None or Key -- [None if key was handled by this widget or
key (the same value passed) if key was
not handled by this widget]
"""
if key in ('enter', 'space'):
if self.user_data is not None:
self.callback(self.user_data)
else:
self.callback()
else:
return key
def set_label(self, new_label):
"""Method to allow changing the button's label
Arguments:
new_label {[str]} -- [New Button Label]
"""
self._label.set_text(str(new_label))
def mouse_event(self, size, event, button, col, row, focus):
"""
handle any mouse events here
and emit the click signal along with any data
"""
pass
def disable(self):
"""Function to allow the disabling of the button"""
_selectable = False
def enable(self):
"""Function to allow the enabling of a disabled button"""
_selectable = True
class QuestionBox(urwid.Filler):
def keypress(self, size, key):
if key != 'enter':
return super(QuestionBox, self).keypress(size, key)
user_input = self.original_widget.get_edit_text()
if len(user_input) >= 255:
self.original_widget.set_caption(
'Input Must be 255 Characters or Less\nPlease Try Again\n')
self.original_widget.set_edit_text('')
else:
entry = self.original_widget.get_edit_text()
self.original_widget.set_edit_text('')
debug('%s Entry String: %s', self.original_widget, entry)
state.set_query(entry)
views.activate(
'search_progress',
is_threaded=True,
on_join=search.new)
class UserBox(urwid.Filler):
def keypress(self, size, key):
if key != 'enter':
return super(UserBox, self).keypress(size, key)
entry = self.original_widget.get_edit_text()
self.original_widget.set_edit_text('')
debug('%s Entry String: %s', self.original_widget, entry)
state.cpanel_user = entry
state.list_of_users_emails = uapi.list_email_accounts(entry)
if not state.cpanel_user:
self.original_widget.set_caption(
'That is not a valid cPanel User\n Please Try Again\n')
else:
if not state.list_of_users_emails:
self.original_widget.set_caption(
state.cpanel_user +
' user does not have any email addresses\n')
else:
views.activate(
'search_progress',
is_threaded=True,
on_join=search.cpanel_summary)
class CustomButton(urwid.Button):
button_left = urwid.Text('[')
button_right = urwid.Text(']')
class BoxButton(urwid.WidgetWrap):
_border_char = u'─'
def __init__(self, label, on_press=None, user_data=None, enabled=True):
padding_size = 2
border = self._border_char * (len(label) + padding_size * 2)
self.cursor_position = len(border) + padding_size
self.top = u'┌' + border + u'┐\n'
self.middle = u'│ ' + label + u' │\n'
self.bottom = u'└' + border + u'┘'
self.on_press_action = on_press
self.on_press_user_data = user_data
self.enabled = enabled
# self.widget = urwid.Text([self.top, self.middle, self.bottom])
self.widget = urwid.Pile([
urwid.Text(self.top[:-1], align='center'),
urwid.Text(self.middle[:-1], align='center'),
urwid.Text(self.bottom, align='center'),
])
self.widget = urwid.AttrMap(self.widget, '', 'highlight')
# self.widget = urwid.Padding(self.widget, 'center')
# self.widget = urwid.Filler(self.widget)
# here is a lil hack: use a hidden button for evt handling
# debug('on_press: %s, user_data: %s', )
self._hidden_btn = urwid.Button(
'hidden %s' % label,
on_press,
user_data)
super(BoxButton, self).__init__(self.widget)
def selectable(self):
if self.enabled:
return True
else:
return False
def disable(self):
self.enabled = False
def enable(self):
self.enabled = True
def keypress(self, *args, **kw):
return self._hidden_btn.keypress(*args, **kw)
def mouse_event(self, *args, **kw):
return self._hidden_btn.mouse_event(*args, **kw)
class MyWidgets():
"""A collection of functions to simplify creation of
frequently used widgets """
def __init__(self):
self.div = urwid.Divider(' ', top=0, bottom=0)
self.blankFlow = self.getText('body', '', 'center')
self.blankBox = urwid.Filler(self.blankFlow)
self.searchProgress = urwid.ProgressBar(
'body',
'header',
current=0,
done=100,
satt=None)
def getDiv(self, divider=' '):
return urwid.Divider(divider, top=0, bottom=0)
def getButton(self,
thisLabel,
callingObject,
callback,
user_data=None,
buttonMap='bold',
focus_map='header'):
"""Creates and returns a FixedButton object.
Arguments:
thisLabel {[str]} -- Label of the Button
callingObject {obj} -- The name of the object that the
callback belongs to
callback {function} -- [function to be executed when button
is clicked]
Keyword Arguments:
user_data {tuple} -- A tuple or list of arguments or data
to be passed to the callback function
(default: {None})
Returns:
FixedButton -- A FixedButton object
FLOW WIDGET
"""
button = FixedButton(
str(thisLabel),
on_press=getattr(callingObject, callback),
user_data=user_data)
button._label.align = 'center'
buttonMap = urwid.AttrMap(button, buttonMap, focus_map=focus_map)
return buttonMap
def get_custom_button(self, *args, **kwargs):
b = CustomButton(*args, **kwargs)
b = urwid.AttrMap(b, '', 'highlight')
b = urwid.Padding(b, left=4, right=4)
return b
def getText(self, format, textString, alignment, **kwargs):
"""Creates a basic urwid.Text widget
Arguments:
format {str} -- Name of a format attribute specified in
DisplayFrameSettings.pallette
textString {str} -- The text string contents of text widget
alignment {str} -- Text alignment (left, right, center)
Returns:
urwid.Text -- An urwidText Widget
FLOW WIDGET
"""
return urwid.Text(
(format, textString),
align=alignment,
wrap='space',
**kwargs)
def getColRow(self, items, dividechars=s.divChars, **kwargs):
"""Creates a single row of columns
Arguments:
items {list} -- List of widgets, each item forming one column.
Items may be tuples containing width specs
Returns:
[urwid.Column] -- An urwid.Columns object
FLOW / BOX WIDGET
"""
return urwid.Columns(
items,
dividechars=dividechars,
focus_column=None,
min_width=1,
box_columns=None)
def getLineBox(self,
contents,
title,
tlcorner='┌',
tline='─',
lline='│',
trcorner='┐',
blcorner='└',
rline='│',
bline='─',
brcorner='┘',
**kwargs):
""" Creates a SimpleFocusListWalker using contents as the list,
adds a centered title, and draws a box around it. If the contents
are not a list of widgets, then set content_list to False.
The character that is used to draw the border can
be adjusted with the following keyword arguments:
tlcorner,tline,trcorner,blcorner,rline,bline,brcorner
Arguments:
contents {widget} -- an original_widget, no widget lists -
title {string} -- Title String
Keyword Arguments:
content_list -- If true, the value of contents must be a list
of widgets
If false, the value must be a single widget to be
used as
original_widget -- default{False}
Returns:
urwid.LineBox -- urwid.LineBox object
FLOW / BOX WIDGET
"""
return urwid.LineBox(
contents,
title=str(title),
title_align='center',
tlcorner=tlcorner,
tline=tline,
lline=lline,
trcorner=trcorner,
blcorner=blcorner,
rline=rline,
bline=bline,
brcorner=brcorner)
def getListBox(self, contents):
"""Creates a ListBox using a SimpleFocusListWalker, with the contents
being a list of widgets
Arguments:
contents {list} -- list of widgets
Returns:
list -- [0]: urwid.ListBox
[1]: urwid.SimpleFocusListWalker - Access this to make
changes to the list
which the SimpleFocusListWalker will follow.
BOX WIDGET
"""
walker = urwid.SimpleFocusListWalker(contents)
listBox = urwid.ListBox(walker)
return [listBox, walker]
def getCheckBox(self, label, on_state_change=None, user_data=None):
"""gets an individual CheckBox item that executes the specified function
with each change of state.
Arguments:
label {str} -- Checkbox item label
Keyword Arguments:
on_state_change {list} -- a list of the following [calling object,
function] (default: {None})
user_data {list} -- list of values to be bassed to function as
arguments (default: {None})
Returns:
object -- urwid.CheckBox object
FLOW WIDGET
"""
return urwid.CheckBox(
label,
state=False,
has_mixed=False,
on_state_change=getattr(
on_state_change[0],
on_state_change[1]),
user_data=user_data)
def centeredListLineBox(self, contents, title, listHeight, **kwargs):
filler = urwid.Filler(contents, height=listHeight)
insideCol = w.getColRow([
w.blankBox,
('weight', 2, filler),
w.blankBox])
lineBox = w.getLineBox(insideCol, title)
outsidefiller = urwid.Filler(lineBox, height=listHeight)
outsideCol = w.getColRow([
w.blankBox,
('weight', 2, outsidefiller),
w.blankBox])
return urwid.Filler(outsideCol, height=listHeight)
def getHeaderWidget(self,
title=s.df.mainTitle,
subtitle=s.df.mainSubTitle):
"""Generates a basic header with a title and optional subtitle
This is meant to be used exclusively by the Headers.new() method
Arguments:
title {str} -- Title String
Keyword Arguments:
subtitle {str} -- Optional Sub-Title (default: {''})
Returns:
object -- urwid.Pile object to be used as the header's widget
FLOW WIDGET
"""
self.title = self.getText('bold', title, 'center')
self.subtitle = self.getText('bold', subtitle, 'center')
titleMap = urwid.AttrMap(self.title, 'bold')
divMap = urwid.AttrMap(self.div, 'body')
if subtitle:
subtitleMap = urwid.AttrMap(self.subtitle, 'bold')
return urwid.Pile((titleMap, subtitleMap, divMap), focus_item=None)
else:
return urwid.Pile((titleMap, divMap), focus_item=None)
def getSearchProgress(self):
return urwid.ProgressBar(
'body',
'header',
current=0,
done=100,
satt=None)
def getFooterWidget(self, view_instance, menuItems):
"""Generates a footer column row containing a list of buttons for a
basic menu / navigation. This is meant to be used exclusively by
the Footers.new() method
Arguments:
menuItems {list} -- List of Menu Items (each item is a list)
in the following format:
[
[Label,callback function]
[Label,callback function]
]
Returns:
object -- urwid.menuItems object to be used as the header's widget
FLOW WIDGET
"""
debug('Getting Footer')
menuList = []
menuGridList = []
for item in menuItems:
if len(item) == 3:
menuGridList.append(
BoxButton(
item[0],
on_press=views.activate,
user_data=(item[1], item[2])))
else:
menuGridList.append(
BoxButton(
item[0],
on_press=views.activate,
user_data=(item[1])))
itemWidths = []
for item in menuGridList:
itemWidths.append(item.cursor_position)
itemWidths.sort()
menuColumns = urwid.Columns(
menuList,
dividechars=1,
focus_column=None,
min_width=1,
box_columns=None)
if itemWidths:
menuGrid = urwid.GridFlow(
menuGridList,
itemWidths[-1], 0, 0, 'center')
else:
menuGrid = w.div
debug(
'menuCol width: %s, menuPadding width:',
menuColumns.column_widths)
legendItems = []
for legend in s.menus.legend:
legendItems.append(w.getText('bold', legend[0], 'center'))
legendGrid = urwid.GridFlow(legendItems, 21, 0, 0, 'center')
legendGridMap = urwid.AttrMap(legendGrid, 'bold')
legendItems = []
for legend in s.menus.legend:
legendItems.append(w.getText('highlight', legend[1], 'center'))
legendItemsGrid = urwid.GridFlow(legendItems, 21, 0, 0, 'center')
legendItemsMap = urwid.AttrMap(legendItemsGrid, 'highlight')
return urwid.Pile([menuGrid, legendGridMap, legendItemsMap])
w = MyWidgets()
class BodyWidgets():
def get_body_widget(self, view_name, user_args=None, calling_view=None):
widget_getter = getattr(self, 'get_' + view_name)
body_widget = widget_getter(
user_args=user_args,
calling_view=calling_view)
return body_widget
def get_choose_logs(self, **kwargs):
"""Page opened on application start to select the
logs that will be used in searches / filters
"""
debug(' kwargs: %s', kwargs)
logCheckBoxes = [w.div]
for log in logFiles.availableLogs:
logCheckBoxes.append(
w.getCheckBox(
log,
on_state_change=[logFiles, 'update'],
user_data=[log])
)
logCheckBoxes.append(
BoxButton('Continue', on_press=views.activate, user_data='home'))
listBox = w.getListBox(logCheckBoxes)[0]
chooseLogsBox = w.centeredListLineBox(
listBox,
'Choose Your Logs to Search',
len(logCheckBoxes) + 4)
return chooseLogsBox
def get_home(self, **kwargs):
"""Page displayed as Home Page for the application
"""
debug(' kwargs : %s', kwargs)
homeText = w.getText(
'body',
'Welcome to the best Exim Search Utility ever created. ' +
'Select an option below to begin.',
'center')
if not s.lf.selectedLogs:
debug(' No logs selected, returning to choose_logs ')
return self.get_choose_logs()
else:
debug('Logs Selected: %s', s.lf.selectedLogs)
logFiles.get_date_range()
return urwid.Filler(homeText, 'middle')
def get_new_search(self, **kwargs):
"""Page opened when starting an entirely new
search. Not used for revising or filtering
previous searches
"""
debug(' kwargs : %s', kwargs)
selectQuery = urwid.Edit('Enter your query below\n', align='center')
selectFiller = QuestionBox(selectQuery, 'middle')
return w.centeredListLineBox(selectFiller, 'New Search Query', 5)
def get_search_progress(self, **kwargs):
debug(' kwargs : %s', kwargs)
searchingStatus = urwid.Pile([
w.getText(
'body',
'Processing Your Request. Please wait....',
'center'),
w.searchProgress
])
statusFiller = urwid.Filler(searchingStatus, 'middle')
return w.centeredListLineBox(statusFiller, '', 10)
def get_results_summary(self, **kwargs):
debug(' kwargs : %s', kwargs)
query = state.get_query(ACTIVE)
result_list = state.get_result_list(ACTIVE)
debug('resultOverFlow = %s', s.rl.resultOverflow)
if s.rl.resultOverflow:
if state.get_query:
summaryRows = [w.getText('header', ' for ' + query, 'center')]
else:
summaryRows = []
summaryRows.extend([
w.div,
w.getText(
'bold',
'There are too many Results \n Only showing the first ' +
str(result_list.count - len(s.lf.selectedLogs)) +
' Results \nConsider applying filters to narrow down ' +
'results ',
'center'),
w.div
])
s.rl.resultOverflow = False
else:
if query:
summaryRows = [w.getText('header', ' for ' + query, 'center')]
else:
summaryRows = []
summaryRows = [
w.div,
w.getText(
'bold',
'There are ' + str(result_list.count) + ' results',
'center'),
w.div
]
activeFilters = state.get_active_filters()
if activeFilters:
summaryRows.append(w.getText(
'bold',
'Currently Active Filters:',
'center'))
for activeFilter in activeFilters:
summaryRows.append(w.getText(
'body',
activeFilter.filter_field + ' : ' +
activeFilter.filter_criteria, 'center'))
summaryRows.append(BoxButton(
'Show Results',
on_press=views.activate,
user_data='results_list'))
summary = urwid.SimpleFocusListWalker(summaryRows)
summaryList = urwid.ListBox(summary)
return w.centeredListLineBox(
summaryList,
'Search Results',
len(summaryRows) + 6)
def get_results_list(self, **kwargs):
debug(' kwargs : %s', kwargs)
list_of_result_entries = entries.get_list_from_active_result_list()
x = 1
self.listDisplayCols = []
for entry in list_of_result_entries:
numColWidth = len(str(x)) + 6
debug('entry.msgType:%s', entry.msgType)
if len(entry.msgType) > 2:
msgType = entry.msgType[2]
else:
msgType = '-'
debug('msgType = %s', msgType)
self.listDisplayCols.append(w.getColRow(
[
(numColWidth, BoxButton(
str(x),
on_press=views.activate,
user_data=['single_entry', entry])),
(13, w.getText('body', '\n' + msgType + '\n', 'center')),
urwid.Text((
'body',
'\n' + entry.fullEntryText[2] + '\n'),
align='left'),
(3, w.getText('body', '', 'left'))
]
))
x += 1
resultListWalker = urwid.SimpleFocusListWalker(self.listDisplayCols)
resultListBox = urwid.ListBox(resultListWalker)
return resultListBox
def get_add_remove_filters(self, **kwargs):
if not state.get_result_list(ACTIVE):
footer = w.getFooterWidget(
state.get_view(ACTIVE),
Menus().add_remove_filters_no_apply)
frame.contents.__setitem__('footer', [footer, None])
else:
footer = w.getFooterWidget(
state.get_view(ACTIVE),
Menus().add_remove_filters)
frame.contents.__setitem__('footer', [footer, None])
debug(' kwargs : %s', kwargs)
list_of_active_filters = []
current_filters = state.get_active_filters()
list_of_active_filters.append(w.getColRow([
(12, urwid.AttrMap(
w.getText('header', 'Remove', 'center'),
'header')),
urwid.AttrMap(
w.getText('header', 'Filter Type', 'center'),
'header'),
urwid.AttrMap(
w.getText('header', 'Filter Criteria', 'center'),
'header')
]))
# Populate Columns with filter info
i = 1
if len(current_filters) > 0:
for filter in current_filters:
list_of_active_filters.append(
w.getColRow([
BoxButton(
'Remove',
on_press=state.remove_active_filter,
user_data=[filter, i, self]),
w.getText(
'body',
"\n"+filter.filter_field+"\n",
'center'),
w.getText(
'body',
"\n"+filter.filter_criteria+"\n",
'left')]))
i + 1
# Create Filter Walker and listbox / linebox
self.filter_walker = \
urwid.SimpleFocusListWalker(list_of_active_filters)
self.filter_list_box = urwid.BoxAdapter(
urwid.ListBox(self.filter_walker),
loop.screen.get_cols_rows()[1]-20)
filter_line_box = w.getLineBox(self.filter_list_box, 'Active Filters')
# Get filter Input
self.filter_input = urwid.Edit(align='center')
input_box = (w.getLineBox(self.filter_input, 'Add New Filter'))
debug('edit_text: %s', self.filter_input.get_edit_text())
# Get Filter Type
bgroup = []
filter_type_select = w.getColRow([
w.getLineBox(
urwid.RadioButton(
bgroup,
'Sender',
on_state_change=state.filter_input_radio,
state=False),