networks: Refactor for simplicity and brevity

- Make connection adding/editing forms inherit from base.

- Make the forms responsible for extracting cleaned data.

- Use dictionaries for passing around settings values while
  adding/editing connections.
This commit is contained in:
Sunil Mohan Adapa 2015-12-09 17:04:28 +05:30
parent 8438bd3f31
commit 42d0198a2e
3 changed files with 163 additions and 301 deletions

View File

@ -24,18 +24,6 @@ from plinth.utils import import_from_gi
nm = import_from_gi('NM', '1.0') nm = import_from_gi('NM', '1.0')
def _get_interface_choices(device_type):
"""Return a list of choices for a given device type."""
interfaces = network.get_interface_list(device_type)
choices = [('', _('-- select --'))]
for interface, mac in interfaces.items():
display_string = '{interface} ({mac})'.format(interface=interface,
mac=mac)
choices.append((interface, display_string))
return choices
class ConnectionTypeSelectForm(forms.Form): class ConnectionTypeSelectForm(forms.Form):
"""Form to select type for new connection.""" """Form to select type for new connection."""
connection_type = forms.ChoiceField( connection_type = forms.ChoiceField(
@ -44,8 +32,8 @@ class ConnectionTypeSelectForm(forms.Form):
for key, value in network.CONNECTION_TYPE_NAMES.items()]) for key, value in network.CONNECTION_TYPE_NAMES.items()])
class AddEthernetForm(forms.Form): class ConnectionForm(forms.Form):
"""Form to create a new ethernet connection.""" """Base form to create/edit a connection."""
name = forms.CharField(label=_('Connection Name')) name = forms.CharField(label=_('Connection Name'))
interface = forms.ChoiceField( interface = forms.ChoiceField(
label=_('Physical Interface'), label=_('Physical Interface'),
@ -94,53 +82,95 @@ available over this interfaces. Select Internal only for trusted networks.'),
validators=[validators.validate_ipv4_address], validators=[validators.validate_ipv4_address],
required=False) required=False)
@staticmethod
def _get_interface_choices(device_type):
"""Return a list of choices for a given device type."""
interfaces = network.get_interface_list(device_type)
choices = [('', _('-- select --'))]
for interface, mac in interfaces.items():
display_string = '{interface} ({mac})'.format(interface=interface,
mac=mac)
choices.append((interface, display_string))
return choices
def get_settings(self):
"""Return settings dict from cleaned data."""
settings = {}
settings['common'] = {
'name': self.cleaned_data['name'],
'interface': self.cleaned_data['interface'],
'zone': self.cleaned_data['zone'],
}
settings['ipv4'] = self.get_ipv4_settings()
return settings
def get_ipv4_settings(self):
"""Return IPv4 dict from cleaned data."""
ipv4 = {
'method': self.cleaned_data['ipv4_method'],
'address': self.cleaned_data['ipv4_address'],
'netmask': self.cleaned_data['ipv4_netmask'],
'gateway': self.cleaned_data['ipv4_gateway'],
'dns': self.cleaned_data['ipv4_dns'],
'second_dns': self.cleaned_data['ipv4_second_dns'],
}
return ipv4
class EthernetForm(ConnectionForm):
"""Form to create/edit a ethernet connection."""
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
"""Initialize the form, populate interface choices.""" """Initialize the form, populate interface choices."""
super(AddEthernetForm, self).__init__(*args, **kwargs) super(EthernetForm, self).__init__(*args, **kwargs)
choices = _get_interface_choices(nm.DeviceType.ETHERNET) choices = self._get_interface_choices(nm.DeviceType.ETHERNET)
self.fields['interface'].choices = choices self.fields['interface'].choices = choices
def get_settings(self):
"""Return settings dict from cleaned data."""
settings = super().get_settings()
settings['common']['type'] = '802-3-ethernet'
return settings
class AddPPPoEForm(forms.Form):
class PPPoEForm(EthernetForm):
"""Form to create a new PPPoE connection.""" """Form to create a new PPPoE connection."""
name = forms.CharField(label=_('Connection Name')) ipv4_method = None
interface = forms.ChoiceField( ipv4_address = None
label=_('Physical Interface'), ipv4_netmask = None
choices=(), ipv4_gateway = None
help_text=_('The network device that this connection should be bound ' ipv4_dns = None
'to.')) ipv4_second_dns = None
zone = forms.ChoiceField(
label=_('Firewall Zone'),
help_text=_('The firewall zone will control which services are '
'available over this interfaces. Select Internal only '
'for trusted networks.'),
choices=[('external', 'External'), ('internal', 'Internal')])
username = forms.CharField(label=_('Username')) username = forms.CharField(label=_('Username'))
password = forms.CharField(label=_('Password'), password = forms.CharField(label=_('Password'),
widget=forms.PasswordInput(render_value=True)) widget=forms.PasswordInput(render_value=True))
show_password = forms.BooleanField(label=_('Show password'), show_password = forms.BooleanField(label=_('Show password'),
required=False) required=False)
def __init__(self, *args, **kwargs):
"""Initialize the form, populate interface choices.""" def get_settings(self):
super(AddPPPoEForm, self).__init__(*args, **kwargs) """Return setting dict from cleaned data."""
choices = _get_interface_choices(nm.DeviceType.ETHERNET) settings = super().get_settings()
self.fields['interface'].choices = choices settings['common']['type'] = 'pppoe'
settings['pppoe'] = {
'username': self.cleaned_data['username'],
'password': self.cleaned_data['password'],
}
return settings
def get_ipv4_settings(self):
"""Return IPv4 settings from cleaned data."""
return None
class AddWifiForm(forms.Form): class WifiForm(ConnectionForm):
"""Form to create a new Wi-Fi connection.""" """Form to create/edit a Wi-Fi connection."""
name = forms.CharField(label=_('Connection Name')) field_order = ['name', 'interface', 'zone', 'ssid', 'mode', 'auth_mode',
interface = forms.ChoiceField( 'passphrase', 'ipv4_method', 'ipv4_address', 'ipv4_netmask',
label=_('Physical interface'), 'ipv4_gateway', 'ipv4_dns', 'ipv4_second_dns']
choices=(),
help_text=_('The network device that this connection should be bound '
'to.'))
zone = forms.ChoiceField(
label=_('Firewall Zone'),
help_text=_('The firewall zone will control which services are \
available over this interfaces. Select Internal only for trusted networks.'),
choices=[('external', 'External'), ('internal', 'Internal')])
ssid = forms.CharField( ssid = forms.CharField(
label=_('SSID'), label=_('SSID'),
help_text=_('The visible name of the network.')) help_text=_('The visible name of the network.'))
@ -158,46 +188,21 @@ requires clients to have the password to connect.'),
label=_('Passphrase'), label=_('Passphrase'),
validators=[validators.MinLengthValidator(8)], validators=[validators.MinLengthValidator(8)],
required=False) required=False)
ipv4_method = forms.ChoiceField(
label=_('IPv4 Addressing Method'),
choices=[('auto', 'Automatic (DHCP)'),
('shared', 'Shared'),
('manual', 'Manual')],
help_text=_('Select Automatic (DHCP) if you are connecting to an \
existing wireless network. Shared mode is useful when running an Access \
Point.'))
ipv4_address = forms.CharField(
label=_('Address'),
validators=[validators.validate_ipv4_address],
required=False)
ipv4_netmask = forms.CharField(
label=_('Netmask'),
help_text=_('Optional value. If left blank, a default netmask '
'based on the address will be used.'),
validators=[validators.validate_ipv4_address],
required=False)
ipv4_gateway = forms.CharField(
label=_('Gateway'),
help_text=_('Optional value.'),
validators=[validators.validate_ipv4_address],
required=False)
ipv4_dns = forms.CharField(
label=_('DNS Server'),
help_text=_('Optional value. If this value is given and IPv4 '
'addressing method is "Automatic", the DNS Servers '
'provided by a DHCP server will be ignored.'),
validators=[validators.validate_ipv4_address],
required=False)
ipv4_second_dns = forms.CharField(
label=_('Second DNS Server'),
help_text=_('Optional value. If this value is given and IPv4 '
'Addressing Method is "Automatic", the DNS Servers '
'provided by a DHCP server will be ignored.'),
validators=[validators.validate_ipv4_address],
required=False)
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
"""Initialize the form, populate interface choices.""" """Initialize the form, populate interface choices."""
super(AddWifiForm, self).__init__(*args, **kwargs) super(WifiForm, self).__init__(*args, **kwargs)
choices = _get_interface_choices(nm.DeviceType.WIFI) choices = self._get_interface_choices(nm.DeviceType.WIFI)
self.fields['interface'].choices = choices self.fields['interface'].choices = choices
def get_settings(self):
"""Return setting dict from cleaned data."""
settings = super().get_settings()
settings['common']['type'] = '802-11-wireless'
settings['wireless'] = {
'ssid': self.cleaned_data['ssid'],
'mode': self.cleaned_data['mode'],
'auth_mode': self.cleaned_data['auth_mode'],
'passphrase': self.cleaned_data['passphrase'],
}
return settings

