summaryrefslogtreecommitdiff
path: root/src/streamml/front/detector_profiles_tab_pushscreens.py
blob: fc5b731d21c32c31a123a9ac1eee0f2cb555c41d (plain)
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
from textual import on
from textual.app import ComposeResult
from textual.screen import ModalScreen
from textual.widgets import Button, Label, Pretty, DataTable, Switch
from textual.containers import Vertical, Horizontal, VerticalScroll, Container
from textual_plotext import PlotextPlot

from datetime import datetime

from ..back.detector_profiles_manager import DetectorProfilesManager
from ..back.detector_profile_HST import DetectorProfileHST

class PlotTab(Container):
    def __init__(self, profile: DetectorProfileHST, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.profile = profile
        self.classes = "plot-card" 

    def compose(self):
        yield PlotextPlot()

    def on_mount(self):
        self.set_interval(1, self.update_plot)

    def update_plot(self):
        plot_widget = self.query_one(PlotextPlot)
        plt = plot_widget.plt
        
        y = list(getattr(self.profile, "plot_data", []))

        plt.clear_figure()
        plt.theme("dark") 
        
        plt.plot(y, marker="dot", color="green")
        plt.title("Anomaly Score")
        plt.ylabel("last 30 windows")
        plt.ylim(0, 1)
        
        threshold = self.profile.params.get("threshold", 0.7)
        if threshold is not None:
            plt.horizontal_line(float(threshold), color="red")


        plot_widget.refresh()


class ShowProfilePushScreen(ModalScreen[str]):
    def __init__(self, manager, profile_name: str, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.manager = manager
        self.profile_name = profile_name
        self.profile = self.manager.get_profile(profile_name)

    def compose(self) -> ComposeResult:
        with Container(classes="modal-window large-modal"):
            yield Label(f"Profile: {self.profile_name}", classes="modal-header")
            
            with Horizontal(classes="modal-split-container"):
                
                with Vertical(classes="left-panel"):
                    yield PlotTab(self.profile)
                
                with Vertical(classes="right-panel"):
                    yield Label("Runtime Stats (Live)", classes="section-header")
                    with VerticalScroll(classes="info-box", id="stats-box"):
                        yield Pretty({}, id="runtime-stats-pretty")

                    yield Label("Configuration", classes="section-header")
                    with VerticalScroll(classes="info-box"):
                        yield Pretty(self.profile.to_dict())
                    
                    with Container(classes="modal-footer"):
                        yield Button("Close", id="cancel-button", variant="primary")

    def on_mount(self):
        self.set_interval(1.0, self.update_stats)
        self.update_stats() 

    def update_stats(self):
        if self.profile:
            stats = self.profile.get_runtime_stats()
            self.query_one("#runtime-stats-pretty", Pretty).update(stats)

    @on(Button.Pressed)
    async def on_button_pressed(self, event: Button.Pressed):
        self.dismiss(None)


class ShowLogsPushScreen(ModalScreen[str]):
    def __init__(self, manager: DetectorProfilesManager, profile_name: str, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.manager = manager
        self.profile_name = profile_name

    def compose(self) -> ComposeResult:
        with Container(classes="modal-window medium-modal"):
            yield Label(f"Anomaly Logs: {self.profile_name}", classes="modal-header")
            
            with Container(classes="table-container"):
                yield DataTable(id="logs_table", zebra_stripes=True, cursor_type="row")
            
            with Horizontal(classes="modal-footer"):
                yield Button("Clear History", id="clear-button", variant="warning")
                yield Button("Close", id="cancel-button", variant="primary")


    def on_mount(self):
        table = self.query_one("#logs_table", DataTable)
        table.add_columns("Timestamp", "Score", "Packets Rate", "Protocol Info", "Verdict")
        
        logs = self.manager.get_profile_logs(self.profile_name)
        
        if not logs:
            return

        sorted_logs = sorted(logs, key=lambda x: x.get("ts", 0), reverse=True)

        for log in sorted_logs:
            dt = datetime.fromtimestamp(log.get("ts", 0)).strftime("%Y-%m-%d %H:%M:%S")
            
            score = f"{log.get('score', 0):.4f}"
            rate = f"{log.get('pkt_rate', 0):.1f}"
            proto = str(log.get("proto_info", "-"))
            verdict = "ANOMALY" 
            
            table.add_row(dt, score, rate, proto, verdict)

    @on(Button.Pressed)
    async def on_button_pressed(self, event: Button.Pressed) -> None:
        if event.button.id == "clear-button":
            profile = self.manager.get_profile(self.profile_name)
            if profile:
                profile.clear_logs()
                self.query_one("#logs_table", DataTable).clear()
        else:
            self.dismiss(None)

class SetDetectorNotificationPushScreen(ModalScreen[str]):
    def __init__(self, manager, profile_name: str, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.manager = manager
        self.profile_name = profile_name
        self.profile = self.manager.get_profile(profile_name)

    def compose(self) -> ComposeResult:
        current_val = getattr(self.profile, 'notify_enabled', False)
        
        with Container(classes="modal-window small-modal"):
            yield Label(f"Notification: {self.profile_name}", classes="modal-header")
            
            with Vertical(classes="section-card"):
                yield Label("Enable notification (Discord)")
                yield Switch(value=current_val, id="switch-anomaly")

            with Horizontal(classes="modal-footer"):
                yield Button("Close", id="close-button", variant="primary")

    @on(Switch.Changed)
    def on_switch_changed(self, event: Switch.Changed):
        if event.switch.id == "switch-anomaly":
            self.profile.notify_enabled = event.value
            self.manager.try_save_profiles(notify=False)

    @on(Button.Pressed)
    async def on_button_pressed(self, event: Button.Pressed):
        self.dismiss(None)

class ConfirmDeletePushScreen(ModalScreen[str]):
    def __init__(self, manager: DetectorProfilesManager, profile_name:str, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.manager = manager
        self.profile_name = profile_name

    def compose(self) -> ComposeResult:
        with Container(classes="modal-window small-modal"):
            yield Label("Are you sure?",classes="modal-header")
            with Horizontal(classes="modal-footer"):
                yield Button("Delete", id="confirm-button", variant="error")
                yield Button("Cancel", id="cancel-button", variant="default")

    @on(Button.Pressed)
    async def on_button_pressed(self, event: Button.Pressed):
        if event.button.id == "confirm-button":
            self.manager.delete_profile(self.profile_name)
            self.dismiss(None)
        else:
            self.dismiss(None)