-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-tray.py
More file actions
executable file
·246 lines (209 loc) · 8.64 KB
/
service-tray.py
File metadata and controls
executable file
·246 lines (209 loc) · 8.64 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
#!/usr/bin/python3
import gi, subprocess, os
gi.require_version('Gtk', '3.0')
gi.require_version('AppIndicator3', '0.1')
from gi.repository import Gtk, GLib, AppIndicator3
# ----------------------------
# CONFIGURATION
# ----------------------------
ICON_DIR = os.path.join(os.path.dirname(__file__), "icons")
ICON_GREEN = os.path.join(ICON_DIR, "green.png")
ICON_RED = os.path.join(ICON_DIR, "red.png")
UPDATE_INTERVAL = 5 # seconds
CONFIG_FILE = os.path.join(os.path.dirname(__file__), "services.conf")
# ----------------------------
# HELPER FUNCTIONS
# ----------------------------
def read_services_config():
"""Read services.conf and return a dict of DisplayName: (ServiceName, Port)"""
services = {}
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, 'r') as f:
for line in f:
line = line.strip()
if line.startswith("#") or not line:
continue
if "=" in line:
# Format: DisplayName=ServiceName:Port
name, service_and_port = line.split("=", 1)
service_and_port = service_and_port.strip()
# Check if port is specified
if ":" in service_and_port:
service_name, port = service_and_port.split(":", 1)
services[name.strip()] = (service_name.strip(), port.strip())
else:
# Default port if not specified
services[name.strip()] = (service_and_port, "N/A")
return services
def get_service_state(service_name):
"""Return 'active' or 'inactive'"""
try:
output = subprocess.check_output(
["systemctl", "is-active", service_name],
stderr=subprocess.STDOUT
).decode().strip()
return output
except subprocess.CalledProcessError:
return "inactive"
def is_service_enabled(service_name):
"""Check if service is enabled to start automatically"""
try:
result = subprocess.run(
["systemctl", "is-enabled", service_name],
capture_output=True,
text=True
)
return result.returncode == 0 and "enabled" in result.stdout
except:
return False
def toggle_service(service_name):
"""Toggle the service on/off"""
state = get_service_state(service_name)
action = "stop" if state == "active" else "start"
subprocess.run(["sudo", "systemctl", action, service_name])
def toggle_service_enablement(service_name):
"""Toggle service enable/disable state"""
try:
current_state = is_service_enabled(service_name)
command = "enable" if not current_state else "disable"
subprocess.run(["sudo", "systemctl", command, service_name], check=True)
return True
except Exception as e:
print(f"Failed to toggle service enablement: {e}")
return False
def update_sudoers():
"""Update /etc/sudoers.d/service-tray with NOPASSWD for listed services"""
try:
sudoers_file = "/etc/sudoers.d/service-tray"
services = read_services_config()
service_names = [service[0] for service in services.values()] # Extract just the service names
if not service_names:
return
rules = f"{os.getenv('USER')} ALL=(ALL) NOPASSWD: " + \
", ".join([f"/bin/systemctl {cmd} {srv}" for srv in service_names for cmd in ["start","stop","restart","status","enable","disable"]])
subprocess.run(["sudo", "tee", sudoers_file], input=rules.encode(), check=True)
subprocess.run(["sudo", "chmod", "440", sudoers_file], check=True)
except Exception as e:
print("Failed to update sudoers:", e)
# ----------------------------
# REFRESH FUNCTION
# ----------------------------
def refresh_services(menu_item=None):
build_menu() # rebuild menu with new services
return False # Return False to remove the timeout
# ----------------------------
# MENU BUILD
# ----------------------------
def build_menu():
global menu, menu_items
menu_items.clear()
# Remove all existing items
for child in menu.get_children():
menu.remove(child)
# Add dynamic service items
services = read_services_config()
for name, (service, port) in services.items():
# Create main service menu item with port information
state = get_service_state(service)
main_label = f"{state.upper()} - {name} - Port: {port}"
# Create the main menu item
main_item = Gtk.MenuItem(label=main_label)
# Create submenu for hover functionality
submenu = Gtk.Menu()
# Start/Stop submenu item
start_stop_label = "Stop" if state == "active" else "Start"
start_stop_item = Gtk.MenuItem(label=start_stop_label)
start_stop_item.connect("activate", lambda w, s=service: toggle_service(s))
submenu.append(start_stop_item)
# Enable/Disable submenu item
enabled_state = is_service_enabled(service)
enable_disable_label = "Disable" if enabled_state else "Enable"
enable_disable_item = Gtk.MenuItem(label=enable_disable_label)
enable_disable_item.connect("activate", lambda w, s=service: toggle_service_enablement_and_refresh(s))
submenu.append(enable_disable_item)
# Show all submenu items
start_stop_item.show()
enable_disable_item.show()
# Set submenu for main item
main_item.set_submenu(submenu)
# Connect left-click to toggle service
main_item.connect("button-press-event", on_service_click, service)
main_item.show()
menu.append(main_item)
menu_items.append(main_item)
# Separator
separator = Gtk.SeparatorMenuItem()
separator.show()
menu.append(separator)
# Refresh Services menu item
refresh_item = Gtk.MenuItem(label="Refresh Services")
refresh_item.connect("activate", refresh_services)
refresh_item.show()
menu.append(refresh_item)
# Quit menu item
quit_item = Gtk.MenuItem(label="Quit")
quit_item.connect("activate", lambda w: Gtk.main_quit())
quit_item.show()
menu.append(quit_item)
def on_service_click(widget, event, service_name):
"""Handle service click events - left click toggles, right click shows submenu"""
if event.button == 1: # Left click
toggle_service(service_name)
# Refresh after a short delay to show updated status
GLib.timeout_add(1000, refresh_services)
# Right click (button == 3) automatically shows the submenu in GTK
def toggle_service_enablement_and_refresh(service_name):
"""Toggle service enablement and refresh the menu"""
if toggle_service_enablement(service_name):
# Refresh after a short delay to show updated status
GLib.timeout_add(1000, refresh_services)
# ----------------------------
# UPDATE ICON FUNCTION
# ----------------------------
def update_icon():
any_active = False
services = read_services_config()
for item, (name, (service, port)) in zip(menu_items, services.items()):
state = get_service_state(service)
item.set_label(f"{state.upper()} - {name} - Port: {port}")
if state == "active":
any_active = True
# Update submenu items
submenu = item.get_submenu()
if submenu:
# Update Start/Stop item
start_stop_item = submenu.get_children()[0]
start_stop_label = "Stop" if state == "active" else "Start"
start_stop_item.set_label(start_stop_label)
# Update Enable/Disable item
enable_disable_item = submenu.get_children()[1]
enabled_state = is_service_enabled(service)
enable_disable_label = "Disable" if enabled_state else "Enable"
enable_disable_item.set_label(enable_disable_label)
# Update icon based on service states
if any_active:
indicator.set_icon(ICON_GREEN)
else:
indicator.set_icon(ICON_RED)
return True # Keep GLib timeout running
# ----------------------------
# INIT
# ----------------------------
menu_items = []
indicator = AppIndicator3.Indicator.new(
"service-tray",
ICON_RED,
AppIndicator3.IndicatorCategory.APPLICATION_STATUS
)
indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
# Create a compact menu
menu = Gtk.Menu()
menu.set_reserve_toggle_size(False) # Remove arrow indicator
build_menu()
indicator.set_menu(menu)
# Update sudoers once at startup
update_sudoers()
# Start periodic updates
GLib.timeout_add_seconds(UPDATE_INTERVAL, update_icon)
update_icon() # initial update
Gtk.main()