-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathknockerQuickSettings.js
More file actions
415 lines (345 loc) · 15.7 KB
/
Copy pathknockerQuickSettings.js
File metadata and controls
415 lines (345 loc) · 15.7 KB
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
/* knockerQuickSettings.js
*
* Quick Settings toggle for Knocker service
*/
import GObject from 'gi://GObject';
import GLib from 'gi://GLib';
import * as Main from 'resource:///org/gnome/shell/ui/main.js';
import * as PopupMenu from 'resource:///org/gnome/shell/ui/popupMenu.js';
import * as QuickSettings from 'resource:///org/gnome/shell/ui/quickSettings.js';
import * as MessageTray from 'resource:///org/gnome/shell/ui/messageTray.js';
import {KnockerEvent} from './knockerMonitor.js';
export const KnockerToggle = GObject.registerClass(
class KnockerToggle extends QuickSettings.QuickMenuToggle {
_init(extensionObject, knockerService, knockerMonitor) {
super._init({
title: 'Knocker',
subtitle: 'Service Inactive',
iconName: 'network-server-symbolic',
toggleMode: true,
});
this._extensionObject = extensionObject;
this._knockerService = knockerService;
this._knockerMonitor = knockerMonitor;
this._settings = extensionObject.getSettings();
this._updateTimeoutId = null;
this._updateStateTimeoutId = null;
this._reenableButtonTimeoutId = null;
this._monitorListeners = [];
// Set up menu
this._setupMenu();
// Set up event listeners
this._setupEventListeners();
// Initial state check
this._updateServiceState();
// Handle toggle changes
this.connect('clicked', () => this._onToggleClicked());
}
_setupMenu() {
// Add header
this.menu.setHeader('network-server-symbolic', 'Knocker', 'Port Knocking Service');
// IP and expiry section
this._whitelistSection = new PopupMenu.PopupMenuSection();
this._ipLabel = new PopupMenu.PopupMenuItem('No active whitelist', {
reactive: false,
can_focus: false,
});
this._whitelistSection.addMenuItem(this._ipLabel);
this.menu.addMenuItem(this._whitelistSection);
// Next knock section
this._nextKnockLabel = new PopupMenu.PopupMenuItem('No scheduled knock', {
reactive: false,
can_focus: false,
});
this.menu.addMenuItem(this._nextKnockLabel);
this.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());
// Manual knock button
const knockButton = this.menu.addAction('Knock Now', async () => {
await this._triggerKnock();
});
this._knockButton = knockButton;
this.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());
// Settings button
const settingsItem = this.menu.addAction('Settings', () => {
this._extensionObject.openPreferences();
});
settingsItem.visible = Main.sessionMode.allowSettings;
this.menu._settingsActions[this._extensionObject.uuid] = settingsItem;
}
_addMonitorListener(event, handler) {
this._knockerMonitor.on(event, handler);
this._monitorListeners.push([event, handler]);
}
_setupEventListeners() {
// Monitor service state changes
const serviceStateHandler = () => {
this._updateServiceState();
};
this._addMonitorListener(KnockerEvent.SERVICE_STATE, serviceStateHandler);
// Monitor status snapshots
const statusSnapshotHandler = () => {
this._updateUI();
};
this._addMonitorListener(KnockerEvent.STATUS_SNAPSHOT, statusSnapshotHandler);
// Monitor whitelist updates
const whitelistAppliedHandler = data => {
this._updateUI();
if (this._settings.get_boolean('notification-on-knock')) {
const expiryTime = this._formatTimestamp(data.expiresUnix);
this._showNotification('Knocker', `Whitelisted ${data.whitelistIp} until ${expiryTime}`);
}
};
this._addMonitorListener(KnockerEvent.WHITELIST_APPLIED, whitelistAppliedHandler);
const whitelistExpiredHandler = () => {
this._updateUI();
};
this._addMonitorListener(KnockerEvent.WHITELIST_EXPIRED, whitelistExpiredHandler);
// Monitor next knock updates
const nextKnockUpdatedHandler = () => {
this._updateUI();
};
this._addMonitorListener(KnockerEvent.NEXT_KNOCK_UPDATED, nextKnockUpdatedHandler);
// Monitor errors
const errorHandler = data => {
if (this._settings.get_boolean('notification-on-error')) {
this._showNotification('Knocker Error', data.errorMsg || data.message, MessageTray.Urgency.HIGH);
}
};
this._addMonitorListener(KnockerEvent.ERROR, errorHandler);
// Set up periodic UI updates for countdown timers
this._updateTimeoutId = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 10, () => {
this._updateUI();
return GLib.SOURCE_CONTINUE;
});
}
async _updateServiceState() {
const isActive = await this._knockerService.isServiceActive();
// Update toggle state without triggering the handler
this.set({checked: isActive});
// Update subtitle
if (isActive) {
this.subtitle = 'Service Active';
} else {
this.subtitle = 'Service Inactive';
}
// Update UI with current state
this._updateUI();
}
_updateUI() {
const state = this._knockerMonitor.getState();
// Update whitelist info
if (state.whitelistIp && state.expiresUnix) {
const now = Math.floor(Date.now() / 1000);
const remaining = state.expiresUnix - now;
if (remaining > 0) {
const remainingStr = this._formatDuration(remaining);
this._ipLabel.label.text = `${state.whitelistIp} (expires in ${remainingStr})`;
} else {
this._ipLabel.label.text = `${state.whitelistIp} (expired)`;
}
} else {
this._ipLabel.label.text = 'No active whitelist';
}
// Update next knock info
if (state.nextAtUnix && state.nextAtUnix > 0) {
const nextTime = this._formatTimestamp(state.nextAtUnix);
const now = Math.floor(Date.now() / 1000);
const timeUntil = state.nextAtUnix - now;
const sourceInfo = state.cadenceSource ? ` (${this._formatCadenceSource(state.cadenceSource)})` : '';
if (timeUntil > 0) {
const untilStr = this._formatDuration(timeUntil);
this._nextKnockLabel.label.text = `Next knock in ${untilStr}${sourceInfo}`;
} else {
this._nextKnockLabel.label.text = `Next knock: ${nextTime}${sourceInfo}`;
}
} else {
this._nextKnockLabel.label.text = 'No scheduled knock';
}
}
async _onToggleClicked() {
const shouldBeActive = this.checked;
if (shouldBeActive) {
const success = await this._knockerService.startService();
if (!success) {
// Revert toggle if start failed
this.set({checked: false});
this._showNotification('Knocker', 'Failed to start knocker.service', MessageTray.Urgency.HIGH);
}
} else {
const success = await this._knockerService.stopService();
if (!success) {
// Revert toggle if stop failed
this.set({checked: true});
this._showNotification('Knocker', 'Failed to stop knocker.service', MessageTray.Urgency.HIGH);
}
}
// Update state after a short delay
// Remove any existing timeout before creating a new one
if (this._updateStateTimeoutId) {
GLib.source_remove(this._updateStateTimeoutId);
this._updateStateTimeoutId = null;
}
this._updateStateTimeoutId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 500, () => {
this._updateStateTimeoutId = null;
this._updateServiceState();
return GLib.SOURCE_REMOVE;
});
}
async _triggerKnock() {
this._knockButton.sensitive = false;
try {
const success = await this._knockerService.triggerKnock();
if (success) {
this._showNotification('Knocker', 'Knock triggered successfully');
} else {
this._showNotification('Knocker', 'Failed to trigger knock', MessageTray.Urgency.HIGH);
}
} finally {
// Re-enable button after a short delay
// Remove any existing timeout before creating a new one
if (this._reenableButtonTimeoutId) {
GLib.source_remove(this._reenableButtonTimeoutId);
this._reenableButtonTimeoutId = null;
}
this._reenableButtonTimeoutId = GLib.timeout_add(GLib.PRIORITY_DEFAULT, 2000, () => {
this._reenableButtonTimeoutId = null;
this._knockButton.sensitive = true;
return GLib.SOURCE_REMOVE;
});
}
}
_showNotification(title, message, urgency = MessageTray.Urgency.NORMAL) {
// Create notification source if not exists
if (!this._notificationSource) {
this._notificationSource = new MessageTray.Source('Knocker', 'network-server-symbolic');
this._notificationSource.connect('destroy', () => {
this._notificationSource = null;
});
Main.messageTray.add(this._notificationSource);
}
// Create and show notification
const notification = new MessageTray.Notification(this._notificationSource, title, message);
notification.setUrgency(urgency);
notification.setTransient(true);
this._notificationSource.showNotification(notification);
}
_formatTimestamp(unixTimestamp) {
if (!unixTimestamp) {
return 'N/A';
}
const date = new Date(unixTimestamp * 1000);
return date.toLocaleString();
}
_formatDuration(seconds) {
if (seconds < 60) {
return `${seconds}s`;
} else if (seconds < 3600) {
const mins = Math.floor(seconds / 60);
return `${mins}m`;
} else if (seconds < 86400) {
const hours = Math.floor(seconds / 3600);
const mins = Math.floor((seconds % 3600) / 60);
return `${hours}h ${mins}m`;
} else {
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
return `${days}d ${hours}h`;
}
}
_formatCadenceSource(cadenceSource) {
if (!cadenceSource) {
return '';
}
const sourceMap = {
'ttl': 'based on TTL',
'ttl_response': 'based on TTL response',
'check_interval': 'based on interval',
};
return sourceMap[cadenceSource] || cadenceSource;
}
destroy() {
if (this._updateTimeoutId) {
GLib.source_remove(this._updateTimeoutId);
this._updateTimeoutId = null;
}
if (this._updateStateTimeoutId) {
GLib.source_remove(this._updateStateTimeoutId);
this._updateStateTimeoutId = null;
}
if (this._reenableButtonTimeoutId) {
GLib.source_remove(this._reenableButtonTimeoutId);
this._reenableButtonTimeoutId = null;
}
for (const [event, handler] of this._monitorListeners) {
this._knockerMonitor.off(event, handler);
}
this._monitorListeners = [];
// Clean up notification source
if (this._notificationSource) {
this._notificationSource.destroy();
this._notificationSource = null;
}
super.destroy();
}
});
export const KnockerIndicator = GObject.registerClass(
class KnockerIndicator extends QuickSettings.SystemIndicator {
_init(extensionObject, knockerService, knockerMonitor) {
super._init();
this._extensionObject = extensionObject;
this._settings = extensionObject.getSettings();
this._knockerService = knockerService;
this._knockerMonitor = knockerMonitor;
// Create an icon for the indicator
this._indicator = this._addIndicator();
this._indicator.icon_name = 'network-server-symbolic';
// Initially hide the indicator (will be shown when service is active)
this._indicator.visible = false;
// Monitor service state to update indicator visibility
this._setupIndicatorVisibility();
// Add the toggle
this._toggle = new KnockerToggle(extensionObject, knockerService, knockerMonitor);
this.quickSettingsItems.push(this._toggle);
}
_setupIndicatorVisibility() {
// Update visibility based on service state AND settings
const updateVisibility = async () => {
const showIndicatorSetting = this._settings.get_boolean('show-indicator');
const isServiceActive = await this._knockerService.isServiceActive();
// Only show indicator if both setting is enabled AND service is active
this._indicator.visible = showIndicatorSetting && isServiceActive;
};
// Initial update
updateVisibility();
// Watch for settings changes
this._settingsChangedId = this._settings.connect('changed::show-indicator', () => {
updateVisibility();
});
// Watch for service state changes
this._serviceStateHandler = () => {
updateVisibility();
};
this._knockerMonitor.on(KnockerEvent.SERVICE_STATE, this._serviceStateHandler);
// Periodically check service state (in case we miss events)
this._visibilityCheckId = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, 10, () => {
updateVisibility();
return GLib.SOURCE_CONTINUE;
});
}
destroy() {
if (this._settingsChangedId) {
this._settings.disconnect(this._settingsChangedId);
this._settingsChangedId = null;
}
if (this._serviceStateHandler) {
this._knockerMonitor.off(KnockerEvent.SERVICE_STATE, this._serviceStateHandler);
this._serviceStateHandler = null;
}
if (this._visibilityCheckId) {
GLib.source_remove(this._visibilityCheckId);
this._visibilityCheckId = null;
}
this.quickSettingsItems.forEach(item => item.destroy());
super.destroy();
}
});