View File

@ -23,8 +23,8 @@ from django.utils.translation import ugettext as _, ugettext_lazy
from django.views.decorators.http import require_POST from django.views.decorators.http import require_POST
from logging import Logger from logging import Logger
from .forms import (ConnectionTypeSelectForm, AddEthernetForm, AddPPPoEForm, from .forms import (ConnectionTypeSelectForm, EthernetForm, PPPoEForm,
AddWifiForm) WifiForm)
from plinth import cfg from plinth import cfg
from plinth import network from plinth import network
from plinth import package from plinth import package
@ -124,45 +124,14 @@ def edit(request, uuid):
if request.method == 'POST': if request.method == 'POST':
if connection.get_connection_type() == '802-11-wireless': if connection.get_connection_type() == '802-11-wireless':
form = AddWifiForm(request.POST) form = WifiForm(request.POST)
elif connection.get_connection_type() == '802-3-ethernet': elif connection.get_connection_type() == '802-3-ethernet':
form = AddEthernetForm(request.POST) form = EthernetForm(request.POST)
elif connection.get_connection_type() == 'pppoe': elif connection.get_connection_type() == 'pppoe':
form = AddPPPoEForm(request.POST) form = PPPoEForm(request.POST)
if form.is_valid(): if form.is_valid():
name = form.cleaned_data['name'] network.edit_connection(connection, form.get_settings())
interface = form.cleaned_data['interface']
zone = form.cleaned_data['zone']
if connection.get_connection_type() == 'pppoe':
username = form.cleaned_data['username']
password = form.cleaned_data['password']
else:
ipv4_method = form.cleaned_data['ipv4_method']
ipv4_address = form.cleaned_data['ipv4_address']
ipv4_netmask = form.cleaned_data['ipv4_netmask']
ipv4_gateway = form.cleaned_data['ipv4_gateway']
ipv4_dns = form.cleaned_data['ipv4_dns']
ipv4_second_dns = form.cleaned_data['ipv4_second_dns']
if connection.get_connection_type() == '802-3-ethernet':
network.edit_ethernet_connection(
connection, name, interface, zone, ipv4_method,
ipv4_address, ipv4_netmask, ipv4_gateway, ipv4_dns,
ipv4_second_dns)
elif connection.get_connection_type() == '802-11-wireless':
ssid = form.cleaned_data['ssid']
mode = form.cleaned_data['mode']
auth_mode = form.cleaned_data['auth_mode']
passphrase = form.cleaned_data['passphrase']
network.edit_wifi_connection(
connection, name, interface, zone, ssid, mode, auth_mode,
passphrase, ipv4_method, ipv4_address, ipv4_netmask,
ipv4_gateway, ipv4_dns, ipv4_second_dns)
elif connection.get_connection_type() == 'pppoe':
network.edit_pppoe_connection(
connection, name, interface, zone, username, password)
return redirect(reverse_lazy('networks:index')) return redirect(reverse_lazy('networks:index'))
else: else:
@ -215,15 +184,15 @@ def edit(request, uuid):
except KeyError: except KeyError:
form_data['auth_mode'] = 'open' form_data['auth_mode'] = 'open'
form = AddWifiForm(form_data) form = WifiForm(form_data)
elif settings_connection.get_connection_type() == '802-3-ethernet': elif settings_connection.get_connection_type() == '802-3-ethernet':
form = AddEthernetForm(form_data) form = EthernetForm(form_data)
elif settings_connection.get_connection_type() == 'pppoe': elif settings_connection.get_connection_type() == 'pppoe':
settings_pppoe = connection.get_setting_pppoe() settings_pppoe = connection.get_setting_pppoe()
form_data['username'] = settings_pppoe.get_username() form_data['username'] = settings_pppoe.get_username()
secrets = connection.get_secrets('pppoe') secrets = connection.get_secrets('pppoe')
form_data['password'] = secrets['pppoe']['password'] form_data['password'] = secrets['pppoe']['password']
form = AddPPPoEForm(form_data) form = PPPoEForm(form_data)
return TemplateResponse(request, 'connections_edit.html', return TemplateResponse(request, 'connections_edit.html',
{'title': _('Edit Connection'), {'title': _('Edit Connection'),
@ -302,24 +271,12 @@ def add_ethernet(request):
form = None form = None
if request.method == 'POST': if request.method == 'POST':
form = AddEthernetForm(request.POST) form = EthernetForm(request.POST)
if form.is_valid(): if form.is_valid():
name = form.cleaned_data['name'] network.add_connection(form.get_settings())
interface = form.cleaned_data['interface']
zone = form.cleaned_data['zone']
ipv4_method = form.cleaned_data['ipv4_method']
ipv4_address = form.cleaned_data['ipv4_address']
ipv4_netmask = form.cleaned_data['ipv4_netmask']
ipv4_gateway = form.cleaned_data['ipv4_gateway']
ipv4_dns = form.cleaned_data['ipv4_dns']
ipv4_second_dns = form.cleaned_data['ipv4_second_dns']
network.add_ethernet_connection(
name, interface, zone, ipv4_method, ipv4_address, ipv4_netmask,
ipv4_gateway, ipv4_dns, ipv4_second_dns)
return redirect(reverse_lazy('networks:index')) return redirect(reverse_lazy('networks:index'))
else: else:
form = AddEthernetForm() form = EthernetForm()
return TemplateResponse(request, 'connections_create.html', return TemplateResponse(request, 'connections_create.html',
{'title': _('Adding New Ethernet Connection'), {'title': _('Adding New Ethernet Connection'),
@ -332,19 +289,12 @@ def add_pppoe(request):
form = None form = None
if request.method == 'POST': if request.method == 'POST':
form = AddPPPoEForm(request.POST) form = PPPoEForm(request.POST)
if form.is_valid(): if form.is_valid():
name = form.cleaned_data['name'] network.add_connection(form.get_settings())
interface = form.cleaned_data['interface']
zone = form.cleaned_data['zone']
username = form.cleaned_data['username']
password = form.cleaned_data['password']
network.add_pppoe_connection(
name, interface, zone, username, password)
return redirect(reverse_lazy('networks:index')) return redirect(reverse_lazy('networks:index'))
else: else:
form = AddPPPoEForm() form = PPPoEForm()
return TemplateResponse(request, 'connections_create.html', return TemplateResponse(request, 'connections_create.html',
{'title': _('Adding New PPPoE Connection'), {'title': _('Adding New PPPoE Connection'),
@ -368,32 +318,15 @@ def add_wifi(request, ssid=None, interface_name=None):
'ipv4_method': 'auto'} 'ipv4_method': 'auto'}
if request.method == 'POST': if request.method == 'POST':
form = AddWifiForm(request.POST) form = WifiForm(request.POST)
if form.is_valid(): if form.is_valid():
name = form.cleaned_data['name'] network.add_connection(form.get_settings())
interface = form.cleaned_data['interface']
zone = form.cleaned_data['zone']
ssid = form.cleaned_data['ssid']
mode = form.cleaned_data['mode']
auth_mode = form.cleaned_data['auth_mode']
passphrase = form.cleaned_data['passphrase']
ipv4_method = form.cleaned_data['ipv4_method']
ipv4_address = form.cleaned_data['ipv4_address']
ipv4_netmask = form.cleaned_data['ipv4_netmask']
ipv4_gateway = form.cleaned_data['ipv4_gateway']
ipv4_dns = form.cleaned_data['ipv4_dns']
ipv4_second_dns = form.cleaned_data['ipv4_second_dns']
network.add_wifi_connection(
name, interface, zone, ssid, mode, auth_mode, passphrase,
ipv4_method, ipv4_address, ipv4_netmask, ipv4_gateway,
ipv4_dns, ipv4_second_dns)
return redirect(reverse_lazy('networks:index')) return redirect(reverse_lazy('networks:index'))
else: else:
if form_data: if form_data:
form = AddWifiForm(form_data) form = WifiForm(form_data)
else: else:
form = AddWifiForm() form = WifiForm()
return TemplateResponse(request, 'connections_create.html', return TemplateResponse(request, 'connections_create.html',
{'title': _('Adding New Wi-Fi Connection'), {'title': _('Adding New Wi-Fi Connection'),

View File

@ -280,8 +280,7 @@ def get_device_by_interface_name(interface_name):
return nm.Client.new(None).get_device_by_iface(interface_name) return nm.Client.new(None).get_device_by_iface(interface_name)
def _update_common_settings(connection, connection_uuid, name, type_, def _update_common_settings(connection, connection_uuid, common):
interface, zone):
"""Create/edit basic settings for network manager connections. """Create/edit basic settings for network manager connections.
Return newly created connection object if connection is None. Return newly created connection object if connection is None.
@ -295,86 +294,62 @@ def _update_common_settings(connection, connection_uuid, name, type_,
connection.add_setting(settings) connection.add_setting(settings)
settings.set_property(nm.SETTING_CONNECTION_UUID, connection_uuid) settings.set_property(nm.SETTING_CONNECTION_UUID, connection_uuid)
settings.set_property(nm.SETTING_CONNECTION_ID, name) settings.set_property(nm.SETTING_CONNECTION_ID, common['name'])
settings.set_property(nm.SETTING_CONNECTION_TYPE, type_) settings.set_property(nm.SETTING_CONNECTION_TYPE, common['type'])
settings.set_property(nm.SETTING_CONNECTION_INTERFACE_NAME, interface) settings.set_property(nm.SETTING_CONNECTION_INTERFACE_NAME,
settings.set_property(nm.SETTING_CONNECTION_ZONE, zone) common['interface'])
settings.set_property(nm.SETTING_CONNECTION_ZONE, common['zone'])
return connection return connection
def _update_ipv4_settings(connection, ipv4_method, ipv4_address, ipv4_netmask, def _update_ipv4_settings(connection, ipv4):
ipv4_gateway, ipv4_dns, ipv4_second_dns):
"""Edit IPv4 settings for network manager connections.""" """Edit IPv4 settings for network manager connections."""
settings = nm.SettingIP4Config.new() settings = nm.SettingIP4Config.new()
connection.add_setting(settings) connection.add_setting(settings)
settings.set_property(nm.SETTING_IP_CONFIG_METHOD, ipv4_method) settings.set_property(nm.SETTING_IP_CONFIG_METHOD, ipv4['method'])
if ipv4_method == nm.SETTING_IP4_CONFIG_METHOD_MANUAL and ipv4_address: if ipv4['method'] == nm.SETTING_IP4_CONFIG_METHOD_MANUAL and \
ipv4_address_int = ipv4_string_to_int(ipv4_address) ipv4['address']:
ipv4_address_int = ipv4_string_to_int(ipv4['address'])
if not ipv4_netmask: if not ipv4['netmask']:
ipv4_netmask_int = nm.utils_ip4_get_default_prefix( ipv4_netmask_int = nm.utils_ip4_get_default_prefix(
ipv4_address_int) ipv4_address_int)
else: else:
ipv4_netmask_int = nm.utils_ip4_netmask_to_prefix( ipv4_netmask_int = nm.utils_ip4_netmask_to_prefix(
ipv4_string_to_int(ipv4_netmask)) ipv4_string_to_int(ipv4['netmask']))
address = nm.IPAddress.new(socket.AF_INET, ipv4_address, address = nm.IPAddress.new(socket.AF_INET, ipv4['address'],
ipv4_netmask_int) ipv4_netmask_int)
settings.add_address(address) settings.add_address(address)
if not ipv4_gateway: if not ipv4['gateway']:
settings.set_property(nm.SETTING_IP_CONFIG_GATEWAY, '0.0.0.0') settings.set_property(nm.SETTING_IP_CONFIG_GATEWAY, '0.0.0.0')
else: else:
settings.set_property(nm.SETTING_IP_CONFIG_GATEWAY, ipv4_gateway) settings.set_property(nm.SETTING_IP_CONFIG_GATEWAY,
ipv4['gateway'])
else: else:
if ipv4_dns or ipv4_second_dns: if ipv4['dns'] or ipv4['second_dns']:
settings.set_property(nm.SETTING_IP_CONFIG_IGNORE_AUTO_DNS, True) settings.set_property(nm.SETTING_IP_CONFIG_IGNORE_AUTO_DNS, True)
if ipv4_dns: if ipv4['dns']:
settings.add_dns(ipv4_dns) settings.add_dns(ipv4['dns'])
if ipv4_second_dns: if ipv4['second_dns']:
settings.add_dns(ipv4_second_dns) settings.add_dns(ipv4['second_dns'])
def _update_ethernet_settings(connection, connection_uuid, name, interface, def _update_pppoe_settings(connection, pppoe):
zone, ipv4_method, ipv4_address, ipv4_netmask,
ipv4_gateway, ipv4_dns, ipv4_second_dns):
"""Create/edit ethernet settings for network manager connections."""
type_ = '802-3-ethernet'
connection = _update_common_settings(connection, connection_uuid, name,
type_, interface, zone)
_update_ipv4_settings(connection, ipv4_method, ipv4_address, ipv4_netmask,
ipv4_gateway, ipv4_dns, ipv4_second_dns)
# Ethernet
settings = connection.get_setting_wired()
if not settings:
settings = nm.SettingWired.new()
connection.add_setting(settings)
return connection
def _update_pppoe_settings(connection, connection_uuid, name, interface, zone,
username, password):
"""Create/edit PPPoE settings for network manager connections.""" """Create/edit PPPoE settings for network manager connections."""
type_ = 'pppoe'
connection = _update_common_settings(connection, connection_uuid, name,
type_, interface, zone)
# PPPoE # PPPoE
settings = connection.get_setting_pppoe() settings = connection.get_setting_pppoe()
if not settings: if not settings:
settings = nm.SettingPppoe.new() settings = nm.SettingPppoe.new()
connection.add_setting(settings) connection.add_setting(settings)
settings.set_property(nm.SETTING_PPPOE_USERNAME, username) settings.set_property(nm.SETTING_PPPOE_USERNAME, pppoe['username'])
settings.set_property(nm.SETTING_PPPOE_PASSWORD, password) settings.set_property(nm.SETTING_PPPOE_PASSWORD, pppoe['password'])
settings = connection.get_setting_ppp() settings = connection.get_setting_ppp()
if not settings: if not settings:
@ -389,118 +364,67 @@ def _update_pppoe_settings(connection, connection_uuid, name, interface, zone,
return connection return connection
def add_pppoe_connection(name, interface, zone, username, password): def _update_wireless_settings(connection, wireless):
"""Add an automatic PPPoE connection in network manager.
Return the UUID for the connection.
"""
connection_uuid = str(uuid.uuid4())
connection = _update_pppoe_settings(
None, connection_uuid, name, interface, zone, username, password)
client = nm.Client.new(None)
client.add_connection_async(connection, True, None, _callback, None)
return connection_uuid
def edit_pppoe_connection(connection, name, interface, zone, username,
password):
"""Edit an existing pppoe connection in network manager."""
_update_pppoe_settings(
connection, connection.get_uuid(), name, interface, zone, username,
password)
connection.commit_changes(True)
def add_ethernet_connection(name, interface, zone, ipv4_method, ipv4_address,
ipv4_netmask, ipv4_gateway, ipv4_dns,
ipv4_second_dns):
"""Add an automatic ethernet connection in network manager.
Return the UUID for the connection.
"""
connection_uuid = str(uuid.uuid4())
connection = _update_ethernet_settings(
None, connection_uuid, name, interface, zone, ipv4_method,
ipv4_address, ipv4_netmask, ipv4_gateway, ipv4_dns, ipv4_second_dns)
client = nm.Client.new(None)
client.add_connection_async(connection, True, None, _callback, None)
return connection_uuid
def edit_ethernet_connection(connection, name, interface, zone, ipv4_method,
ipv4_address, ipv4_netmask, ipv4_gateway,
ipv4_dns, ipv4_second_dns):
"""Edit an existing ethernet connection in network manager."""
_update_ethernet_settings(
connection, connection.get_uuid(), name, interface, zone, ipv4_method,
ipv4_address, ipv4_netmask, ipv4_gateway, ipv4_dns, ipv4_second_dns)
connection.commit_changes(True)
def _update_wifi_settings(connection, connection_uuid, name, interface, zone,
ssid, mode, auth_mode, passphrase, ipv4_method,
ipv4_address, ipv4_netmask, ipv4_gateway, ipv4_dns,
ipv4_second_dns):
"""Create/edit wifi settings for network manager connections.""" """Create/edit wifi settings for network manager connections."""
type_ = '802-11-wireless'
key_mgmt = 'wpa-psk' key_mgmt = 'wpa-psk'
connection = _update_common_settings(connection, connection_uuid, name,
type_, interface, zone)
_update_ipv4_settings(connection, ipv4_method, ipv4_address, ipv4_netmask,
ipv4_gateway, ipv4_dns, ipv4_second_dns)
# Wireless # Wireless
settings = connection.get_setting_wireless() settings = connection.get_setting_wireless()
if not settings: if not settings:
settings = nm.SettingWireless.new() settings = nm.SettingWireless.new()
connection.add_setting(settings) connection.add_setting(settings)
ssid_gbytes = glib.Bytes.new(ssid.encode()) ssid_gbytes = glib.Bytes.new(wireless['ssid'].encode())
settings.set_property(nm.SETTING_WIRELESS_SSID, ssid_gbytes) settings.set_property(nm.SETTING_WIRELESS_SSID, ssid_gbytes)
settings.set_property(nm.SETTING_WIRELESS_MODE, mode) settings.set_property(nm.SETTING_WIRELESS_MODE, wireless['mode'])
# Wireless Security # Wireless Security
if auth_mode == 'wpa' and passphrase: if wireless['auth_mode'] == 'wpa' and wireless['passphrase']:
settings = connection.get_setting_wireless_security() settings = connection.get_setting_wireless_security()
if not settings: if not settings:
settings = nm.SettingWirelessSecurity.new() settings = nm.SettingWirelessSecurity.new()
connection.add_setting(settings) connection.add_setting(settings)
settings.set_property(nm.SETTING_WIRELESS_SECURITY_KEY_MGMT, key_mgmt) settings.set_property(nm.SETTING_WIRELESS_SECURITY_KEY_MGMT, key_mgmt)
settings.set_property(nm.SETTING_WIRELESS_SECURITY_PSK, passphrase) settings.set_property(nm.SETTING_WIRELESS_SECURITY_PSK,
wireless['passphrase'])
else: else:
connection.remove_setting(nm.SettingWirelessSecurity) connection.remove_setting(nm.SettingWirelessSecurity)
return connection return connection
def add_wifi_connection(name, interface, zone, ssid, mode, auth_mode, def _update_settings(connection, connection_uuid, settings):
passphrase, ipv4_method, ipv4_address, ipv4_netmask, """Create/edit wifi settings for network manager connections."""
ipv4_gateway, ipv4_dns, ipv4_second_dns): connection = _update_common_settings(connection, connection_uuid,
"""Add an automatic Wi-Fi connection in network manager. settings['common'])
if 'ipv4' in settings and settings['ipv4']:
_update_ipv4_settings(connection, settings['ipv4'])
if 'pppoe' in settings and settings['pppoe']:
_update_pppoe_settings(connection, settings['pppoe'])
if 'wireless' in settings and settings['wireless']:
_update_wireless_settings(connection, settings['wireless'])
return connection
def add_connection(settings):
"""Add an connection in network manager.
Return the UUID for the connection. Return the UUID for the connection.
""" """
connection_uuid = str(uuid.uuid4()) connection_uuid = str(uuid.uuid4())
connection = _update_wifi_settings( connection = _update_settings(None, connection_uuid, settings)
None, connection_uuid, name, interface, zone, ssid, mode, auth_mode,
passphrase, ipv4_method, ipv4_address, ipv4_netmask, ipv4_gateway,
ipv4_dns, ipv4_second_dns)
client = nm.Client.new(None) client = nm.Client.new(None)
client.add_connection_async(connection, True, None, _callback, None) client.add_connection_async(connection, True, None, _callback, None)
return connection_uuid return connection_uuid
def edit_wifi_connection(connection, name, interface, zone, ssid, mode, def edit_connection(connection, settings):
auth_mode, passphrase, ipv4_method, ipv4_address, """Edit an existing connection in network manager."""
ipv4_netmask, ipv4_gateway, ipv4_dns, _update_settings(connection, connection.get_uuid(), settings)
ipv4_second_dns):
"""Edit an existing wifi connection in network manager."""
_update_wifi_settings(
connection, connection.get_uuid(), name, interface, zone, ssid, mode,
auth_mode, passphrase, ipv4_method, ipv4_address, ipv4_netmask,
ipv4_gateway, ipv4_dns, ipv4_second_dns)
connection.commit_changes(True) connection.commit_changes(True)