|
| 1 | +"""connect or disconnect from a NetworkManager VPN profiles (via nmcli)""" |
| 2 | + |
| 3 | +from albert import * |
| 4 | +from collections import namedtuple |
| 5 | +import subprocess |
| 6 | + |
| 7 | +md_iid = "0.5" |
| 8 | +md_version = "1.1" |
| 9 | +md_id = "vpn" |
| 10 | +md_name = "VPN" |
| 11 | +md_description = "Manage VPN connection" |
| 12 | +md_license = "MIT" |
| 13 | +md_url = "https://github.com/albertlauncher/python" |
| 14 | +md_maintainers = ["@Bierchermuesli"] |
| 15 | +md_credits = ["@janeklb"] |
| 16 | +md_bin_dependencies = ["nmcli"] |
| 17 | + |
| 18 | + |
| 19 | + |
| 20 | +class Plugin(QueryHandler): |
| 21 | + |
| 22 | + iconPath = ['xdg:network-wired'] |
| 23 | + |
| 24 | + VPNConnection = namedtuple('VPNConnection', ['name', 'connected']) |
| 25 | + |
| 26 | + def id(self): |
| 27 | + return md_id |
| 28 | + |
| 29 | + def name(self): |
| 30 | + return md_name |
| 31 | + |
| 32 | + def description(self): |
| 33 | + return md_description |
| 34 | + |
| 35 | + def getVPNConnections(self): |
| 36 | + consStr = subprocess.check_output( |
| 37 | + 'nmcli -t connection show', |
| 38 | + shell=True, |
| 39 | + encoding='UTF-8' |
| 40 | + ) |
| 41 | + for conStr in consStr.splitlines(): |
| 42 | + con = conStr.split(':') |
| 43 | + if con[2] == 'vpn': |
| 44 | + yield self.VPNConnection(name=con[0], connected=con[3] != '') |
| 45 | + |
| 46 | + |
| 47 | + def buildItem(self,con): |
| 48 | + name = con.name |
| 49 | + command = 'down' if con.connected else 'up' |
| 50 | + text = f'Connect to {name}' if command == 'up' else f'Disconnect from {name}' |
| 51 | + commandline = ['nmcli', 'connection', command, 'id', name] |
| 52 | + return Item( |
| 53 | + id=f'vpn-{command}-{name}', |
| 54 | + text=name, |
| 55 | + subtext=text, |
| 56 | + icon=self.iconPath, |
| 57 | + completion=name, |
| 58 | + actions=[ Action("run",text=text, callable=lambda: runDetachedProcess(commandline)) ] |
| 59 | + ) |
| 60 | + |
| 61 | + |
| 62 | + def handleQuery(self,query): |
| 63 | + if query.isValid: |
| 64 | + connections = self.getVPNConnections() |
| 65 | + if query.string: |
| 66 | + connections = [ con for con in connections if query.string.lower() in con.name.lower() ] |
| 67 | + query.add([ self.buildItem(con) for con in connections ]) |
0 commit comments