-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfreepn-gtk3-indicator
executable file
·263 lines (213 loc) · 8.13 KB
/
freepn-gtk3-indicator
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
#!/usr/bin/env python3
import os
import json
import signal
import subprocess
import time
import urllib.request
from pathlib import Path
from collections import deque
from threading import Thread
import xmltodict
import gi
gi.require_version('Gtk', '3.0') # noqa
gi.require_version('AppIndicator3', '0.1') # noqa
gi.require_version('Notify', '0.7') # noqa
from gi.repository import Gtk, AppIndicator3, Notify
APP_VERSION = '0.0.8'
APPINDICATOR_ID = 'fpndindicator'
FPND_UPGRADE_MSG = '''
Your FreePN network daemon is out-of-date and no longer
compatible with the FreePN network infrastructure. Please
update your system packages as soon as possible.
'''
state_file = Path(os.path.join('/run/fpnd', 'fpnd.state'))
def get_state_icon(state):
"""
Look up the state msg and return the icon name.
"""
install_path = '/usr/share/icons/hicolor/scalable/status'
icon_name = 'network-freepn-connected-symbolic.svg'
fallback_dict = {
'CONNECTED': 'network-vpn-symbolic',
'WAITING': 'network-vpn-no-route-symbolic',
'CONFIG': 'network-vpn-acquiring-symbolic',
'ERROR': 'network-error-symbolic',
'STARTING': 'network-vpn-acquiring-symbolic',
'UPGRADE': 'network-offline-symbolic',
'NONE': 'network-offline-symbolic'
}
freepn_dict = {
'CONNECTED': 'network-freepn-connected-key2-symbolic',
'WAITING': 'network-freepn-no-route-symbolic',
'CONFIG': 'network-freepn-acquiring-symbolic',
'ERROR': 'network-freepn-error-symbolic',
'STARTING': 'network-freepn-acquiring-symbolic',
'UPGRADE': 'network-freepn-offline-symbolic',
'NONE': 'network-freepn-offline-symbolic'
}
state_dict = freepn_dict
connected_icon = Path(install_path).joinpath(icon_name)
if not connected_icon.exists():
state_dict = fallback_dict
return state_dict.get(state, state_dict['NONE'])
def get_status(filename, n=1):
"""
Return the last n lines of the status file in a deque.
"""
try:
with open(filename) as f:
return deque(f, n)
except Exception as exc:
print('State file error: {}'.format(exc))
def fetch_geoip():
"""
Fetch location info from ubuntu.com geoip server and transform the
xml payload to json.
"""
request = urllib.request.Request('https://geoip.ubuntu.com/lookup')
response = urllib.request.urlopen(request)
payload = xmltodict.parse(response.read())
return json.dumps(payload, indent=4, separators=(',', ': '))
def run_service_cmd(action='is-active'):
"""
Run systemctl command on fpnd service.
:param action: one of <start|stop>
:return: cmd result or empty str
"""
result = ''
actions = ['start', 'stop', 'status', 'is-active']
svc_list = ['pkexec', 'systemctl']
act_list = [action, 'fpnd.service']
if Path('/sbin/openrc').is_file():
if action == 'is-active':
action = 'status'
svc_list = ['pkexec', '/sbin/openrc', '-s']
act_list = ['fpnd', action]
cmd = svc_list + act_list
if action in actions:
print('Running {}'.format(cmd))
else:
msg = 'Invalid action: {}'.format(action)
print(msg)
return result
try:
proc = subprocess.Popen(cmd,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
shell=False)
out, err = proc.communicate()
if err:
print('run_service_cmd err result: {}'.format(err.decode().strip()))
result = err.decode()
else:
result = out.decode()
print('{} result: {}'.format(action, out.decode().strip()))
except Exception as exc:
print('run_service_cmd exception: {}'.format(exc))
return result
class Indicator():
def __init__(self):
self.app_id = APPINDICATOR_ID
icon_name = get_state_icon('NONE')
self.indicator = AppIndicator3.Indicator.new(
self.app_id,
icon_name,
AppIndicator3.IndicatorCategory.APPLICATION_STATUS)
self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
# self.indicator.set_attention_icon_full('indicator-messages-new',
# 'State update')
self.indicator.set_menu(self.create_menu())
# setup the state updater thread
self.update = Thread(target=self.check_for_new_state)
self.update.setDaemon(True)
self.update.start()
def check_for_new_state(self):
"""
Check for new state msg and update icon if new.
"""
old_state = 'NONE'
new_state = 'NONE'
guide = '999999999'
while True:
time.sleep(1)
if state_file.exists():
msg_queue = get_status(str(state_file))
new_state = msg_queue.pop().strip()
# if there is a change in state, update the icon
if old_state != new_state:
if new_state == 'UPGRADE':
Notify.Notification.new("Version Error!!", FPND_UPGRADE_MSG, None).show()
self.indicator.set_icon_full(get_state_icon(new_state), new_state)
# Notify.Notification.new(new_state, None, None).show()
# note the second label arg should be the longest possible label str
self.indicator.set_label(new_state.format().center(9), guide)
old_state = new_state
def create_menu(self):
menu = Gtk.Menu()
item_start = Gtk.MenuItem(label='Start')
item_start.connect('activate', self.startd)
menu.append(item_start)
item_stop = Gtk.MenuItem(label='Stop')
item_stop.connect('activate', self.stopd)
menu.append(item_stop)
item_status = Gtk.MenuItem(label='Status')
item_status.connect('activate', self.statusd)
menu.append(item_status)
item_geoip = Gtk.MenuItem(label='Geoip')
item_geoip.connect('activate', self.geoip)
menu.append(item_geoip)
item_separator = Gtk.SeparatorMenuItem()
menu.append(item_separator)
item_about = Gtk.MenuItem(label='About FreePN')
item_about.connect('activate', self.about)
menu.append(item_about)
item_quit = Gtk.MenuItem(label='Quit')
item_quit.connect('activate', self.stop)
menu.append(item_quit)
menu.show_all()
return menu
def about(self, source):
dlg = Gtk.AboutDialog()
dlg.set_name('About...')
dlg.set_program_name('FreePN GUI')
dlg.set_version(APP_VERSION)
dlg.set_copyright('© 2019-2020 Allieae, Inc')
dlg.set_license_type(Gtk.License.AGPL_3_0)
dlg.set_logo_icon_name('freepn')
dlg.set_website('https://www.freepn.org/')
dlg.set_website_label('www.freepn.org')
dlg.set_comments("""
FreePN network privacy control and status tool.
""")
dlg.set_authors(['Stephen L Arnold <nerdboy@gentoo.org>'])
dlg.set_artists(['Marianne Cruzat <marianne.y.cruzat@gmail.com>'])
dlg.run()
dlg.hide()
def stop(self, source):
Notify.uninit()
Gtk.main_quit()
def geoip(self, source):
Notify.Notification.new("Geoip", fetch_geoip(), None).show()
def startd(self, source):
svc_msg = run_service_cmd(action='start')
if not svc_msg:
svc_msg = 'Starting...'
Notify.Notification.new("Daemon status", svc_msg, None).show()
def statusd(self, source):
svc_msg = run_service_cmd()
Notify.Notification.new("Daemon status", svc_msg, None).show()
def stopd(self, source):
svc_msg = run_service_cmd(action='stop')
if not svc_msg:
svc_msg = 'Stopping...'
self.indicator.set_icon_full(get_state_icon('NONE'), 'NONE')
self.indicator.set_label('NONE'.format().center(9), '99999')
Notify.Notification.new("Daemon status", svc_msg, None).show()
def main():
Indicator()
Notify.init(APPINDICATOR_ID)
Gtk.main()
if __name__ == "__main__":
signal.signal(signal.SIGINT, signal.SIG_DFL)
main()